Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

MUL-8516 feat(apps): redesign Connected Apps — team accounts, per-agent apps, confirmations (#9849)

Jiayuan Zhangbc5b792db247
diff --git a/apps/mobile/components/inbox/detail-label.tsx b/apps/mobile/components/inbox/detail-label.tsx
index 7d577fd439..16aaca336e 100644
--- a/apps/mobile/components/inbox/detail-label.tsx
+++ b/apps/mobile/components/inbox/detail-label.tsx
@@ -57,6 +57,10 @@ const TYPE_KEY: Record<InboxItemType, string> = {
autopilot_paused: "type.autopilot_paused",
autopilot_quota_exceeded: "type.autopilot_quota_exceeded",
children_done: "type.children_done",
+ app_action_requested: "type.app_action_requested",
+ app_action_reminder: "type.app_action_reminder",
+ app_connect_requested: "type.app_connect_requested",
+ app_action_result: "type.app_action_result",
};
// due_date is a calendar day — format timezone-safely (no offset day shift).
diff --git a/apps/mobile/locales/en/inbox.json b/apps/mobile/locales/en/inbox.json
index 62520d96d6..65b8eac0fe 100644
--- a/apps/mobile/locales/en/inbox.json
+++ b/apps/mobile/locales/en/inbox.json
@@ -75,7 +75,11 @@
"reacted_with": "Reacted with {{emoji}}",
"created_with_agent": "Created with agent: {{identifier}}",
"failed_with_detail": "Failed: {{detail}}",
- "run_limit_blocked": "Run blocked because the limit was reached"
+ "run_limit_blocked": "Run blocked because the limit was reached",
+ "app_action_requested": "Needs your confirmation",
+ "app_action_reminder": "Confirmation expiring soon",
+ "app_connect_requested": "Connect an app",
+ "app_action_result": "App action result"
},
"body": {
"autopilot_title_limit": "Autopilot \"{{title}}\" was not started because this workspace has reached its limit of {{limit}} runs for the current period. The allowance resets {{resetAt}}.",
diff --git a/apps/mobile/locales/zh-Hans/inbox.json b/apps/mobile/locales/zh-Hans/inbox.json
index 4c95d9d92a..1a98f8f71c 100644
--- a/apps/mobile/locales/zh-Hans/inbox.json
+++ b/apps/mobile/locales/zh-Hans/inbox.json
@@ -75,7 +75,11 @@
"reacted_with": "回应了 {{emoji}}",
"created_with_agent": "由智能体创建:{{identifier}}",
"failed_with_detail": "失败:{{detail}}",
- "run_limit_blocked": "已达到上限,本次运行被阻止"
+ "run_limit_blocked": "已达到上限,本次运行被阻止",
+ "app_action_requested": "等待你确认",
+ "app_action_reminder": "确认即将过期",
+ "app_connect_requested": "请连接应用",
+ "app_action_result": "应用操作结果"
},
"body": {
"autopilot_title_limit": "自动化 \"{{title}}\" 未启动,因为该工作区已达到当前周期 {{limit}} 次运行的上限。额度将在 {{resetAt}} 重置。",
diff --git a/apps/mobile/locales/zh-Hant/inbox.json b/apps/mobile/locales/zh-Hant/inbox.json
index 657378c89c..6d39109bdd 100644
--- a/apps/mobile/locales/zh-Hant/inbox.json
+++ b/apps/mobile/locales/zh-Hant/inbox.json
@@ -75,7 +75,11 @@
"reacted_with": "回應了 {{emoji}}",
"created_with_agent": "由 AI 代理建立:{{identifier}}",
"failed_with_detail": "失敗:{{detail}}",
- "run_limit_blocked": "已達到上限,本次執行被阻止"
+ "run_limit_blocked": "已達到上限,本次執行被阻止",
+ "app_action_requested": "等待你確認",
+ "app_action_reminder": "確認即將過期",
+ "app_connect_requested": "請連線應用",
+ "app_action_result": "應用操作結果"
},
"body": {
"autopilot_title_limit": "自動化 \"{{title}}\" 未啟動,因為該工作區已達到當前週期 {{limit}} 次執行的上限。額度將在 {{resetAt}} 重置。",
diff --git a/packages/core/api/client.ts b/packages/core/api/client.ts
index 1964caa76e..a948ee7663 100644
--- a/packages/core/api/client.ts
+++ b/packages/core/api/client.ts
@@ -198,6 +198,21 @@ import type {
ComposioToolkit,
ComposioConnection,
ComposioConnectInitResponse,
+ AppsOverview,
+ AppCatalogResponse,
+ AppRule,
+ AppTool,
+ AppToolCall,
+ IssueAppCall,
+ AppRequestList,
+ TeamAppImpact,
+ AppRequest,
+ AgentApp,
+ AppAccountScope,
+ AppActionClass,
+ AppActionPolicy,
+ AppCatalogMode,
+ UpdateAgentAppsRequest,
SlackInstallation,
ListSlackInstallationsResponse,
RegisterSlackBYORequest,
@@ -422,6 +437,21 @@ import {
InboxUnreadSummarySchema,
EMPTY_INBOX_UNREAD_SUMMARY,
IssueUnreadPageSchema,
+ AgentAppsResponseSchema,
+ AppActivityResponseSchema,
+ AppCatalogResponseSchema,
+ AppConnectInitSchema,
+ AppRequestListSchema,
+ AppRequestSchema,
+ AppRulesResponseSchema,
+ AppSettingsResponseSchema,
+ AppToolsResponseSchema,
+ AppsOverviewSchema,
+ EMPTY_APP_CATALOG,
+ EMPTY_APPS_OVERVIEW,
+ EMPTY_TEAM_APP_IMPACT,
+ IssueAppCallsResponseSchema,
+ TeamAppImpactSchema,
EMPTY_ISSUE_UNREAD_PAGE,
SubscribedIssueIdsSchema,
IssueInboxReadSchema,
@@ -5329,6 +5359,143 @@ export class ApiClient {
});
}
+ // Connected Apps (MUL-8516). Workspace-scoped: team accounts belong to the
+ // workspace, personal accounts to the caller.
+
+ async getAppsOverview(): Promise<AppsOverview> {
+ const raw = await this.fetch<unknown>(`/api/apps`);
+ return parseWithFallback(raw, AppsOverviewSchema, EMPTY_APPS_OVERVIEW, { endpoint: "GET /api/apps" });
+ }
+
+ /** The workspace's catalog; `view: "all"` (admins) lists every app with
+ * whether the catalog allows it. */
+ async listAppCatalog(view?: "all"): Promise<AppCatalogResponse> {
+ const raw = await this.fetch<unknown>(`/api/apps/catalog${view ? `?view=${view}` : ""}`);
+ return parseWithFallback(raw, AppCatalogResponseSchema, EMPTY_APP_CATALOG, { endpoint: "GET /api/apps/catalog" });
+ }
+
+ /** Starts connecting an account; the browser is sent to the returned URL
+ * and comes back to `returnTo` (an app path) when given. */
+ async connectApp(scope: AppAccountScope, toolkitSlug: string, returnTo?: string): Promise<ComposioConnectInitResponse> {
+ const raw = await this.fetch<unknown>(`/api/apps/${scope}/connect`, {
+ method: "POST",
+ body: JSON.stringify({ toolkit_slug: toolkitSlug, ...(returnTo ? { return_to: returnTo } : {}) }),
+ });
+ const endpoint = `POST /api/apps/${scope}/connect`;
+ const parsed = parseWithFallback<ComposioConnectInitResponse | null>(raw, AppConnectInitSchema, null, { endpoint });
+ if (!parsed) throw new Error(`Malformed response from ${endpoint}`);
+ return parsed;
+ }
+
+ async disconnectTeamApp(connectionId: string): Promise<void> {
+ await this.fetch(`/api/apps/team/connections/${connectionId}`, { method: "DELETE" });
+ }
+
+ async getTeamAppImpact(toolkitSlug: string): Promise<TeamAppImpact> {
+ const raw = await this.fetch<unknown>(`/api/apps/team/impact?toolkit_slug=${encodeURIComponent(toolkitSlug)}`);
+ return parseWithFallback(raw, TeamAppImpactSchema, EMPTY_TEAM_APP_IMPACT, { endpoint: "GET /api/apps/team/impact" });
+ }
+
+ // Write responses parse to null when malformed; callers refetch instead of
+ // caching a guess.
+
+ async updateAppSettings(body: {
+ catalog_mode: AppCatalogMode;
+ allowed_toolkits?: string[];
+ }): Promise<{ catalog_mode: AppCatalogMode; allowed_toolkits: string[] } | null> {
+ const raw = await this.fetch<unknown>(`/api/apps/settings`, {
+ method: "PUT",
+ body: JSON.stringify(body),
+ });
+ return parseWithFallback(raw, AppSettingsResponseSchema, null, { endpoint: "PUT /api/apps/settings" });
+ }
+
+ async listAppTools(toolkitSlug: string): Promise<{ tools: AppTool[] }> {
+ const raw = await this.fetch<unknown>(`/api/apps/tools?toolkit_slug=${encodeURIComponent(toolkitSlug)}`);
+ return parseWithFallback(raw, AppToolsResponseSchema, { tools: [] }, { endpoint: "GET /api/apps/tools" });
+ }
+
+ /** Corrects one tool's class; `null` restores the automatic class. */
+ async updateAppToolClass(toolkitSlug: string, toolSlug: string, actionClass: AppActionClass | null): Promise<void> {
+ await this.fetch(`/api/apps/tools/class`, {
+ method: "PUT",
+ body: JSON.stringify({ toolkit_slug: toolkitSlug, tool_slug: toolSlug, action_class: actionClass ?? "" }),
+ });
+ }
+
+ async listIssueAppCalls(issueId: string): Promise<{ calls: IssueAppCall[] }> {
+ const raw = await this.fetch<unknown>(`/api/app-calls?issue_id=${encodeURIComponent(issueId)}`);
+ return parseWithFallback(raw, IssueAppCallsResponseSchema, { calls: [] }, { endpoint: "GET /api/app-calls" });
+ }
+
+ async getAppRules(toolkitSlug: string, scope: AppAccountScope): Promise<{ rules: AppRule[] }> {
+ const raw = await this.fetch<unknown>(`/api/apps/rules?toolkit_slug=${encodeURIComponent(toolkitSlug)}&scope=${scope}`);
+ return parseWithFallback(raw, AppRulesResponseSchema, { rules: [] }, { endpoint: "GET /api/apps/rules" });
+ }
+
+ async updateAppRules(
+ toolkitSlug: string,
+ scope: AppAccountScope,
+ rules: { action_class: AppActionClass; policy: AppActionPolicy }[],
+ ): Promise<{ rules: AppRule[] } | null> {
+ const raw = await this.fetch<unknown>(`/api/apps/rules?toolkit_slug=${encodeURIComponent(toolkitSlug)}&scope=${scope}`, {
+ method: "PUT",
+ body: JSON.stringify({ rules }),
+ });
+ return parseWithFallback(raw, AppRulesResponseSchema, null, { endpoint: "PUT /api/apps/rules" });
+ }
+
+ async listAppActivity(toolkitSlug: string, scope: AppAccountScope): Promise<{ calls: AppToolCall[] }> {
+ const raw = await this.fetch<unknown>(`/api/apps/activity?toolkit_slug=${encodeURIComponent(toolkitSlug)}&scope=${scope}`);
+ return parseWithFallback(raw, AppActivityResponseSchema, { calls: [] }, { endpoint: "GET /api/apps/activity" });
+ }
+
+ async listAgentApps(agentId: string): Promise<{ apps: AgentApp[] }> {
+ const raw = await this.fetch<unknown>(`/api/agents/${agentId}/apps`);
+ return parseWithFallback(raw, AgentAppsResponseSchema, { apps: [] }, { endpoint: "GET /api/agents/:id/apps" });
+ }
+
+ async updateAgentApps(agentId: string, body: UpdateAgentAppsRequest): Promise<{ apps: AgentApp[] } | null> {
+ const raw = await this.fetch<unknown>(`/api/agents/${agentId}/apps`, {
+ method: "PUT",
+ body: JSON.stringify(body),
+ });
+ return parseWithFallback(raw, AgentAppsResponseSchema, null, { endpoint: "PUT /api/agents/:id/apps" });
+ }
+
+ /** Requests of an issue, of a chat, or (neither given) the caller's
+ * pending ones. The first page holds every pending request and the newest
+ * decided ones; `before` (a `next_before`) pages back through history. */
+ async listAppRequests(
+ params: { issueId?: string; chatSessionId?: string; before?: string } = {},
+ ): Promise<AppRequestList> {
+ const qs = new URLSearchParams();
+ if (params.issueId) qs.set("issue_id", params.issueId);
+ if (params.chatSessionId) qs.set("chat_session_id", params.chatSessionId);
+ if (params.before) qs.set("before", params.before);
+ const query = qs.toString();
+ const raw = await this.fetch<unknown>(`/api/app-requests${query ? `?${query}` : ""}`);
+ return parseWithFallback(raw, AppRequestListSchema, { requests: [], next_before: null }, {
+ endpoint: "GET /api/app-requests",
+ });
+ }
+
+ async approveAppRequest(requestId: string, args?: Record<string, unknown>): Promise<AppRequest | null> {
+ const raw = await this.fetch<unknown>(`/api/app-requests/${requestId}/approve`, {
+ method: "POST",
+ body: JSON.stringify(args ? { arguments: args } : {}),
+ });
+ return parseWithFallback(raw, AppRequestSchema, null, { endpoint: "POST /api/app-requests/:id/approve" });
+ }
+
+ async rejectAppRequest(requestId: string, reason?: string): Promise<AppRequest | null> {
+ const raw = await this.fetch<unknown>(`/api/app-requests/${requestId}/reject`, {
+ method: "POST",
+ body: JSON.stringify(reason ? { reason } : {}),
+ });
+ return parseWithFallback(raw, AppRequestSchema, null, { endpoint: "POST /api/app-requests/:id/reject" });
+ }
+
// Slack integration (MUL-3666)
async listSlackInstallations(workspaceId: string): Promise<ListSlackInstallationsResponse> {
return this.fetch(`/api/workspaces/${workspaceId}/slack/installations`);
diff --git a/packages/core/api/connected-apps.test.ts b/packages/core/api/connected-apps.test.ts
new file mode 100644
index 0000000000..21b59f4bc1
--- /dev/null
+++ b/packages/core/api/connected-apps.test.ts
@@ -0,0 +1,124 @@
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { ApiClient } from "./client";
+import { EMPTY_APPS_OVERVIEW } from "./schemas";
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+});
+
+function respondWith(body: unknown) {
+ const fetchMock = vi.fn().mockResolvedValue(
+ new Response(JSON.stringify(body), { status: 200, headers: { "Content-Type": "application/json" } }),
+ );
+ vi.stubGlobal("fetch", fetchMock);
+ return { client: new ApiClient("https://api.example.test"), fetchMock };
+}
+
+const request = {
+ id: "r1",
+ kind: "action",
+ status: "pending",
+ agent_id: "a1",
+ issue_id: "i1",
+ approver_user_id: "u1",
+ account_scope: "personal",
+ toolkit_slug: "gmail",
+ tool_slug: "GMAIL_SEND_EMAIL",
+ action_class: "send",
+ summary: "Send the report",
+ arguments: { to: "[email protected]" },
+ error: null,
+ reason: null,
+ redacted: false,
+ expires_at: "2026-11-05T00:00:00Z",
+ decided_by: null,
+ decided_at: null,
+ created_at: "2026-11-04T00:00:00Z",
+};
+
+describe("Connected Apps API parsing", () => {
+ it("reads the overview and falls back to empty when it is malformed", async () => {
+ let { client } = respondWith({
+ catalog_mode: "custom",
+ allowed_toolkits: ["gmail"],
+ can_manage: true,
+ team: [],
+ personal: [{ id: "c1", toolkit_slug: "gmail", status: "active", connected_at: "t", last_used_at: null }],
+ agent_apps: [{ agent_id: "a1", toolkit_slug: "gmail", account_scope: "personal", level: "write" }],
+ });
+ const overview = await client.getAppsOverview();
+ expect(overview.catalog_mode).toBe("custom");
+ expect(overview.personal[0]?.connected_by).toBeNull();
+ expect(overview.agent_apps[0]?.level).toBe("write");
+
+ ({ client } = respondWith({ team: "nope" }));
+ expect(await client.getAppsOverview()).toEqual(EMPTY_APPS_OVERVIEW);
+ });
+
+ it("maps enum values this client does not know to the cautious ones", async () => {
+ const { client } = respondWith({
+ catalog_mode: "future_mode",
+ team: [],
+ personal: [],
+ agent_apps: [{ agent_id: "a1", toolkit_slug: "gmail", account_scope: "org", level: "admin" }],
+ });
+ const overview = await client.getAppsOverview();
+ expect(overview.catalog_mode).toBe("curated");
+ expect(overview.can_manage).toBe(false);
+ expect(overview.agent_apps[0]).toMatchObject({ account_scope: "personal", level: "confirm_writes" });
+ });
+
+ it("keeps request details hidden unless the server says otherwise", async () => {
+ const { redacted: _redacted, arguments: _args, ...rest } = request;
+ const { client } = respondWith({ requests: [{ ...rest, action_class: "transfer_funds" }], next_before: "2026-11-01T00:00:00Z" });
+ const page = await client.listAppRequests({ issueId: "i1" });
+ expect(page.next_before).toBe("2026-11-01T00:00:00Z");
+ expect(page.requests[0]).toMatchObject({ redacted: true, action_class: "send", chat_session_id: null });
+ });
+
+ it("sends the history cursor and tolerates a malformed list", async () => {
+ const { client, fetchMock } = respondWith({ requests: [{ id: 1 }] });
+ const page = await client.listAppRequests({ issueId: "i1", before: "2026-11-01T00:00:00Z" });
+ expect(String(fetchMock.mock.calls[0]?.[0])).toContain("before=2026-11-01T00%3A00%3A00Z");
+ expect(page).toEqual({ requests: [], next_before: null });
+ });
+
+ it("returns null from writes whose response is malformed, so callers refetch", async () => {
+ let { client } = respondWith({ id: "r1" });
+ expect(await client.approveAppRequest("r1")).toBeNull();
+ ({ client } = respondWith({ apps: [{ toolkit_slug: 5 }] }));
+ expect(await client.updateAgentApps("a1", { apps: [] })).toBeNull();
+ ({ client } = respondWith({ rules: "x" }));
+ expect(await client.updateAppRules("gmail", "personal", [])).toBeNull();
+ ({ client } = respondWith(request));
+ expect(await client.rejectAppRequest("r1")).toMatchObject({ id: "r1", redacted: false });
+ });
+
+ it("refuses to redirect without a connect URL", async () => {
+ let { client } = respondWith({});
+ await expect(client.connectApp("personal", "gmail", "/ws/issues/1")).rejects.toThrow(/malformed/i);
+ const ok = respondWith({ redirect_url: "https://connect.example.test" });
+ client = ok.client;
+ expect(await client.connectApp("personal", "gmail", "/ws/issues/1")).toEqual({ redirect_url: "https://connect.example.test" });
+ expect(JSON.parse(String(ok.fetchMock.mock.calls[0]?.[1]?.body))).toEqual({ toolkit_slug: "gmail", return_to: "/ws/issues/1" });
+ });
+
+ it("parses tools and issue calls, dropping malformed pages", async () => {
+ let { client } = respondWith({
+ tools: [{ slug: "GMAIL_SEND_EMAIL", name: "Send", auto_class: "send", class: "unknown", overridden: true }],
+ });
+ expect((await client.listAppTools("gmail")).tools[0]).toMatchObject({ class: "send", description: "" });
+ ({ client } = respondWith({ tools: null }));
+ expect(await client.listAppTools("gmail")).toEqual({ tools: [] });
+
+ ({ client } = respondWith({
+ calls: [{
+ id: "c1", agent_id: "a1", account_scope: "team", toolkit_slug: "gmail", tool_slug: "GMAIL_SEND_EMAIL",
+ action_class: "send", outcome: "rate_limited", created_at: "t",
+ }],
+ }));
+ expect((await client.listIssueAppCalls("i1")).calls[0]).toMatchObject({ task_id: null, error: null, outcome: "rate_limited" });
+ ({ client } = respondWith("oops"));
+ expect(await client.listIssueAppCalls("i1")).toEqual({ calls: [] });
+ });
+});
diff --git a/packages/core/api/schemas.ts b/packages/core/api/schemas.ts
index c3b86ff82b..4e9ac0eec7 100644
--- a/packages/core/api/schemas.ts
+++ b/packages/core/api/schemas.ts
@@ -1,6 +1,9 @@
import { z } from "zod";
import { normalizeIssueStatusCategory } from "../issues/config/status";
import type {
+ AppCatalogResponse,
+ AppsOverview,
+ TeamAppImpact,
WorkflowHandoffPreview,
IssueWorkflow,
IssueWorkflowDryRunResponse,
@@ -4074,6 +4077,177 @@ export const EMPTY_LIST_LARK_INSTALLATIONS_RESPONSE: ListLarkInstallationsRespon
configured: false,
};
+// Connected Apps (MUL-8516). Enum fields the UI indexes into label tables
+// fall back to their most cautious value, so a value this client does not
+// know yet renders as something safe instead of a missing label; statuses
+// and outcomes stay strings because their renderers already handle unknowns.
+
+const appNullableString = z.string().nullish().transform((v) => v ?? null);
+const AppAccountScopeSchema = z.enum(["team", "personal"]).catch("personal");
+const AppAccessLevelSchema = z.enum(["read", "confirm_writes", "write"]).catch("confirm_writes");
+const AppActionClassSchema = z.enum(["read", "write", "send", "delete", "share"]).catch("send");
+const AppActionPolicySchema = z.enum(["allow", "confirm", "block"]).catch("confirm");
+const AppCatalogModeSchema = z.enum(["all", "curated", "custom"]).catch("curated");
+
+const AppConnectionSchema = z.object({
+ id: z.string(),
+ toolkit_slug: z.string(),
+ status: z.string().default("active"),
+ connected_by: appNullableString,
+ connected_at: z.string().default(""),
+ last_used_at: appNullableString,
+}).loose();
+
+const AgentAppSchema = z.object({
+ agent_id: z.string(),
+ toolkit_slug: z.string(),
+ account_scope: AppAccountScopeSchema,
+ level: AppAccessLevelSchema,
+}).loose();
+
+export const AppsOverviewSchema = z.object({
+ catalog_mode: AppCatalogModeSchema,
+ allowed_toolkits: z.array(z.string()).default([]).catch([]),
+ can_manage: z.boolean().default(false).catch(false),
+ team: z.array(AppConnectionSchema).default([]),
+ personal: z.array(AppConnectionSchema).default([]),
+ agent_apps: z.array(AgentAppSchema).default([]),
+}).loose();
+
+const AppCatalogEntrySchema = z.object({
+ slug: z.string(),
+ name: z.string().default(""),
+ logo: z.string().optional().catch(undefined),
+ category: z.string().optional().catch(undefined),
+ curated: z.boolean().default(false).catch(false),
+ recommended_scope: AppAccountScopeSchema.optional(),
+ allowed: z.boolean().optional().catch(undefined),
+}).loose();
+
+export const AppCatalogResponseSchema = z.object({
+ catalog_mode: AppCatalogModeSchema,
+ apps: z.array(AppCatalogEntrySchema).default([]),
+}).loose();
+
+export const AppSettingsResponseSchema = z.object({
+ catalog_mode: AppCatalogModeSchema,
+ allowed_toolkits: z.array(z.string()).default([]).catch([]),
+}).loose();
+
+export const AppRulesResponseSchema = z.object({
+ rules: z.array(z.object({
+ action_class: AppActionClassSchema,
+ policy: AppActionPolicySchema,
+ default_policy: AppActionPolicySchema,
+ custom: z.boolean().default(false).catch(false),
+ }).loose()).default([]),
+}).loose();
+
+export const AppActivityResponseSchema = z.object({
+ calls: z.array(z.object({
+ id: z.string(),
+ agent_id: z.string(),
+ issue_id: appNullableString,
+ chat_session_id: appNullableString,
+ triggered_by: appNullableString,
+ tool_slug: z.string(),
+ action_class: AppActionClassSchema,
+ outcome: z.string(),
+ error: appNullableString,
+ created_at: z.string(),
+ }).loose()).default([]),
+}).loose();
+
+export const TeamAppImpactSchema = z.object({
+ agents: z.array(z.object({ id: z.string(), name: z.string().default("") }).loose()).default([]),
+ active_tasks: z.number().default(0).catch(0),
+ active_autopilots: z.number().default(0).catch(0),
+ pending_requests: z.number().default(0).catch(0),
+}).loose();
+
+export const AgentAppsResponseSchema = z.object({
+ apps: z.array(AgentAppSchema).default([]),
+}).loose();
+
+export const AppRequestSchema = z.object({
+ id: z.string(),
+ kind: z.enum(["action", "connect"]).catch("action"),
+ status: z.string(),
+ agent_id: z.string(),
+ issue_id: appNullableString,
+ chat_session_id: appNullableString,
+ approver_user_id: z.string(),
+ account_scope: AppAccountScopeSchema,
+ toolkit_slug: z.string(),
+ tool_slug: z.string().default(""),
+ action_class: AppActionClassSchema,
+ summary: z.string().default(""),
+ arguments: z.record(z.string(), z.unknown()).optional().catch(undefined),
+ approved_arguments: z.record(z.string(), z.unknown()).optional().catch(undefined),
+ result: z.unknown().optional(),
+ error: appNullableString,
+ reason: appNullableString,
+ // Withhold the details unless the server said otherwise.
+ redacted: z.boolean().default(true).catch(true),
+ expires_at: z.string(),
+ decided_by: appNullableString,
+ decided_at: appNullableString,
+ created_at: z.string(),
+}).loose();
+
+export const AppRequestListSchema = z.object({
+ requests: z.array(AppRequestSchema).default([]),
+ next_before: appNullableString,
+}).loose();
+
+export const AppToolsResponseSchema = z.object({
+ tools: z.array(z.object({
+ slug: z.string(),
+ name: z.string().default(""),
+ description: z.string().default(""),
+ auto_class: AppActionClassSchema,
+ class: AppActionClassSchema,
+ overridden: z.boolean().default(false).catch(false),
+ }).loose()).default([]),
+}).loose();
+
+export const IssueAppCallsResponseSchema = z.object({
+ calls: z.array(z.object({
+ id: z.string(),
+ task_id: appNullableString,
+ agent_id: z.string(),
+ account_scope: AppAccountScopeSchema,
+ account_owner_user_id: appNullableString,
+ toolkit_slug: z.string(),
+ tool_slug: z.string(),
+ action_class: AppActionClassSchema,
+ outcome: z.string(),
+ request_id: appNullableString,
+ error: appNullableString,
+ created_at: z.string(),
+ }).loose()).default([]),
+}).loose();
+
+export const AppConnectInitSchema = z.object({ redirect_url: z.string().min(1) }).loose();
+
+export const EMPTY_APPS_OVERVIEW: AppsOverview = {
+ catalog_mode: "curated",
+ allowed_toolkits: [],
+ can_manage: false,
+ team: [],
+ personal: [],
+ agent_apps: [],
+};
+
+export const EMPTY_APP_CATALOG: AppCatalogResponse = { catalog_mode: "curated", apps: [] };
+
+export const EMPTY_TEAM_APP_IMPACT: TeamAppImpact = {
+ agents: [],
+ active_tasks: 0,
+ active_autopilots: 0,
+ pending_requests: 0,
+};
+
// Only `pinned_at` is new here; every other field keeps its pre-schema
// leniency so one odd workspace can never empty the whole switcher.
export const WorkspaceListItemSchema = z.object({
diff --git a/packages/core/connected-apps/index.ts b/packages/core/connected-apps/index.ts
new file mode 100644
index 0000000000..a6cefca2fd
--- /dev/null
+++ b/packages/core/connected-apps/index.ts
@@ -0,0 +1,22 @@
+export {
+ connectedAppsKeys,
+ appsOverviewOptions,
+ appCatalogOptions,
+ fullAppCatalogOptions,
+ appToolsOptions,
+ issueAppCallsOptions,
+ appRulesOptions,
+ appActivityOptions,
+ teamAppImpactOptions,
+ agentAppsOptions,
+ issueAppRequestsOptions,
+ chatAppRequestsOptions,
+} from "./queries";
+export {
+ useUpdateAppSettings,
+ useUpdateAppRules,
+ useUpdateAppToolClass,
+ useDisconnectTeamApp,
+ useUpdateAgentApps,
+ useDecideAppRequest,
+} from "./mutations";
diff --git a/packages/core/connected-apps/mutations.ts b/packages/core/connected-apps/mutations.ts
new file mode 100644
index 0000000000..2f7b2c9cde
--- /dev/null
+++ b/packages/core/connected-apps/mutations.ts
@@ -0,0 +1,86 @@
+import { useMutation, useQueryClient } from "@tanstack/react-query";
+import { api } from "../api";
+import { useWorkspaceId } from "../hooks";
+import type {
+ AppAccountScope,
+ AppActionClass,
+ AppActionPolicy,
+ AppCatalogMode,
+ UpdateAgentAppsRequest,
+} from "../types";
+import { workspaceKeys } from "../workspace/queries";
+import { connectedAppsKeys } from "./queries";
+
+export function useUpdateAppSettings() {
+ const qc = useQueryClient();
+ const wsId = useWorkspaceId();
+ return useMutation({
+ mutationFn: (body: { catalog_mode: AppCatalogMode; allowed_toolkits?: string[] }) =>
+ api.updateAppSettings(body),
+ onSettled: () => qc.invalidateQueries({ queryKey: connectedAppsKeys.all(wsId) }),
+ });
+}
+
+export function useUpdateAppRules(slug: string, scope: AppAccountScope) {
+ const qc = useQueryClient();
+ const wsId = useWorkspaceId();
+ return useMutation({
+ mutationFn: (rules: { action_class: AppActionClass; policy: AppActionPolicy }[]) =>
+ api.updateAppRules(slug, scope, rules),
+ onSuccess: (data) => {
+ if (data) qc.setQueryData(connectedAppsKeys.rules(wsId, slug, scope), data.rules);
+ else void qc.invalidateQueries({ queryKey: connectedAppsKeys.rules(wsId, slug, scope) });
+ },
+ });
+}
+
+export function useUpdateAppToolClass(slug: string) {
+ const qc = useQueryClient();
+ const wsId = useWorkspaceId();
+ return useMutation({
+ mutationFn: ({ tool, actionClass }: { tool: string; actionClass: AppActionClass | null }) =>
+ api.updateAppToolClass(slug, tool, actionClass),
+ onSettled: () => qc.invalidateQueries({ queryKey: connectedAppsKeys.tools(wsId, slug) }),
+ });
+}
+
+export function useDisconnectTeamApp() {
+ const qc = useQueryClient();
+ const wsId = useWorkspaceId();
+ return useMutation({
+ mutationFn: (connectionId: string) => api.disconnectTeamApp(connectionId),
+ onSettled: () => qc.invalidateQueries({ queryKey: connectedAppsKeys.all(wsId) }),
+ });
+}
+
+/** Replaces an agent's apps. The legacy `composio_toolkit_allowlist` on the
+ * agent follows server-side, so the agent list is refreshed too. */
+export function useUpdateAgentApps(agentId: string) {
+ const qc = useQueryClient();
+ const wsId = useWorkspaceId();
+ return useMutation({
+ mutationFn: (body: UpdateAgentAppsRequest) => api.updateAgentApps(agentId, body),
+ onSuccess: (data) => {
+ if (data) qc.setQueryData(connectedAppsKeys.agentApps(wsId, agentId), data.apps);
+ else void qc.invalidateQueries({ queryKey: connectedAppsKeys.agentApps(wsId, agentId) });
+ },
+ onSettled: () => {
+ qc.invalidateQueries({ queryKey: connectedAppsKeys.overview(wsId) });
+ qc.invalidateQueries({ queryKey: workspaceKeys.agents(wsId) });
+ },
+ });
+}
+
+export function useDecideAppRequest() {
+ const qc = useQueryClient();
+ const wsId = useWorkspaceId();
+ return useMutation({
+ mutationFn: (input:
+ | { id: string; decision: "approve"; arguments?: Record<string, unknown> }
+ | { id: string; decision: "reject"; reason?: string }) =>
+ input.decision === "approve"
+ ? api.approveAppRequest(input.id, input.arguments)
+ : api.rejectAppRequest(input.id, input.reason),
+ onSettled: () => qc.invalidateQueries({ queryKey: connectedAppsKeys.requests(wsId) }),
+ });
+}
diff --git a/packages/core/connected-apps/queries.ts b/packages/core/connected-apps/queries.ts
new file mode 100644
index 0000000000..51fa5b35ad
--- /dev/null
+++ b/packages/core/connected-apps/queries.ts
@@ -0,0 +1,99 @@
+import { queryOptions } from "@tanstack/react-query";
+import { api } from "../api";
+import type { AppAccountScope } from "../types";
+
+/** Query keys for Connected Apps (MUL-8516). Everything sits under the
+ * workspace id: team accounts, rules, and requests are workspace data. */
+export const connectedAppsKeys = {
+ all: (wsId: string) => ["connected-apps", wsId] as const,
+ overview: (wsId: string) => [...connectedAppsKeys.all(wsId), "overview"] as const,
+ catalog: (wsId: string) => [...connectedAppsKeys.all(wsId), "catalog"] as const,
+ fullCatalog: (wsId: string) => [...connectedAppsKeys.all(wsId), "catalog", "all"] as const,
+ tools: (wsId: string, slug: string) => [...connectedAppsKeys.all(wsId), "tools", slug] as const,
+ issueCalls: (wsId: string, issueId: string) =>
+ [...connectedAppsKeys.all(wsId), "calls", issueId] as const,
+ calls: (wsId: string) => [...connectedAppsKeys.all(wsId), "calls"] as const,
+ rules: (wsId: string, slug: string, scope: AppAccountScope) =>
+ [...connectedAppsKeys.all(wsId), "rules", slug, scope] as const,
+ activity: (wsId: string, slug: string, scope: AppAccountScope) =>
+ [...connectedAppsKeys.all(wsId), "activity", slug, scope] as const,
+ impact: (wsId: string, slug: string) => [...connectedAppsKeys.all(wsId), "impact", slug] as const,
+ agentApps: (wsId: string, agentId: string) =>
+ [...connectedAppsKeys.all(wsId), "agent", agentId] as const,
+ requests: (wsId: string) => [...connectedAppsKeys.all(wsId), "requests"] as const,
+ issueRequests: (wsId: string, issueId: string) =>
+ [...connectedAppsKeys.requests(wsId), "issue", issueId] as const,
+ chatRequests: (wsId: string, sessionId: string) =>
+ [...connectedAppsKeys.requests(wsId), "chat", sessionId] as const,
+};
+
+export const appsOverviewOptions = (wsId: string) =>
+ queryOptions({
+ queryKey: connectedAppsKeys.overview(wsId),
+ queryFn: () => api.getAppsOverview(),
+ });
+
+/** The catalog changes rarely; keep it for a few minutes. */
+export const appCatalogOptions = (wsId: string) =>
+ queryOptions({
+ queryKey: connectedAppsKeys.catalog(wsId),
+ queryFn: () => api.listAppCatalog(),
+ staleTime: 5 * 60 * 1000,
+ });
+
+/** Every connectable app, for an admin editing a custom catalog. */
+export const fullAppCatalogOptions = (wsId: string) =>
+ queryOptions({
+ queryKey: connectedAppsKeys.fullCatalog(wsId),
+ queryFn: () => api.listAppCatalog("all"),
+ staleTime: 5 * 60 * 1000,
+ });
+
+export const appToolsOptions = (wsId: string, slug: string) =>
+ queryOptions({
+ queryKey: connectedAppsKeys.tools(wsId, slug),
+ queryFn: () => api.listAppTools(slug).then((r) => r.tools),
+ });
+
+/** One fetch per issue backs both the comment chips and the sidebar. */
+export const issueAppCallsOptions = (wsId: string, issueId: string) =>
+ queryOptions({
+ queryKey: connectedAppsKeys.issueCalls(wsId, issueId),
+ queryFn: () => api.listIssueAppCalls(issueId).then((r) => r.calls),
+ });
+
+export const appRulesOptions = (wsId: string, slug: string, scope: AppAccountScope) =>
+ queryOptions({
+ queryKey: connectedAppsKeys.rules(wsId, slug, scope),
+ queryFn: () => api.getAppRules(slug, scope).then((r) => r.rules),
+ });
+
+export const appActivityOptions = (wsId: string, slug: string, scope: AppAccountScope) =>
+ queryOptions({
+ queryKey: connectedAppsKeys.activity(wsId, slug, scope),
+ queryFn: () => api.listAppActivity(slug, scope).then((r) => r.calls),
+ });
+
+export const teamAppImpactOptions = (wsId: string, slug: string) =>
+ queryOptions({
+ queryKey: connectedAppsKeys.impact(wsId, slug),
+ queryFn: () => api.getTeamAppImpact(slug),
+ });
+
+export const agentAppsOptions = (wsId: string, agentId: string) =>
+ queryOptions({
+ queryKey: connectedAppsKeys.agentApps(wsId, agentId),
+ queryFn: () => api.listAgentApps(agentId).then((r) => r.apps),
+ });
+
+export const issueAppRequestsOptions = (wsId: string, issueId: string) =>
+ queryOptions({
+ queryKey: connectedAppsKeys.issueRequests(wsId, issueId),
+ queryFn: () => api.listAppRequests({ issueId }).then((r) => r.requests),
+ });
+
+export const chatAppRequestsOptions = (wsId: string, sessionId: string) =>
+ queryOptions({
+ queryKey: connectedAppsKeys.chatRequests(wsId, sessionId),
+ queryFn: () => api.listAppRequests({ chatSessionId: sessionId }).then((r) => r.requests),
+ });
diff --git a/packages/core/package.json b/packages/core/package.json
index 0c738c7eb7..fb6572a08a 100644
--- a/packages/core/package.json
+++ b/packages/core/package.json
@@ -146,6 +146,9 @@
"./lark/queries": "./lark/queries.ts",
"./composio": "./composio/index.ts",
"./composio/queries": "./composio/queries.ts",
+ "./connected-apps": "./connected-apps/index.ts",
+ "./connected-apps/queries": "./connected-apps/queries.ts",
+ "./connected-apps/mutations": "./connected-apps/mutations.ts",
"./slack": "./slack/index.ts",
"./slack/queries": "./slack/queries.ts",
"./dingtalk": "./dingtalk/index.ts",
diff --git a/packages/core/realtime/use-realtime-sync.ts b/packages/core/realtime/use-realtime-sync.ts
index 393d75d733..d0a732a027 100644
--- a/packages/core/realtime/use-realtime-sync.ts
+++ b/packages/core/realtime/use-realtime-sync.ts
@@ -73,6 +73,7 @@ import {
QUICK_ACTIONS_PENDING_TIMEOUT_MS,
} from "../chat/queries";
import { useChatStore } from "../chat";
+import { connectedAppsKeys } from "../connected-apps/queries";
import { upsertChatMessageToCaches } from "../chat/message-cache";
import {
promotePendingChatTask,
@@ -839,6 +840,16 @@ export function useRealtimeSync(
workspace: () => {
qc.invalidateQueries({ queryKey: workspaceKeys.list() });
},
+ // app_request:changed carries ids only; refetch through the
+ // authorized list endpoints.
+ app_request: () => {
+ const wsId = getCurrentWsId();
+ if (wsId) qc.invalidateQueries({ queryKey: connectedAppsKeys.requests(wsId) });
+ },
+ app_call: () => {
+ const wsId = getCurrentWsId();
+ if (wsId) qc.invalidateQueries({ queryKey: connectedAppsKeys.calls(wsId) });
+ },
skill: () => {
const wsId = getCurrentWsId();
if (wsId) qc.invalidateQueries({ queryKey: workspaceKeys.skills(wsId) });
diff --git a/packages/core/types/connected-apps.ts b/packages/core/types/connected-apps.ts
new file mode 100644
index 0000000000..720c4d6caa
--- /dev/null
+++ b/packages/core/types/connected-apps.ts
@@ -0,0 +1,178 @@
+/** Wire shapes of the Connected Apps API (MUL-8516). Mirrors the response
+ * types in `server/internal/handler/connected_apps.go`. New backend fields
+ * must stay optional here so older desktop builds keep parsing. */
+
+/** Whose account an agent's app acts as: the workspace's team account, or
+ * the personal account of whoever triggered the run. */
+export type AppAccountScope = "team" | "personal";
+
+/** How far an agent may go with an app. Non-read calls at `confirm_writes`
+ * wait for the person who triggered the run. */
+export type AppAccessLevel = "read" | "confirm_writes" | "write";
+
+export type AppActionClass = "read" | "write" | "send" | "delete" | "share";
+
+export type AppActionPolicy = "allow" | "confirm" | "block";
+
+/** `all` lists every connectable app; `curated` only Multica's reviewed set;
+ * `custom` only the apps an admin listed. */
+export type AppCatalogMode = "all" | "curated" | "custom";
+
+export interface AppConnection {
+ id: string;
+ toolkit_slug: string;
+ status: "active" | "expired" | "revoked" | string;
+ connected_by?: string | null;
+ connected_at: string;
+ last_used_at: string | null;
+}
+
+export interface AgentApp {
+ agent_id: string;
+ toolkit_slug: string;
+ account_scope: AppAccountScope;
+ level: AppAccessLevel;
+}
+
+export interface AppsOverview {
+ catalog_mode: AppCatalogMode;
+ /** The apps of a custom catalog. */
+ allowed_toolkits?: string[];
+ /** Whether the caller administers team accounts and catalog settings. */
+ can_manage: boolean;
+ team: AppConnection[];
+ personal: AppConnection[];
+ agent_apps: AgentApp[];
+}
+
+export interface AppCatalogEntry {
+ slug: string;
+ name: string;
+ logo?: string;
+ category?: string;
+ curated: boolean;
+ recommended_scope?: AppAccountScope;
+ /** False only in the admin's full view for apps the catalog leaves out. */
+ allowed?: boolean;
+}
+
+/** One tool of an app and how this workspace classifies it. */
+export interface AppTool {
+ slug: string;
+ name: string;
+ description: string;
+ auto_class: AppActionClass;
+ class: AppActionClass;
+ overridden: boolean;
+}
+
+export type AppCallOutcome =
+ | "ok"
+ | "error"
+ | "blocked"
+ | "pending"
+ | "approved"
+ | "rejected"
+ | "rate_limited";
+
+/** One call an issue's runs made through an app. */
+export interface IssueAppCall {
+ id: string;
+ task_id: string | null;
+ agent_id: string;
+ account_scope: AppAccountScope;
+ account_owner_user_id: string | null;
+ toolkit_slug: string;
+ tool_slug: string;
+ action_class: AppActionClass | string;
+ outcome: AppCallOutcome | string;
+ request_id: string | null;
+ /** Present only for the account's owner. */
+ error: string | null;
+ created_at: string;
+}
+
+export interface AppCatalogResponse {
+ catalog_mode: AppCatalogMode;
+ apps: AppCatalogEntry[];
+}
+
+export interface AppRule {
+ action_class: AppActionClass;
+ policy: AppActionPolicy;
+ default_policy: AppActionPolicy;
+ custom: boolean;
+}
+
+export interface AppToolCall {
+ id: string;
+ agent_id: string;
+ issue_id: string | null;
+ chat_session_id: string | null;
+ triggered_by: string | null;
+ tool_slug: string;
+ action_class: AppActionClass;
+ outcome: AppCallOutcome | string;
+ error: string | null;
+ created_at: string;
+}
+
+export interface TeamAppImpact {
+ agents: { id: string; name: string }[];
+ active_tasks: number;
+ active_autopilots: number;
+ pending_requests: number;
+}
+
+export type AppRequestStatus =
+ | "pending"
+ | "approved"
+ | "rejected"
+ | "failed"
+ | "expired"
+ | "cancelled";
+
+/** A call waiting for (or decided by) a person. Arguments and results are
+ * present only for the approver; everyone else sees `redacted: true`. */
+export interface AppRequest {
+ id: string;
+ kind: "action" | "connect";
+ status: AppRequestStatus | string;
+ agent_id: string;
+ issue_id: string | null;
+ chat_session_id: string | null;
+ approver_user_id: string;
+ account_scope: AppAccountScope;
+ toolkit_slug: string;
+ tool_slug: string;
+ action_class: AppActionClass | string;
+ summary: string;
+ arguments?: Record<string, unknown>;
+ approved_arguments?: Record<string, unknown>;
+ result?: unknown;
+ error: string | null;
+ reason: string | null;
+ redacted: boolean;
+ expires_at: string;
+ decided_by: string | null;
+ decided_at: string | null;
+ created_at: string;
+}
+
+/** One page of requests. `next_before` pages back through decided history. */
+export interface AppRequestList {
+ requests: AppRequest[];
+ next_before: string | null;
+}
+
+export interface UpdateAgentAppsRequest {
+ apps: { toolkit_slug: string; account_scope: AppAccountScope; level: AppAccessLevel }[];
+}
+
+/** `app_request:changed` realtime payload: ids and status only. */
+export interface AppRequestChangedPayload {
+ request_id: string;
+ issue_id: string | null;
+ chat_session_id: string | null;
+ status: string;
+}
diff --git a/packages/core/types/events.ts b/packages/core/types/events.ts
index e7478dc291..a46fac5b4c 100644
--- a/packages/core/types/events.ts
+++ b/packages/core/types/events.ts
@@ -77,6 +77,8 @@ export type WSEventType =
| "label:deleted"
| "issue_labels:changed"
| "issue_unread:changed"
+ | "app_request:changed"
+ | "app_call:created"
| "issue_metadata:changed"
| "issue_properties:changed"
| "property:created"
diff --git a/packages/core/types/inbox.ts b/packages/core/types/inbox.ts
index e789f1b98c..0d61219cb9 100644
--- a/packages/core/types/inbox.ts
+++ b/packages/core/types/inbox.ts
@@ -31,7 +31,13 @@ export type InboxItemType =
| "autopilot_quota_exceeded"
// Sub-issues of an issue assigned to the recipient closed (the child_done
// system rule notifies a member assignee instead of waking an agent).
- | "children_done";
+ | "children_done"
+ // Connected Apps (MUL-8516): an agent waits on the recipient to confirm an
+ // app call, or to connect their account.
+ | "app_action_requested"
+ | "app_action_reminder"
+ | "app_connect_requested"
+ | "app_action_result";
/**
* One workspace's unread inbox count in the cross-workspace summary
diff --git a/packages/core/types/index.ts b/packages/core/types/index.ts
index adadfe9ce5..287c095556 100644
--- a/packages/core/types/index.ts
+++ b/packages/core/types/index.ts
@@ -251,6 +251,29 @@ export type {
ComposioConnection,
ComposioConnectInitResponse,
} from "./composio";
+export type {
+ AppAccountScope,
+ AppAccessLevel,
+ AppActionClass,
+ AppActionPolicy,
+ AppCatalogMode,
+ AppConnection,
+ AgentApp,
+ AppsOverview,
+ AppCatalogEntry,
+ AppCatalogResponse,
+ AppRule,
+ AppTool,
+ AppToolCall,
+ AppCallOutcome,
+ IssueAppCall,
+ TeamAppImpact,
+ AppRequestStatus,
+ AppRequest,
+ AppRequestList,
+ UpdateAgentAppsRequest,
+ AppRequestChangedPayload,
+} from "./connected-apps";
export type {
SlackInstallation,
ListSlackInstallationsResponse,
diff --git a/packages/views/agents/components/agent-advanced-settings.tsx b/packages/views/agents/components/agent-advanced-settings.tsx
index daf8994dba..cfb20a0215 100644
--- a/packages/views/agents/components/agent-advanced-settings.tsx
+++ b/packages/views/agents/components/agent-advanced-settings.tsx
@@ -34,7 +34,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 { AgentAppsTab } from "./tabs/agent-apps-tab";
import { IntegrationsTab } from "./tabs/integrations-tab";
import { QoderAgentTab } from "./tabs/qoder-agent-tab";
import { RuntimeConfigTab } from "./tabs/runtime-config-tab";
@@ -191,11 +191,7 @@ export function AgentAdvancedSettings({
);
}
const showMcp = runtime ? providerSupportsMcpConfig(runtime.provider) : true;
- const showComposioMcp =
- composioMCPAppsEnabled &&
- !!currentUserId &&
- !!agent.owner_id &&
- agent.owner_id === currentUserId;
+ const showComposioMcp = composioMCPAppsEnabled && canEdit;
return CAPABILITY_SECTIONS.filter((item) => {
if (item.id === "mcp_config") return showMcp;
if (item.id === "composio_mcp") return showComposioMcp;
@@ -203,9 +199,8 @@ export function AgentAdvancedSettings({
return true;
});
}, [
- agent.owner_id,
+ canEdit,
composioMCPAppsEnabled,
- currentUserId,
integrationsConfigured,
qoderRuntime,
runtime,
@@ -375,7 +370,7 @@ export function AgentAdvancedSettings({
onDirtyChange={setDirty}
/>
)}
- {active.id === "composio_mcp" && <AgentMcpTab agent={agent} />}
+ {active.id === "composio_mcp" && <AgentAppsTab agent={agent} />}
{active.id === "integrations" && (
<IntegrationsTab agent={agent} />
)}
diff --git a/packages/views/agents/components/tabs/agent-apps-tab.tsx b/packages/views/agents/components/tabs/agent-apps-tab.tsx
new file mode 100644
index 0000000000..97e5e81a72
--- /dev/null
+++ b/packages/views/agents/components/tabs/agent-apps-tab.tsx
@@ -0,0 +1,235 @@
+"use client";
+
+import { useMemo } from "react";
+import { useQuery } from "@tanstack/react-query";
+import { toast } from "sonner";
+import { AlertTriangle, Loader2, Plug, X } from "@multica/ui/icons";
+import { Button } from "@multica/ui/components/ui/button";
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from "@multica/ui/components/ui/select";
+import { useWorkspaceId } from "@multica/core/hooks";
+import {
+ agentAppsOptions,
+ appCatalogOptions,
+ appsOverviewOptions,
+ useUpdateAgentApps,
+} from "@multica/core/connected-apps";
+import { useWorkspacePaths } from "@multica/core/paths";
+import type {
+ Agent,
+ AgentApp,
+ AppAccessLevel,
+ AppAccountScope,
+ AppCatalogEntry,
+} from "@multica/core/types";
+import { ComposioToolkitLogo } from "../../../common/composio-toolkit-logo";
+import { AppLink } from "../../../navigation";
+import { useT } from "../../../i18n";
+import { ObjectSectionEmpty } from "../../../layout/object-page";
+
+const SCOPES: readonly AppAccountScope[] = ["personal", "team"];
+const LEVELS: readonly AppAccessLevel[] = ["read", "confirm_writes", "write"];
+
+/**
+ * The agent's apps (MUL-8516): which apps it can use, whose account each acts
+ * as, and how far it may go. Editable by whoever manages the agent; giving it
+ * a team account needs a workspace admin, which the server enforces too.
+ */
+export function AgentAppsTab({ agent }: { agent: Agent }) {
+ const { t } = useT("agents");
+ const { t: ts } = useT("settings");
+ const wsId = useWorkspaceId();
+ const paths = useWorkspacePaths();
+ const appsQuery = useQuery(agentAppsOptions(wsId, agent.id));
+ const overview = useQuery(appsOverviewOptions(wsId));
+ const catalog = useQuery(appCatalogOptions(wsId));
+ const update = useUpdateAgentApps(agent.id);
+
+ const canManageTeam = overview.data?.can_manage ?? false;
+ const apps = useMemo(() => appsQuery.data ?? [], [appsQuery.data]);
+ const appBySlug = useMemo(() => {
+ const m = new Map<string, AppCatalogEntry>();
+ for (const app of catalog.data?.apps ?? []) m.set(app.slug, app);
+ return m;
+ }, [catalog.data]);
+ const connected = useMemo(() => {
+ const set = new Set<string>();
+ for (const c of overview.data?.team ?? []) if (c.status === "active") set.add(`team:${c.toolkit_slug}`);
+ for (const c of overview.data?.personal ?? []) if (c.status === "active") set.add(`personal:${c.toolkit_slug}`);
+ return set;
+ }, [overview.data]);
+
+ const save = (next: AgentApp[]) => {
+ update.mutate(
+ {
+ apps: next.map((a) => ({
+ toolkit_slug: a.toolkit_slug,
+ account_scope: a.account_scope,
+ level: a.level,
+ })),
+ },
+ { onError: (e) => toast.error(e instanceof Error && e.message ? e.message : t(($) => $.tab_body.connected_apps.save_failed_toast)) },
+ );
+ };
+ const patch = (slug: string, change: Partial<AgentApp>) =>
+ save(apps.map((a) => (a.toolkit_slug === slug ? { ...a, ...change } : a)));
+ const add = (slug: string) => {
+ const recommended = appBySlug.get(slug)?.recommended_scope;
+ const scope: AppAccountScope = recommended === "team" && canManageTeam ? "team" : "personal";
+ // Only its owner runs a private agent, and would confirm each write anyway.
+ const level: AppAccessLevel = agent.permission_mode === "private" ? "write" : "confirm_writes";
+ save([...apps, { agent_id: agent.id, toolkit_slug: slug, account_scope: scope, level }]);
+ };
+
+ const addable = (catalog.data?.apps ?? []).filter((app) => !apps.some((a) => a.toolkit_slug === app.slug));
+ const scopeLabel = (scope: AppAccountScope) => ts(($) => $.connected_apps.scopes[scope]);
+ const levelLabel = (level: AppAccessLevel) => ts(($) => $.connected_apps.levels[level]);
+ const hasTeamApp = apps.some((a) => a.account_scope === "team");
+
+ if (appsQuery.isLoading) {
+ return <p className="text-body text-muted-foreground">{t(($) => $.tab_body.connected_apps.loading)}</p>;
+ }
+ if (appsQuery.isError) {
+ return <p className="text-body text-destructive">{t(($) => $.tab_body.connected_apps.load_failed)}</p>;
+ }
+
+ return (
+ <div className="space-y-4">
+ <p className="text-caption text-muted-foreground">{t(($) => $.tab_body.connected_apps.subtitle)}</p>
+
+ {hasTeamApp && agent.permission_mode !== "private" && (
+ <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-caption text-amber-700 dark:text-amber-400"
+ >
+ <AlertTriangle className="mt-0.5 size-3.5 shrink-0" />
+ <span>{t(($) => $.tab_body.connected_apps.team_shared_warning)}</span>
+ </div>
+ )}
+
+ {apps.length === 0 ? (
+ <ObjectSectionEmpty icon={Plug} description={t(($) => $.tab_body.connected_apps.empty)} />
+ ) : (
+ <ul className="divide-y rounded-lg border">
+ {apps.map((app) => {
+ const entry = appBySlug.get(app.toolkit_slug);
+ const name = entry?.name || app.toolkit_slug;
+ const isConnected = connected.has(`${app.account_scope}:${app.toolkit_slug}`);
+ const status =
+ app.account_scope === "team"
+ ? isConnected
+ ? t(($) => $.tab_body.connected_apps.team_connected)
+ : t(($) => $.tab_body.connected_apps.team_missing)
+ : isConnected
+ ? t(($) => $.tab_body.connected_apps.personal_connected)
+ : t(($) => $.tab_body.connected_apps.personal_missing);
+ const lockedTeam = app.account_scope === "team" && !canManageTeam;
+ return (
+ <li key={app.toolkit_slug} className="flex flex-wrap items-center gap-3 p-3">
+ <ComposioToolkitLogo slug={app.toolkit_slug} name={name} fallbackLogo={entry?.logo} />
+ <div className="min-w-0 flex-1">
+ <p className="truncate text-body font-medium">{name}</p>
+ <p className={isConnected ? "truncate text-caption text-muted-foreground" : "truncate text-caption text-warning"}>
+ {status}
+ </p>
+ </div>
+ <Select
+ items={SCOPES.map((value) => ({ value, label: scopeLabel(value) }))}
+ value={app.account_scope}
+ disabled={update.isPending || !canManageTeam}
+ onValueChange={(value) => {
+ if (value && value !== app.account_scope) patch(app.toolkit_slug, { account_scope: value as AppAccountScope });
+ }}
+ >
+ <SelectTrigger
+ size="sm"
+ className="w-44"
+ aria-label={t(($) => $.tab_body.connected_apps.account)}
+ title={canManageTeam ? undefined : t(($) => $.tab_body.connected_apps.team_admin_only)}
+ >
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent align="end">
+ {SCOPES.map((value) => (
+ <SelectItem key={value} value={value}>
+ {scopeLabel(value)}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ <Select
+ items={LEVELS.map((value) => ({ value, label: levelLabel(value) }))}
+ value={app.level}
+ disabled={update.isPending || lockedTeam}
+ onValueChange={(value) => {
+ if (value && value !== app.level) patch(app.toolkit_slug, { level: value as AppAccessLevel });
+ }}
+ >
+ <SelectTrigger size="sm" className="w-40" aria-label={t(($) => $.tab_body.connected_apps.level)}>
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent align="end">
+ {LEVELS.map((value) => (
+ <SelectItem key={value} value={value}>
+ {levelLabel(value)}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ <Button
+ variant="ghost"
+ size="icon-sm"
+ disabled={update.isPending || lockedTeam}
+ aria-label={t(($) => $.tab_body.connected_apps.remove, { app: name })}
+ onClick={() => save(apps.filter((a) => a.toolkit_slug !== app.toolkit_slug))}
+ >
+ <X />
+ </Button>
+ </li>
+ );
+ })}
+ </ul>
+ )}
+
+ <div className="flex flex-wrap items-center justify-between gap-3">
+ <Select
+ items={addable.map((app) => ({ value: app.slug, label: app.name || app.slug }))}
+ value={null}
+ disabled={update.isPending || addable.length === 0}
+ onValueChange={(value) => {
+ if (value) add(value as string);
+ }}
+ >
+ <SelectTrigger size="sm" className="w-56" aria-label={t(($) => $.tab_body.connected_apps.add_placeholder)}>
+ <SelectValue placeholder={t(($) => $.tab_body.connected_apps.add_placeholder)} />
+ </SelectTrigger>
+ <SelectContent>
+ {addable.map((app) => (
+ <SelectItem key={app.slug} value={app.slug}>
+ {app.name || app.slug}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ <AppLink
+ href={`${paths.settings()}?tab=apps`}
+ className="inline-flex items-center gap-1.5 text-caption font-medium text-primary hover:underline"
+ >
+ <Plug className="size-3" />
+ {t(($) => $.tab_body.connected_apps.manage_link)}
+ </AppLink>
+ </div>
+
+ {update.isPending && (
+ <p className="flex items-center gap-1.5 text-caption text-muted-foreground">
+ <Loader2 className="size-3 animate-spin" />
+ </p>
+ )}
+ </div>
+ );
+}
diff --git a/packages/views/agents/components/tabs/agent-mcp-tab.test.tsx b/packages/views/agents/components/tabs/agent-mcp-tab.test.tsx
deleted file mode 100644
index 87933313d3..0000000000
--- a/packages/views/agents/components/tabs/agent-mcp-tab.test.tsx
+++ /dev/null
@@ -1,258 +0,0 @@
-// @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=apps");
- });
-
- 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();
- });
-
- // Regression: GH #4915. Legacy self-host backends / stale caches may
- // return an agent without `invocation_targets` even though the modern
- // type declares a required array. The tab must degrade to the "not
- // workspace-public" copy instead of crashing the whole detail route
- // with "Cannot read properties of undefined (reading 'some')".
- it("does not crash when invocation_targets is undefined", () => {
- expect(() =>
- renderTab({
- permission_mode: "public_to",
- invocation_targets:
- undefined as unknown as Agent["invocation_targets"],
- composio_toolkit_allowlist: ["notion"],
- }),
- ).not.toThrow();
- // Falls back to the generic shared warning (no workspace target
- // resolves to `false`), not the workspace-wide one.
- 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.tsx
deleted file mode 100644
index c6c1e29b7e..0000000000
--- a/packages/views/agents/components/tabs/agent-mcp-tab.tsx
+++ /dev/null
@@ -1,212 +0,0 @@
-"use client";
-
-import { useMemo } from "react";
-import { useQuery } from "@tanstack/react-query";
-import { AlertTriangle, Loader2, Lock, Plug } from "@multica/ui/icons";
-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 { buttonVariants } from "@multica/ui/components/ui/button";
-import { Checkbox } from "@multica/ui/components/ui/checkbox";
-import { ComposioToolkitLogo } from "../../../common/composio-toolkit-logo";
-import { AppLink } from "../../../navigation";
-import { useT } from "../../../i18n";
-import { ObjectSectionEmpty } from "../../../layout/object-page";
-
-/**
- * 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=apps`;
-
- // 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-body font-medium">
- <Lock className="h-3.5 w-3.5 text-muted-foreground" />
- {t(($) => $.tab_body.composio_mcp.redacted_title)}
- </p>
- <p className="text-caption text-muted-foreground">
- {t(($) => $.tab_body.composio_mcp.redacted_hint)}
- </p>
- </div>
- );
- }
-
- return (
- <div className="space-y-4">
- <p className="text-caption 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-caption 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-body text-muted-foreground">
- {t(($) => $.tab_body.composio_mcp.loading)}
- </p>
- ) : connectionsQuery.isError ? (
- <p className="text-body text-destructive">
- {t(($) => $.tab_body.composio_mcp.load_failed)}
- </p>
- ) : activeSlugs.length === 0 ? (
- <ObjectSectionEmpty
- icon={Plug}
- title={t(($) => $.tab_body.composio_mcp.empty_title)}
- description={t(($) => $.tab_body.composio_mcp.empty_link_to_settings)}
- action={
- <AppLink
- href={settingsHref}
- className={buttonVariants({ variant: "outline", size: "sm" })}
- >
- {t(($) => $.tab_body.composio_mcp.open_settings)}
- </AppLink>
- }
- />
- ) : (
- <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-body font-medium">{name}</p>
- <p className="truncate text-micro 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-caption text-muted-foreground">
- <Loader2 className="h-3 w-3 animate-spin" />
- {t(($) => $.tab_body.composio_mcp.saving)}
- </p>
- )}
- </div>
- );
-}
diff --git a/packages/views/chat/chat-page.test.tsx b/packages/views/chat/chat-page.test.tsx
index d2ac316cc8..1f669a2cad 100644
--- a/packages/views/chat/chat-page.test.tsx
+++ b/packages/views/chat/chat-page.test.tsx
@@ -56,6 +56,12 @@ vi.mock("./components/offline-banner", () => ({
vi.mock("./components/no-agent-banner", () => ({
NoAgentBanner: () => null,
}));
+vi.mock("../common/app-requests", () => ({
+ ChatAppRequests: () => null,
+}));
+vi.mock("../common/app-requests", () => ({
+ ChatAppRequests: () => null,
+}));
vi.mock("./components/archived-agent-banner", () => ({
ArchivedAgentBanner: () => null,
}));
diff --git a/packages/views/chat/chat-page.tsx b/packages/views/chat/chat-page.tsx
index 4695e1a4b4..36a8d4983d 100644
--- a/packages/views/chat/chat-page.tsx
+++ b/packages/views/chat/chat-page.tsx
@@ -35,6 +35,7 @@ import { NoAgentBanner } from "./components/no-agent-banner";
import { ArchivedAgentBanner } from "./components/archived-agent-banner";
import { AgentAccessRevokedBanner } from "./components/agent-access-revoked-banner";
import { RuntimeRequiredBanner } from "./components/runtime-required-banner";
+import { ChatAppRequests } from "../common/app-requests";
import { useRegisterCommandBarContext } from "../search/register-context";
/**
@@ -374,6 +375,10 @@ export function ChatPage() {
<OfflineBanner agentName={c.activeAgent?.name} availability={c.availability} />
)}
+ <div className="px-4">
+ <ChatAppRequests sessionId={c.activeSessionId} />
+ </div>
+
<ChatQueue
tasks={queuedTasks}
headStatus={c.pendingTask?.status}
diff --git a/packages/views/chat/components/chat-window.test.tsx b/packages/views/chat/components/chat-window.test.tsx
index 5beff347b1..e5dc9f7244 100644
--- a/packages/views/chat/components/chat-window.test.tsx
+++ b/packages/views/chat/components/chat-window.test.tsx
@@ -61,6 +61,7 @@ vi.mock("./use-chat-resize", () => ({
}));
vi.mock("./use-chat-context-items", () => ({ useChatContextItems: () => [] }));
vi.mock("./chat-window-messages", () => ({ ChatWindowMessages: () => null }));
+vi.mock("../../common/app-requests", () => ({ ChatAppRequests: () => null }));
vi.mock("./chat-input", () => ({ ChatInput: () => null }));
vi.mock("./chat-queue", () => ({ ChatQueue: () => null }));
vi.mock("./chat-empty-state", () => ({ EmptyState: () => null }));
diff --git a/packages/views/chat/components/chat-window.tsx b/packages/views/chat/components/chat-window.tsx
index 5e21792cda..0f1807af1c 100644
--- a/packages/views/chat/components/chat-window.tsx
+++ b/packages/views/chat/components/chat-window.tsx
@@ -73,6 +73,7 @@ import { useChatOpenReveal } from "./use-chat-open-reveal";
import { ChatWindowMessages } from "./chat-window-messages";
import { ChatInput } from "./chat-input";
import { ChatQueue } from "./chat-queue";
+import { ChatAppRequests } from "../../common/app-requests";
import { EmptyState } from "./chat-empty-state";
import { SessionRenameInput } from "./session-rename-input";
import { SessionHistoryList } from "./session-history-list";
@@ -949,6 +950,10 @@ export function ChatWindow() {
<OfflineBanner agentName={activeAgent?.name} availability={availability} />
)}
+ <div className="px-4">
+ <ChatAppRequests sessionId={activeSessionId} />
+ </div>
+
<ChatQueue
tasks={queuedTasks}
headStatus={pendingTask?.status}
diff --git a/packages/views/common/app-requests.tsx b/packages/views/common/app-requests.tsx
new file mode 100644
index 0000000000..b9971a5609
--- /dev/null
+++ b/packages/views/common/app-requests.tsx
@@ -0,0 +1,373 @@
+"use client";
+
+import { useEffect, useRef, useState } from "react";
+import { useQuery, useQueryClient } from "@tanstack/react-query";
+import { toast } from "sonner";
+import { Loader2, Pencil, Plug, ShieldCheck } from "@multica/ui/icons";
+import { Badge } from "@multica/ui/components/ui/badge";
+import { Button } from "@multica/ui/components/ui/button";
+import { Input } from "@multica/ui/components/ui/input";
+import { Textarea } from "@multica/ui/components/ui/textarea";
+import { cn } from "@multica/ui/lib/utils";
+import { ApiError, api } from "@multica/core/api";
+import { useAuthStore } from "@multica/core/auth";
+import { useFeatureEnabled } from "@multica/core/config";
+import { COMPOSIO_MCP_APPS_FLAG } from "@multica/core/feature-flags";
+import { useWorkspaceId } from "@multica/core/hooks";
+import {
+ chatAppRequestsOptions,
+ connectedAppsKeys,
+ issueAppRequestsOptions,
+ useDecideAppRequest,
+} from "@multica/core/connected-apps";
+import { useActorName } from "@multica/core/workspace/hooks";
+import type { AppRequest } from "@multica/core/types";
+import { useLocale, useT } from "../i18n";
+import { currentPath, useNavigation } from "../navigation";
+
+const CONNECTED_PARAM = "app_connected";
+const CONNECT_ERROR_PARAM = "app_connect_error";
+let lastConnectReturn = "";
+
+/**
+ * Connecting from a card leaves the app and comes back to the page it started
+ * on with `?app_connected=<slug>` (or `app_connect_error`). The server has
+ * already let the waiting agent continue; say so once, then drop the param so
+ * a refresh does not repeat it.
+ */
+function useConnectReturn() {
+ const { t } = useT("settings");
+ const navigation = useNavigation();
+ const qc = useQueryClient();
+ const wsId = useWorkspaceId();
+ const connected = navigation.searchParams?.get(CONNECTED_PARAM) ?? null;
+ const failed = navigation.searchParams?.get(CONNECT_ERROR_PARAM) ?? null;
+ useEffect(() => {
+ const app = connected ?? failed;
+ if (!app) return;
+ // Several cards can mount on one page; only the first reports.
+ const key = `${navigation.pathname}:${connected ? "ok" : "error"}:${app}`;
+ if (lastConnectReturn === key) return;
+ lastConnectReturn = key;
+ if (connected) {
+ toast.success(t(($) => $.connected_apps.request.connected_resumed, { app }));
+ void qc.invalidateQueries({ queryKey: connectedAppsKeys.all(wsId) });
+ } else {
+ toast.error(t(($) => $.connected_apps.toast_connect_failed));
+ }
+ const params = new URLSearchParams(navigation.searchParams);
+ params.delete(CONNECTED_PARAM);
+ params.delete(CONNECT_ERROR_PARAM);
+ const search = params.toString();
+ navigation.replace(`${navigation.pathname}${search ? `?${search}` : ""}${navigation.hash}`);
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [connected, failed]);
+}
+
+/** Pending app confirmations of an issue, shown above its composer. The Inbox
+ * passes the request it opened so that card scrolls into view; bumping
+ * `highlightToken` replays it. */
+export function IssueAppRequests({
+ issueId,
+ highlightId,
+ highlightToken,
+}: {
+ issueId: string;
+ highlightId?: string;
+ highlightToken?: number;
+}) {
+ const wsId = useWorkspaceId();
+ const enabled = useFeatureEnabled(COMPOSIO_MCP_APPS_FLAG, false);
+ const { data } = useQuery({ ...issueAppRequestsOptions(wsId, issueId), enabled });
+ useConnectReturn();
+ return <AppRequestList requests={data ?? []} highlightId={highlightId} highlightToken={highlightToken} />;
+}
+
+/** Pending app confirmations of a chat, shown above its input. */
+export function ChatAppRequests({ sessionId }: { sessionId: string | null | undefined }) {
+ const wsId = useWorkspaceId();
+ const enabled = useFeatureEnabled(COMPOSIO_MCP_APPS_FLAG, false) && !!sessionId;
+ const { data } = useQuery({ ...chatAppRequestsOptions(wsId, sessionId ?? ""), enabled });
+ useConnectReturn();
+ return <AppRequestList requests={data ?? []} />;
+}
+
+/** One request, looked up from its chat or the caller's pending list (Inbox). */
+export function InboxAppRequest({ requestId, chatSessionId }: { requestId: string; chatSessionId?: string | null }) {
+ const wsId = useWorkspaceId();
+ const enabled = useFeatureEnabled(COMPOSIO_MCP_APPS_FLAG, false);
+ useConnectReturn();
+ const { data } = useQuery({
+ queryKey: [...chatAppRequestsOptions(wsId, chatSessionId ?? "").queryKey, "inbox", requestId],
+ queryFn: () =>
+ api.listAppRequests(chatSessionId ? { chatSessionId } : {}).then((r) => r.requests),
+ enabled,
+ });
+ const request = data?.find((r) => r.id === requestId);
+ if (!request) return null;
+ return <AppRequestList requests={[request]} showDecided />;
+}
+
+function AppRequestList({
+ requests,
+ showDecided = false,
+ highlightId,
+ highlightToken,
+}: {
+ requests: AppRequest[];
+ showDecided?: boolean;
+ highlightId?: string;
+ highlightToken?: number;
+}) {
+ const { t } = useT("settings");
+ const viewerId = useAuthStore((s) => s.user?.id);
+ const decide = useDecideAppRequest();
+ const visible = showDecided ? requests : requests.filter((r) => r.status === "pending");
+ if (visible.length === 0) return null;
+
+ const batch = visible.filter(
+ (r) => r.status === "pending" && r.kind === "action" && r.approver_user_id === viewerId,
+ );
+ const approveAll = async () => {
+ let failed = 0;
+ let limited = 0;
+ for (const r of batch) {
+ try {
+ await decide.mutateAsync({ id: r.id, decision: "approve" });
+ } catch (e) {
+ if (e instanceof ApiError && e.status === 429) limited++;
+ else failed++;
+ }
+ }
+ if (limited) toast.error(t(($) => $.connected_apps.request.rate_limited_some, { count: limited }));
+ else if (failed) toast.error(t(($) => $.connected_apps.request.toast_failed));
+ else toast.success(t(($) => $.connected_apps.request.toast_approved));
+ };
+
+ return (
+ <section className="my-3 space-y-2" aria-label={t(($) => $.connected_apps.request.pending_count, { count: visible.length })}>
+ {batch.length > 1 && (
+ <div className="flex items-center justify-between gap-3 text-caption text-muted-foreground">
+ <span>{t(($) => $.connected_apps.request.pending_count, { count: batch.length })}</span>
+ <Button size="xs" variant="outline" disabled={decide.isPending} onClick={approveAll}>
+ {t(($) => $.connected_apps.request.approve_all)}
+ </Button>
+ </div>
+ )}
+ {visible.map((request) => (
+ <AppRequestCard
+ key={request.id}
+ request={request}
+ isApprover={request.approver_user_id === viewerId}
+ highlightToken={request.id === highlightId ? (highlightToken ?? 0) : undefined}
+ />
+ ))}
+ </section>
+ );
+}
+
+type SettingsT = ReturnType<typeof useT<"settings">>["t"];
+
+function approveErrorMessage(e: unknown, t: SettingsT): string {
+ if (e instanceof ApiError) {
+ // 429 leaves the request pending; approving again later runs it.
+ if (e.status === 429) return t(($) => $.connected_apps.request.rate_limited);
+ if (e.status === 403) return t(($) => $.connected_apps.request.withdrawn);
+ }
+ if (e instanceof Error && /connect the account/i.test(e.message)) {
+ return t(($) => $.connected_apps.request.not_connected);
+ }
+ return t(($) => $.connected_apps.request.toast_failed);
+}
+
+function prettyArgs(args: Record<string, unknown> | undefined) {
+ return JSON.stringify(args ?? {}, null, 2);
+}
+
+const HIGHLIGHT_MS = 2400;
+
+function AppRequestCard({
+ request,
+ isApprover,
+ highlightToken,
+}: {
+ request: AppRequest;
+ isApprover: boolean;
+ highlightToken?: number;
+}) {
+ const { t } = useT("settings");
+ const locale = useLocale();
+ const navigation = useNavigation();
+ const ref = useRef<HTMLDivElement>(null);
+ const [highlighted, setHighlighted] = useState(false);
+ useEffect(() => {
+ if (highlightToken === undefined) return;
+ ref.current?.scrollIntoView({ block: "center", behavior: "smooth" });
+ setHighlighted(true);
+ const timer = setTimeout(() => setHighlighted(false), HIGHLIGHT_MS);
+ return () => clearTimeout(timer);
+ }, [highlightToken]);
+ const { getActorName } = useActorName();
+ const decide = useDecideAppRequest();
+ const [editing, setEditing] = useState(false);
+ const [draft, setDraft] = useState(() => prettyArgs(request.arguments));
+ const [rejecting, setRejecting] = useState(false);
+ const [reason, setReason] = useState("");
+ const [connecting, setConnecting] = useState(false);
+
+ const agent = getActorName("agent", request.agent_id);
+ const approver = getActorName("member", request.approver_user_id);
+ const app = request.toolkit_slug;
+ const pending = request.status === "pending";
+
+ const approve = () => {
+ let args: Record<string, unknown> | undefined;
+ if (editing) {
+ try {
+ const parsed: unknown = JSON.parse(draft);
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) throw new Error();
+ args = parsed as Record<string, unknown>;
+ } catch {
+ toast.error(t(($) => $.connected_apps.request.invalid_json));
+ return;
+ }
+ }
+ decide.mutate(
+ { id: request.id, decision: "approve", arguments: args },
+ {
+ onSuccess: () => toast.success(t(($) => $.connected_apps.request.toast_approved)),
+ onError: (e) => toast.error(approveErrorMessage(e, t)),
+ },
+ );
+ };
+ const reject = () =>
+ decide.mutate(
+ { id: request.id, decision: "reject", reason: reason.trim() || undefined },
+ {
+ onSuccess: () => toast.success(t(($) => $.connected_apps.request.toast_rejected)),
+ onError: () => toast.error(t(($) => $.connected_apps.request.toast_failed)),
+ },
+ );
+ const connect = async () => {
+ setConnecting(true);
+ try {
+ // The callback appends its own query, so the fragment stays behind.
+ const returnTo = currentPath({ ...navigation, hash: "" });
+ const { redirect_url } = await api.connectApp("personal", app, returnTo);
+ window.location.href = redirect_url;
+ } catch {
+ toast.error(t(($) => $.connected_apps.toast_failed));
+ setConnecting(false);
+ }
+ };
+
+ const statusLabel = (status: string) => {
+ switch (status) {
+ case "approved":
+ case "rejected":
+ case "failed":
+ case "expired":
+ case "cancelled":
+ return t(($) => $.connected_apps.request.status[status]);
+ default:
+ return status;
+ }
+ };
+
+ return (
+ <div
+ ref={ref}
+ data-app-request={request.id}
+ className={cn(
+ "rounded-lg border border-brand/40 bg-brand/5 p-3 transition-shadow duration-300",
+ highlighted && "ring-2 ring-brand/60",
+ )}
+ >
+ <div className="flex items-start gap-2">
+ <ShieldCheck className="mt-0.5 size-4 shrink-0 text-brand" />
+ <div className="min-w-0 flex-1 space-y-1">
+ <p className="text-body font-medium">
+ {request.kind === "connect"
+ ? t(($) => $.connected_apps.request.title_connect, { agent, app })
+ : t(($) => $.connected_apps.request.title_action, { agent, tool: request.tool_slug })}
+ </p>
+ <p className="flex flex-wrap items-center gap-1.5 text-caption text-muted-foreground">
+ <Badge variant="outline">{t(($) => $.connected_apps.scopes[request.account_scope])}</Badge>
+ {request.kind === "action" && <Badge variant="outline">{request.action_class}</Badge>}
+ <span>
+ {pending
+ ? `${t(($) => $.connected_apps.request.waiting_for, { name: approver })} · ${t(($) => $.connected_apps.request.expires, { when: new Date(request.expires_at).toLocaleString(locale, { month: "short", day: "numeric", hour: "2-digit", minute: "2-digit" }) })}`
+ : statusLabel(request.status)}
+ </span>
+ </p>
+ {request.summary && <p className="text-body">{request.summary}</p>}
+ {request.kind === "action" &&
+ (request.redacted ? (
+ <p className="text-caption text-muted-foreground">
+ {t(($) => $.connected_apps.request.redacted, { name: approver })}
+ </p>
+ ) : editing ? (
+ <Textarea
+ value={draft}
+ onChange={(e) => setDraft(e.target.value)}
+ className="min-h-32 font-mono text-caption"
+ aria-label={t(($) => $.connected_apps.request.arguments)}
+ />
+ ) : (
+ <pre className="max-h-48 overflow-auto rounded-md bg-muted p-2 font-mono text-caption">
+ {prettyArgs(request.approved_arguments ?? request.arguments)}
+ </pre>
+ ))}
+ {request.error && <p className="text-caption text-destructive">{request.error}</p>}
+ </div>
+ </div>
+
+ {pending && isApprover && (
+ <div className="mt-3 space-y-2">
+ {rejecting && (
+ <Input
+ autoFocus
+ value={reason}
+ onChange={(e) => setReason(e.target.value)}
+ placeholder={t(($) => $.connected_apps.request.reject_reason)}
+ />
+ )}
+ <div className="flex flex-wrap items-center justify-end gap-2">
+ {request.kind === "action" && !editing && !rejecting && (
+ <Button size="xs" variant="ghost" onClick={() => setEditing(true)}>
+ <Pencil />
+ {t(($) => $.connected_apps.request.edit)}
+ </Button>
+ )}
+ <Button
+ size="xs"
+ variant="outline"
+ disabled={decide.isPending}
+ onClick={() => (rejecting ? reject() : setRejecting(true))}
+ >
+ {t(($) => $.connected_apps.request.reject)}
+ </Button>
+ {request.kind === "connect" ? (
+ <>
+ <Button size="xs" variant="outline" disabled={connecting} onClick={connect}>
+ {connecting ? <Loader2 className="animate-spin" /> : <Plug />}
+ {t(($) => $.connected_apps.request.connect, { app })}
+ </Button>
+ <Button size="xs" disabled={decide.isPending} onClick={approve}>
+ {t(($) => $.connected_apps.request.connected_continue)}
+ </Button>
+ </>
+ ) : (
+ !rejecting && (
+ <Button size="xs" disabled={decide.isPending} onClick={approve}>
+ {decide.isPending && <Loader2 className="animate-spin" />}
+ {t(($) => $.connected_apps.request.approve)}
+ </Button>
+ )
+ )}
+ </div>
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/packages/views/inbox/components/inbox-detail-label.tsx b/packages/views/inbox/components/inbox-detail-label.tsx
index 7fdafdc7bf..0f8af99907 100644
--- a/packages/views/inbox/components/inbox-detail-label.tsx
+++ b/packages/views/inbox/components/inbox-detail-label.tsx
@@ -38,6 +38,10 @@ export function useTypeLabels(): Record<InboxItemType, string> {
autopilot_paused: t(($) => $.types.autopilot_paused),
autopilot_quota_exceeded: t(($) => $.types.autopilot_quota_exceeded),
children_done: t(($) => $.types.children_done),
+ app_action_requested: t(($) => $.types.app_action_requested),
+ app_action_reminder: t(($) => $.types.app_action_reminder),
+ app_connect_requested: t(($) => $.types.app_connect_requested),
+ app_action_result: t(($) => $.types.app_action_result),
};
}
diff --git a/packages/views/inbox/components/inbox-page.tsx b/packages/views/inbox/components/inbox-page.tsx
index 115a59f5c3..408d988631 100644
--- a/packages/views/inbox/components/inbox-page.tsx
+++ b/packages/views/inbox/components/inbox-page.tsx
@@ -112,6 +112,7 @@ import {
resolveDetailItem,
} from "./inbox-display";
import { AutopilotQuotaNotice } from "./autopilot-quota-notice";
+import { InboxAppRequest } from "../../common/app-requests";
import { useT } from "../../i18n";
import { useIssueLimitUpgradePrompt } from "../../modals/use-issue-limit-upgrade-prompt";
@@ -887,6 +888,9 @@ export function InboxPage() {
layoutId="multica_inbox_issue_detail_layout"
highlightCommentId={detailItem.details?.comment_id ?? undefined}
highlightRequestToken={highlightRequestToken}
+ highlightAppRequestId={
+ detailItem.type.startsWith("app_") ? (detailItem.details?.request_id ?? undefined) : undefined
+ }
// The inbox reads the row it selected itself (see the auto-read
// effect above), and must keep a row marked unread while it is open.
readsInbox={false}
@@ -927,6 +931,12 @@ export function InboxPage() {
{detailItem.body}
</div>
) : null}
+ {detailItem.details?.request_id && detailItem.type.startsWith("app_") && (
+ <InboxAppRequest
+ requestId={detailItem.details.request_id}
+ chatSessionId={detailItem.details.chat_session_id}
+ />
+ )}
{isQuickCreateOutcome(detailItem.type) && detailItem.details?.original_prompt && (
<div className="mt-4 rounded-md border bg-muted/40 p-3">
<p className="text-caption font-medium text-muted-foreground">
diff --git a/packages/views/issues/components/app-call-chips.tsx b/packages/views/issues/components/app-call-chips.tsx
new file mode 100644
index 0000000000..b6bf080927
--- /dev/null
+++ b/packages/views/issues/components/app-call-chips.tsx
@@ -0,0 +1,132 @@
+"use client";
+
+import { useMemo } from "react";
+import { useQuery } from "@tanstack/react-query";
+import { Ban, CircleCheck, Clock, XCircle } from "@multica/ui/icons";
+import { Tooltip, TooltipContent, TooltipTrigger } from "@multica/ui/components/ui/tooltip";
+import { cn } from "@multica/ui/lib/utils";
+import { useFeatureEnabled } from "@multica/core/config";
+import { COMPOSIO_MCP_APPS_FLAG } from "@multica/core/feature-flags";
+import { useWorkspaceId } from "@multica/core/hooks";
+import { appCatalogOptions, issueAppCallsOptions } from "@multica/core/connected-apps";
+import type { IssueAppCall } from "@multica/core/types";
+import { ComposioToolkitLogo } from "../../common/composio-toolkit-logo";
+import { useT } from "../../i18n";
+
+const MAX_CHIPS = 6;
+
+type IssuesT = ReturnType<typeof useT<"issues">>["t"];
+
+/** The calls of an issue's runs, and app display names. Both the comment
+ * chips and the sidebar read this one query. */
+export function useIssueAppCalls(issueId: string) {
+ const wsId = useWorkspaceId();
+ const enabled = useFeatureEnabled(COMPOSIO_MCP_APPS_FLAG, false);
+ const calls = useQuery({ ...issueAppCallsOptions(wsId, issueId), enabled });
+ const catalog = useQuery({ ...appCatalogOptions(wsId), enabled: enabled && (calls.data?.length ?? 0) > 0 });
+ const appName = useMemo(() => {
+ const names = new Map<string, string>();
+ for (const app of catalog.data?.apps ?? []) names.set(app.slug, app.name);
+ return (slug: string) => names.get(slug) || slug;
+ }, [catalog.data]);
+ return { calls: calls.data ?? [], appName };
+}
+
+/** `GMAIL_SEND_EMAIL` of `gmail` reads as "Send email". */
+export function toolLabel(toolkitSlug: string, toolSlug: string): string {
+ const prefix = `${toolkitSlug.toUpperCase().replace(/-/g, "_")}_`;
+ const bare = toolSlug.toUpperCase().startsWith(prefix) ? toolSlug.slice(prefix.length) : toolSlug;
+ const words = bare.toLowerCase().replace(/_+/g, " ").trim();
+ return words ? words.charAt(0).toUpperCase() + words.slice(1) : toolSlug;
+}
+
+export function outcomeLabel(outcome: string, t: IssuesT): string {
+ switch (outcome) {
+ case "ok":
+ case "error":
+ case "blocked":
+ case "pending":
+ case "approved":
+ case "rejected":
+ case "rate_limited":
+ return t(($) => $.app_calls.outcome[outcome]);
+ default:
+ return outcome;
+ }
+}
+
+export function OutcomeIcon({ outcome, className }: { outcome: string; className?: string }) {
+ const cls = cn("size-3 shrink-0", className);
+ switch (outcome) {
+ case "ok":
+ case "approved":
+ return <CircleCheck className={cn(cls, "text-success")} />;
+ case "pending":
+ case "rate_limited":
+ return <Clock className={cn(cls, "text-warning")} />;
+ case "blocked":
+ return <Ban className={cn(cls, "text-muted-foreground")} />;
+ default:
+ return <XCircle className={cn(cls, "text-destructive")} />;
+ }
+}
+
+type ChipGroup = { key: string; toolkit: string; tool: string; calls: IssueAppCall[] };
+
+/** What the run behind an agent comment did in apps: one chip per tool,
+ * marked with how its latest call ended. */
+export function AppCallChips({ issueId, taskId, className }: { issueId: string; taskId: string; className?: string }) {
+ const { t } = useT("issues");
+ const { calls, appName } = useIssueAppCalls(issueId);
+ const groups = useMemo(() => {
+ const byTool = new Map<string, ChipGroup>();
+ // Calls arrive newest first, so each group's first call is its latest.
+ for (const call of calls) {
+ if (call.task_id !== taskId) continue;
+ const key = `${call.toolkit_slug}:${call.tool_slug}`;
+ const group = byTool.get(key);
+ if (group) group.calls.push(call);
+ else byTool.set(key, { key, toolkit: call.toolkit_slug, tool: call.tool_slug, calls: [call] });
+ }
+ return [...byTool.values()].reverse();
+ }, [calls, taskId]);
+
+ if (groups.length === 0) return null;
+ const shown = groups.slice(0, MAX_CHIPS);
+ const hidden = groups.length - shown.length;
+
+ return (
+ <div className={cn("mt-1.5 flex flex-wrap items-center gap-1", className)} aria-label={t(($) => $.app_calls.chips_label)}>
+ {shown.map((group) => {
+ const latest = group.calls[0]!;
+ const app = appName(group.toolkit);
+ return (
+ <Tooltip key={group.key}>
+ <TooltipTrigger
+ render={
+ <span className="inline-flex h-6 max-w-56 items-center gap-1.5 rounded-md border bg-card px-1.5 text-micro font-medium text-muted-foreground">
+ <ComposioToolkitLogo slug={group.toolkit} name={app} className="size-3.5 rounded-xs text-[8px]" />
+ <span className="truncate text-foreground">{toolLabel(group.toolkit, group.tool)}</span>
+ {group.calls.length > 1 && <span className="tabular-nums">×{group.calls.length}</span>}
+ <OutcomeIcon outcome={latest.outcome} />
+ </span>
+ }
+ />
+ <TooltipContent side="top" className="max-w-72 text-caption">
+ <p className="font-medium">{app} · {group.tool}</p>
+ <p>
+ {outcomeLabel(latest.outcome, t)} · {t(($) => $.app_calls.scope[latest.account_scope])}
+ </p>
+ {latest.error && <p className="mt-1 line-clamp-3 opacity-80">{latest.error}</p>}
+ </TooltipContent>
+ </Tooltip>
+ );
+ })}
+ {hidden > 0 && (
+ <span className="inline-flex h-6 items-center px-1 text-micro font-medium text-muted-foreground">
+ {t(($) => $.app_calls.more, { count: hidden })}
+ </span>
+ )}
+ </div>
+ );
+}
diff --git a/packages/views/issues/components/comment-card.tsx b/packages/views/issues/components/comment-card.tsx
index 3b65cd5fa9..167f13033d 100644
--- a/packages/views/issues/components/comment-card.tsx
+++ b/packages/views/issues/components/comment-card.tsx
@@ -37,6 +37,7 @@ import { FileUploadButton } from "@multica/ui/components/common/file-upload-butt
import { api, dispatchReasonCode, errorCode } from "@multica/core/api";
import { ReplyInput } from "./reply-input";
import { CommentTriggerChips } from "./comment-trigger-chips";
+import { AppCallChips } from "./app-call-chips";
import { useCommentTriggerPreview } from "../hooks/use-comment-trigger-preview";
import { useRecipientActions } from "../hooks/use-recipient-actions";
import { SteerBadge, SteerReceipts } from "./steer-receipts";
@@ -911,6 +912,9 @@ function CommentRow({
<AttachmentList attachments={entry.attachments} content={entry.content} className="mt-1.5 pl-12 pr-4 max-md:pl-3 max-md:pr-3" />
<div className="pl-12 pr-4 max-md:pl-3 max-md:pr-3">
<SteerReceipts issueId={issueId} entry={entry} />
+ {entry.actor_type === "agent" && entry.source_task_id && (
+ <AppCallChips issueId={issueId} taskId={entry.source_task_id} />
+ )}
</div>
{retryableAgentFailureComment(entry) && (
<TaskCommentRetryButton
@@ -1466,6 +1470,9 @@ function CommentCardImpl({
<AttachmentList attachments={entry.attachments} content={entry.content} className="mt-1.5 pl-8 max-md:pl-0" />
<div className="pl-8 max-md:pl-0">
<SteerReceipts issueId={issueId} entry={entry} />
+ {entry.actor_type === "agent" && entry.source_task_id && (
+ <AppCallChips issueId={issueId} taskId={entry.source_task_id} />
+ )}
</div>
{retryableAgentFailureComment(entry) && (
<TaskCommentRetryButton
diff --git a/packages/views/issues/components/issue-apps-section.tsx b/packages/views/issues/components/issue-apps-section.tsx
new file mode 100644
index 0000000000..ef73373292
--- /dev/null
+++ b/packages/views/issues/components/issue-apps-section.tsx
@@ -0,0 +1,96 @@
+"use client";
+
+import { useMemo, useState } from "react";
+import type { AppAccountScope, IssueAppCall } from "@multica/core/types";
+import { ComposioToolkitLogo } from "../../common/composio-toolkit-logo";
+import { useT } from "../../i18n";
+import { OutcomeIcon, outcomeLabel, toolLabel, useIssueAppCalls } from "./app-call-chips";
+import { IssueSidebarSectionHeader } from "./issue-sidebar-section";
+
+type AppGroup = {
+ key: string;
+ toolkit: string;
+ scope: AppAccountScope;
+ calls: IssueAppCall[];
+ tools: Map<string, number>;
+};
+
+/** Outcomes worth calling out next to an app; plain successes are not. */
+const NOTABLE = ["pending", "blocked", "rejected", "error", "rate_limited"] as const;
+
+/**
+ * "Apps" in the issue sidebar: which apps, through which account, this
+ * issue's runs called, so a reader sees what an agent touched outside
+ * Multica without opening every run. Renders nothing until a call is made.
+ */
+export function IssueAppsSection({ issueId }: { issueId: string }) {
+ const { t } = useT("issues");
+ const [open, setOpen] = useState(true);
+ const { calls, appName } = useIssueAppCalls(issueId);
+ const groups = useMemo(() => {
+ const byApp = new Map<string, AppGroup>();
+ for (const call of calls) {
+ const key = `${call.account_scope}:${call.toolkit_slug}`;
+ let group = byApp.get(key);
+ if (!group) {
+ group = { key, toolkit: call.toolkit_slug, scope: call.account_scope, calls: [], tools: new Map() };
+ byApp.set(key, group);
+ }
+ group.calls.push(call);
+ group.tools.set(call.tool_slug, (group.tools.get(call.tool_slug) ?? 0) + 1);
+ }
+ return [...byApp.values()];
+ }, [calls]);
+
+ if (groups.length === 0) return null;
+
+ return (
+ <div>
+ <IssueSidebarSectionHeader
+ title={t(($) => $.app_calls.section_title)}
+ open={open}
+ onOpenChange={setOpen}
+ count={groups.length}
+ />
+ {open && (
+ <div className="px-2">
+ {groups.map((group) => {
+ const name = appName(group.toolkit);
+ const notable = NOTABLE.flatMap((outcome) => {
+ const count = group.calls.filter((c) => c.outcome === outcome).length;
+ return count > 0 ? [{ outcome, count }] : [];
+ });
+ const tools = [...group.tools.entries()]
+ .map(([tool, count]) => (count > 1 ? `${toolLabel(group.toolkit, tool)} ×${count}` : toolLabel(group.toolkit, tool)))
+ .join(", ");
+ return (
+ <div key={group.key} className="flex items-start gap-2 rounded-md px-2 py-2 text-caption" title={tools}>
+ <ComposioToolkitLogo slug={group.toolkit} name={name} className="mt-px size-4 rounded-xs text-[9px]" />
+ <div className="min-w-0 flex-1">
+ <p className="flex min-w-0 items-center gap-1.5">
+ <span className="truncate font-medium">{name}</span>
+ <span className="shrink-0 text-muted-foreground">{t(($) => $.app_calls.scope[group.scope])}</span>
+ </p>
+ <p className="truncate text-muted-foreground">{tools}</p>
+ {notable.length > 0 && (
+ <p className="mt-0.5 flex flex-wrap items-center gap-x-2 gap-y-0.5 text-muted-foreground">
+ {notable.map(({ outcome, count }) => (
+ <span key={outcome} className="inline-flex items-center gap-1">
+ <OutcomeIcon outcome={outcome} />
+ {count} {outcomeLabel(outcome, t)}
+ </span>
+ ))}
+ </p>
+ )}
+ </div>
+ <span className="ml-auto shrink-0 pl-2 text-micro tabular-nums text-muted-foreground">
+ {t(($) => $.app_calls.calls_count, { count: group.calls.length })}
+ </span>
+ </div>
+ );
+ })}
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/packages/views/issues/components/issue-detail.tsx b/packages/views/issues/components/issue-detail.tsx
index ef54f796de..67dc52b1ee 100644
--- a/packages/views/issues/components/issue-detail.tsx
+++ b/packages/views/issues/components/issue-detail.tsx
@@ -7,6 +7,7 @@ import {
issueStatusCategory,
} from "@multica/core/issues";
import { IssueFlowCard } from "../../workflows/issue-flow-card";
+import { IssueAppRequests } from "../../common/app-requests";
import { useStatusLabel } from "../utils/status-label";
import { priorityLabel } from "../utils/priority-label";
import { useIssueStatuses } from "@multica/core/issue-statuses/hooks";
@@ -123,6 +124,7 @@ import { PluginPanelSection } from "../../plugins";
import { PullRequestsSection } from "./pull-requests-section";
import { useGitHubSettings } from "@multica/core/github";
import { DeliverablesSection } from "./deliverables/deliverables-section";
+import { IssueAppsSection } from "./issue-apps-section";
import { DeliverablesOverview } from "./deliverables/deliverables-overview";
import {
DESCRIPTION_BLOCK_ID,
@@ -1178,6 +1180,9 @@ interface IssueDetailProps {
* guard and forces the render that re-reads the cleared memento entry.
*/
highlightRequestToken?: number;
+ /** The app confirmation an Inbox notification points at; its card scrolls
+ * into view and flashes, replayed by `highlightRequestToken`. */
+ highlightAppRequestId?: string;
/**
* Far-left header slot, replacing the mobile sidebar trigger. A host that
* embeds this detail one level deep (the inbox, on a phone) passes its own
@@ -1395,7 +1400,7 @@ export function IssueDetailSkeleton({
// IssueDetail
-export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = true, layoutId = "multica_issue_detail_layout", highlightCommentId, highlightRequestToken, leadingAction, variant = "page", trailingActions, readsInbox = true, skipInitialRefetch = false }: IssueDetailProps) {
+export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = true, layoutId = "multica_issue_detail_layout", highlightCommentId, highlightRequestToken, highlightAppRequestId, leadingAction, variant = "page", trailingActions, readsInbox = true, skipInitialRefetch = false }: IssueDetailProps) {
const isPeek = variant === "peek";
const { t } = useT("issues");
const { t: tCommon } = useT("common");
@@ -3163,6 +3168,9 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = tr
while there are none. */}
<DeliverablesSection files={deliverableFiles} onOpenOverview={openOverview} />
+ {/* Apps the issue's runs used. Hidden until one makes a call. */}
+ <IssueAppsSection issueId={id} />
+
{/* Execution summary owns its query, realtime updates and disclosure. */}
<ExecutionLogSection key={id} issueId={id} identifier={issue.identifier} issueTitle={issue.title} hasChildren={childIssues.length > 0} />
@@ -4063,6 +4071,7 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = tr
<JumpToLatestButton onClick={jumpToLatest.jump} label={t(($) => $.timeline.jump_to_latest)} />
</div>
)}
+ <IssueAppRequests issueId={id} highlightId={highlightAppRequestId} highlightToken={highlightRequestToken} />
<div
ref={composerRef}
className={cn(
diff --git a/packages/views/locales/en/agents.json b/packages/views/locales/en/agents.json
index ac5d98bb78..8ff074d1d2 100644
--- a/packages/views/locales/en/agents.json
+++ b/packages/views/locales/en/agents.json
@@ -300,7 +300,7 @@
"environment": "Environment",
"custom_args": "Custom Args",
"mcp_config": "MCP",
- "composio_mcp": "MCP Apps",
+ "composio_mcp": "Apps",
"integrations": "Integrations",
"runtime_config": "Routing",
"qoder_agent": "Qoder Cloud Agents",
@@ -722,22 +722,6 @@
"redacted_hint": "Only the agent owner or a workspace admin can read this config.",
"dialog_json_help": "Edit the full server configuration as JSON."
},
- "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_link_to_settings": "Connect one in Settings → Integrations",
- "open_settings": "Open settings",
- "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": {
"mode_label": "Routing mode",
"mode_local": "Local",
@@ -852,6 +836,24 @@
"started_prefix": "Started {{when}}",
"dispatched_prefix": "Dispatched {{when}}",
"queued_prefix": "Queued {{when}}"
+ },
+ "connected_apps": {
+ "subtitle": "Apps this agent can use. Each app acts as the team account or as the account of whoever triggers the run, at the level you choose.",
+ "loading": "Loading apps…",
+ "load_failed": "Couldn't load this agent's apps.",
+ "empty": "No apps yet.",
+ "add_placeholder": "Add an app…",
+ "account": "Account",
+ "level": "Level",
+ "remove": "Remove {{app}}",
+ "team_connected": "Team account connected",
+ "team_missing": "Team account not connected",
+ "personal_connected": "Your account is connected",
+ "personal_missing": "You haven't connected this app",
+ "team_admin_only": "Only workspace admins can give an agent a team account.",
+ "team_shared_warning": "Anyone who can run this agent acts as the team account for these apps.",
+ "manage_link": "Manage accounts in Settings → Connected apps",
+ "save_failed_toast": "Couldn't save — please try again"
}
},
"char_counter": {
diff --git a/packages/views/locales/en/inbox.json b/packages/views/locales/en/inbox.json
index 7c8fa9058a..a0072fbb4f 100644
--- a/packages/views/locales/en/inbox.json
+++ b/packages/views/locales/en/inbox.json
@@ -95,7 +95,11 @@
"quick_create_unconfirmed": "Create with agent unconfirmed",
"autopilot_paused": "Autopilot paused",
"children_done": "Sub-issues finished",
- "autopilot_quota_exceeded": "Autopilot run limit reached"
+ "autopilot_quota_exceeded": "Autopilot run limit reached",
+ "app_action_requested": "Needs your confirmation",
+ "app_action_reminder": "Confirmation expiring soon",
+ "app_connect_requested": "Connect an app",
+ "app_action_result": "App action result"
},
"labels": {
"set_status_to": "Set status to",
diff --git a/packages/views/locales/en/issues.json b/packages/views/locales/en/issues.json
index 6426f4b1b3..d17edec8a8 100644
--- a/packages/views/locales/en/issues.json
+++ b/packages/views/locales/en/issues.json
@@ -1878,5 +1878,25 @@
"empty_title": "No saved views yet",
"empty_description": "Set up filters and display options in an issue list, then save them as a view."
}
+ },
+ "app_calls": {
+ "section_title": "Apps",
+ "chips_label": "Apps used in this run",
+ "calls_count_one": "{{count}} call",
+ "calls_count_other": "{{count}} calls",
+ "more": "+{{count}} more",
+ "scope": {
+ "team": "Team account",
+ "personal": "Personal account"
+ },
+ "outcome": {
+ "ok": "Ran",
+ "error": "Failed",
+ "blocked": "Blocked",
+ "pending": "Waiting",
+ "approved": "Approved",
+ "rejected": "Declined",
+ "rate_limited": "Rate limited"
+ }
}
}
diff --git a/packages/views/locales/en/settings.json b/packages/views/locales/en/settings.json
index 22357c7b9f..3b9c4c34f2 100644
--- a/packages/views/locales/en/settings.json
+++ b/packages/views/locales/en/settings.json
@@ -955,35 +955,6 @@
"inbound_pending_hint": "Send this bot a message in Feishu/Lark to verify reception. If it does not arrive, check long connection mode, the im.message.receive_v1 subscription, and app publication/approval. Existing bindings may have no recorded verification yet.",
"inbound_verified_hint": "This binding received a valid message. This does not confirm ongoing connectivity, agent execution, or replies."
},
- "composio": {
- "page_description": "Connect apps your agents can use.",
- "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 connectable apps yet",
- "empty_description": "No toolkit has an enabled auth config in your Composio project yet. Enable one in the Composio dashboard to make it available here.",
- "search_placeholder": "Search toolkits…",
- "connect": "Connect",
- "connecting": "Connecting…",
- "connected": "Connected",
- "disconnect": "Disconnect",
- "disconnecting": "Disconnecting…",
- "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": "Chat with agents in Slack or use /issue to create an issue.",
@@ -1478,7 +1449,180 @@
"title": "Ways to give agents tools",
"current": "This page",
"mcp": "Added by admins and shared across the workspace, then assigned per agent.",
- "apps": "Authorized with your own account through Composio and enabled on agents you own.",
+ "apps": "Team or personal accounts connected through Multica, given to each agent with an account and a permission level.",
"plugins": "Installed packages that can add tools, scheduled hooks, and storage, each with its own permissions."
+ },
+ "connected_apps": {
+ "description": "Accounts your agents act through. Every call goes through Multica, which applies your rules and asks before sending, deleting or sharing.",
+ "add_app": "Add app",
+ "loading": "Loading apps…",
+ "load_failed": "Couldn't load apps.",
+ "team_title": "Team accounts",
+ "team_description": "Shared accounts the workspace owns, such as a support inbox or the company GitHub. Admins connect them; agents given the team account act as it.",
+ "team_empty": "No team accounts yet.",
+ "team_empty_member": "No team accounts yet. Ask a workspace admin to connect one.",
+ "personal_title": "My accounts",
+ "personal_description": "Your own accounts. When you trigger a run, agents use these for apps set to the triggerer's account.",
+ "personal_empty": "You haven't connected any accounts.",
+ "connected_by": "Connected by {{name}}",
+ "last_used": "Last used {{when}}",
+ "last_used_never": "Never used",
+ "used_by_one": "Used by {{count}} agent",
+ "used_by_other": "Used by {{count}} agents",
+ "expired": "Needs reconnecting",
+ "reconnect": "Reconnect",
+ "rules": "Rules",
+ "activity": "Activity",
+ "disconnect": "Disconnect",
+ "catalog_title": "Available apps",
+ "catalog_label": "Apps members can add",
+ "catalog_description": "Curated apps come with reviewed default rules. All apps adds everything Composio can connect; actions Multica can't classify always ask first. A custom list allows only the apps you pick.",
+ "catalog_all": "All apps",
+ "catalog_curated": "Curated only",
+ "catalog_custom": "Custom list",
+ "toast_connected": "Account connected",
+ "toast_connect_failed": "Couldn't complete the connection. Please try again.",
+ "toast_disconnected": "Disconnected",
+ "toast_failed": "Something went wrong. Please try again.",
+ "add": {
+ "title": "Add an app",
+ "description": "Connect an account for the team or for yourself. Which agents use it is set on each agent's Apps page.",
+ "search": "Search apps…",
+ "empty": "No apps match.",
+ "curated": "Curated",
+ "recommended_team": "Usually a team account",
+ "recommended_personal": "Usually a personal account",
+ "connect_team": "Connect for team",
+ "connect_personal": "Connect my account",
+ "connecting": "Connecting…",
+ "connected": "Connected"
+ },
+ "disconnect_team": {
+ "title": "Disconnect the team {{app}} account?",
+ "description": "Agents using the team account lose access right away.",
+ "agents": "Agents using it",
+ "no_agents": "No agent uses it.",
+ "active_tasks": "Runs in progress: {{count}}",
+ "active_autopilots": "Active autopilots: {{count}}",
+ "pending": "Confirmations that will be cancelled: {{count}}",
+ "cancel": "Cancel",
+ "confirm": "Disconnect"
+ },
+ "disconnect_personal": {
+ "title": "Disconnect your {{app}} account?",
+ "description": "Runs you trigger can no longer use it. You can reconnect later.",
+ "cancel": "Cancel",
+ "confirm": "Disconnect"
+ },
+ "detail": {
+ "team_title": "{{app}} · team account",
+ "personal_title": "{{app}} · my account",
+ "rules_description": "What agents may do through this account. An agent's level can only make these stricter.",
+ "rules_read_only": "Only workspace admins can change team account rules.",
+ "default": "Default: {{policy}}",
+ "activity_empty": "No calls yet.",
+ "activity_failed": "Couldn't load activity."
+ },
+ "classes": {
+ "read": {
+ "label": "Read",
+ "description": "Search, list and fetch"
+ },
+ "write": {
+ "label": "Write",
+ "description": "Create and update content"
+ },
+ "send": {
+ "label": "Send",
+ "description": "Send email or messages, post, invite"
+ },
+ "delete": {
+ "label": "Delete",
+ "description": "Delete or archive"
+ },
+ "share": {
+ "label": "Share",
+ "description": "Change permissions or share outside"
+ }
+ },
+ "policies": {
+ "allow": "Allow",
+ "confirm": "Ask first",
+ "block": "Block"
+ },
+ "outcomes": {
+ "ok": "Ran",
+ "error": "Failed",
+ "blocked": "Blocked",
+ "pending": "Waiting",
+ "approved": "Approved",
+ "rejected": "Declined",
+ "rate_limited": "Rate limited"
+ },
+ "scopes": {
+ "team": "Team account",
+ "personal": "Triggerer's account"
+ },
+ "levels": {
+ "read": "Read only",
+ "confirm_writes": "Ask before writes",
+ "write": "Can write"
+ },
+ "request": {
+ "title_action": "{{agent}} wants to run {{tool}}",
+ "title_connect": "{{agent}} asks you to connect {{app}}",
+ "pending_count_one": "{{count}} app action waiting for confirmation",
+ "pending_count_other": "{{count}} app actions waiting for confirmation",
+ "waiting_for": "Waiting for {{name}}",
+ "expires": "Expires {{when}}",
+ "redacted": "Only {{name}} can see the details.",
+ "arguments": "Arguments",
+ "edit": "Edit",
+ "invalid_json": "Arguments must be a JSON object.",
+ "approve": "Approve and run",
+ "approve_all": "Approve all",
+ "reject": "Decline",
+ "reject_reason": "Reason (optional, the agent sees it)",
+ "connect": "Connect {{app}}",
+ "connected_continue": "I've connected it",
+ "status": {
+ "approved": "Approved",
+ "rejected": "Declined",
+ "failed": "Failed",
+ "expired": "Expired",
+ "cancelled": "Cancelled"
+ },
+ "toast_approved": "Approved. The agent will continue.",
+ "toast_rejected": "Declined. The agent will adapt.",
+ "toast_failed": "Couldn't record your decision.",
+ "not_connected": "Connect the account first.",
+ "connected_resumed": "{{app}} connected. The agent picks up where it stopped.",
+ "rate_limited": "This account reached its limit of calls per minute. Approve again in a minute.",
+ "rate_limited_some_one": "{{count}} request hit the per-minute limit. Approve it again in a minute.",
+ "rate_limited_some_other": "{{count}} requests hit the per-minute limit. Approve them again in a minute.",
+ "withdrawn": "You can no longer use this agent, so the request was withdrawn."
+ },
+ "tools": {
+ "tab": "Tools",
+ "description": "A tool's class decides which rule applies to it. Correct any tool the automatic class gets wrong; the change covers every account of this app in the workspace.",
+ "read_only": "Only workspace admins can change how tools are classified.",
+ "search": "Search tools",
+ "empty": "No tools match.",
+ "auto": "Automatic ({{class}})",
+ "truncated": "Showing {{shown}} of {{total}}. Search to narrow the list."
+ },
+ "custom": {
+ "title": "Custom app list",
+ "description": "Agents see only the apps you pick, and nobody can connect an account for any other app.",
+ "selected_one": "{{count}} app selected",
+ "selected_other": "{{count}} apps selected",
+ "cancel": "Cancel",
+ "save": "Save list",
+ "saved": "App list saved",
+ "edit": "Edit list",
+ "row_label": "Allowed apps",
+ "row_description_one": "{{count}} app allowed",
+ "row_description_other": "{{count}} apps allowed"
+ }
}
}
diff --git a/packages/views/locales/es/agents.json b/packages/views/locales/es/agents.json
index 162c3ce97b..4eac1bd4ba 100644
--- a/packages/views/locales/es/agents.json
+++ b/packages/views/locales/es/agents.json
@@ -282,7 +282,7 @@
"environment": "Entorno",
"custom_args": "Argumentos personalizados",
"mcp_config": "MCP",
- "composio_mcp": "Apps MCP",
+ "composio_mcp": "Aplicaciones",
"integrations": "Integraciones",
"runtime_config": "Enrutado",
"discard_dialog_title": "¿Descartar los cambios sin guardar?",
@@ -704,22 +704,6 @@
"redacted_hint": "Solo el propietario del agente o un administrador del espacio de trabajo pueden leer esta configuración.",
"dialog_json_help": "Edita la configuración completa del servidor como JSON."
},
- "composio_mcp": {
- "subtitle": "Marca un toolkit para que este agente lo monte como servidor MCP, pero solo cuando quien dispara la ejecución eres tú (su creador), directamente o a través de una cadena de subagentes.",
- "loading": "Cargando tus conexiones…",
- "load_failed": "No se han podido cargar tus apps conectadas. Inténtalo de nuevo en un momento.",
- "empty_title": "Todavía no hay apps conectadas",
- "empty_link_to_settings": "Conecta una en Ajustes → Integraciones",
- "connected": "Conectada",
- "toggle_aria": "Permitir {{toolkit}} para este agente",
- "saving": "Guardando…",
- "save_failed_toast": "No se ha podido guardar: inténtalo de nuevo",
- "redacted_title": "Configurado: oculto a tu vista",
- "redacted_hint": "Solo el creador del agente puede ver o cambiar las apps que puede usar.",
- "shared_warning": "Este agente está compartido. Las personas que puedan ejecutarlo podrán usar las apps de Composio que actives aquí. Usa Privado o reduce la lista de acceso si estas apps exponen datos sensibles.",
- "workspace_warning": "Público para el espacio de trabajo: cualquier miembro puede usar estas apps de Composio a través de este agente.",
- "open_settings": "Abrir ajustes"
- },
"runtime_config": {
"mode_label": "Modo de enrutado",
"mode_local": "Local",
@@ -834,6 +818,24 @@
"started_prefix": "Iniciada {{when}}",
"dispatched_prefix": "Enviada {{when}}",
"queued_prefix": "En cola {{when}}"
+ },
+ "connected_apps": {
+ "subtitle": "Aplicaciones que puede usar este agente. Cada aplicación usa la cuenta del equipo o la de quien inicia la ejecución, con el nivel que elijas.",
+ "loading": "Cargando aplicaciones…",
+ "load_failed": "No se pudieron cargar las aplicaciones de este agente.",
+ "empty": "Aún no hay aplicaciones.",
+ "add_placeholder": "Añadir una aplicación…",
+ "account": "Cuenta",
+ "level": "Nivel",
+ "remove": "Eliminar {{app}}",
+ "team_connected": "Cuenta del equipo conectada",
+ "team_missing": "Cuenta del equipo sin conectar",
+ "personal_connected": "Tu cuenta está conectada",
+ "personal_missing": "No has conectado esta aplicación",
+ "team_admin_only": "Solo los administradores del espacio de trabajo pueden dar a un agente acceso a una cuenta del equipo.",
+ "team_shared_warning": "Cualquier persona que pueda ejecutar este agente usará la cuenta del equipo en estas aplicaciones.",
+ "manage_link": "Gestionar cuentas en Ajustes → Aplicaciones conectadas",
+ "save_failed_toast": "No se pudo guardar. Inténtalo de nuevo"
}
},
"char_counter": {
diff --git a/packages/views/locales/es/inbox.json b/packages/views/locales/es/inbox.json
index 6e5fb86903..4563f8792b 100644
--- a/packages/views/locales/es/inbox.json
+++ b/packages/views/locales/es/inbox.json
@@ -95,7 +95,11 @@
"quick_create_unconfirmed": "Creación con agente sin confirmar",
"autopilot_paused": "Automatización en pausa",
"children_done": "Sub-tareas finalizadas",
- "autopilot_quota_exceeded": "Límite de ejecuciones de automatizaciones alcanzado"
+ "autopilot_quota_exceeded": "Límite de ejecuciones de automatizaciones alcanzado",
+ "app_action_requested": "Necesita tu confirmación",
+ "app_action_reminder": "La confirmación caduca pronto",
+ "app_connect_requested": "Conectar una aplicación",
+ "app_action_result": "Resultado de la acción de la aplicación"
},
"labels": {
"set_status_to": "Establecer estado en",
diff --git a/packages/views/locales/es/issues.json b/packages/views/locales/es/issues.json
index b05f0ff507..ab41ceb627 100644
--- a/packages/views/locales/es/issues.json
+++ b/packages/views/locales/es/issues.json
@@ -1878,5 +1878,25 @@
"empty_title": "Aún no hay vistas guardadas",
"empty_description": "Configura los filtros y las opciones de visualización de una lista de tareas y guárdalos como vista."
}
+ },
+ "app_calls": {
+ "section_title": "Aplicaciones",
+ "chips_label": "Aplicaciones usadas en esta ejecución",
+ "calls_count_one": "{{count}} llamada",
+ "calls_count_other": "{{count}} llamadas",
+ "more": "+{{count}} más",
+ "scope": {
+ "team": "Cuenta del equipo",
+ "personal": "Cuenta personal"
+ },
+ "outcome": {
+ "ok": "Ejecutada",
+ "error": "Fallida",
+ "blocked": "Bloqueada",
+ "pending": "En espera",
+ "approved": "Aprobada",
+ "rejected": "Rechazada",
+ "rate_limited": "Límite de llamadas alcanzado"
+ }
}
}
diff --git a/packages/views/locales/es/settings.json b/packages/views/locales/es/settings.json
index 2744695437..cc19675d05 100644
--- a/packages/views/locales/es/settings.json
+++ b/packages/views/locales/es/settings.json
@@ -937,35 +937,6 @@
"inbound_pending_hint": "Envía un mensaje a este bot en Feishu/Lark para verificar la recepción. Si no llega, comprueba el modo de conexión persistente, la suscripción im.message.receive_v1 y la publicación o aprobación de la app. Puede que las vinculaciones existentes aún no tengan una verificación registrada.",
"inbound_verified_hint": "Esta vinculación ha recibido un mensaje válido. Esto no confirma la conectividad continua, la ejecución del agente ni las respuestas."
},
- "composio": {
- "page_description": "Conecta apps que tus agentes pueden usar.",
- "not_enabled_title": "La integración con Composio no está activada",
- "not_enabled_description_prefix": "Define",
- "not_enabled_description_suffix": "en el servidor para activar las conexiones de toolkits de Composio.",
- "loading": "Cargando toolkits…",
- "load_failed": "Error al cargar los toolkits de Composio.",
- "empty_title": "Aún no hay apps conectables",
- "empty_description": "Ningún toolkit tiene aún una configuración de auth activada en tu proyecto de Composio. Activa una en el panel de Composio para que aparezca aquí.",
- "search_placeholder": "Buscar toolkits…",
- "connect": "Conectar",
- "connecting": "Conectando…",
- "connected": "Conectado",
- "disconnect": "Desconectar",
- "disconnecting": "Desconectando…",
- "connect_failed": "No se ha podido iniciar la conexión. Inténtalo de nuevo.",
- "disconnect_failed": "No se ha podido desconectar. Inténtalo de nuevo.",
- "toast_disconnected": "Desconectado",
- "disconnect_confirm_title": "¿Desconectar esta app?",
- "disconnect_confirm_description": "Tu cuenta conectada se revocará en Composio y tus agentes perderán acceso a este toolkit. Puedes volver a conectarla más tarde.",
- "disconnect_confirm_cancel": "Cancelar",
- "connections_load_failed": "No se han podido cargar tus conexiones existentes; el estado de conexión puede estar incompleto.",
- "toast_connected": "Conectado",
- "toast_connect_failed": "No se ha podido completar la conexión. Inténtalo de nuevo.",
- "last_used": "Último uso {{when}}",
- "last_used_never": "Nunca usado",
- "expired": "Token caducado",
- "reconnect": "Reconectar"
- },
"slack": {
"section_title": "Slack",
"page_description": "Chatea con agentes en Slack o usa /issue para crear una tarea.",
@@ -1447,7 +1418,7 @@
}
},
"mcp_sources": {
- "apps": "Autorizadas con tu propia cuenta a través de Composio y activadas en agentes que posees.",
+ "apps": "Cuentas del equipo o personales conectadas mediante Multica, asignadas a cada agente con una cuenta y un nivel de permisos.",
"current": "Esta página",
"mcp": "Añadidas por administradores y compartidas en todo el espacio de trabajo, y luego asignadas por agente.",
"plugins": "Paquetes instalados que pueden añadir herramientas, ganchos programados y almacenamiento, cada uno con sus propios permisos.",
@@ -1480,5 +1451,178 @@
"save": "Guardar",
"save_error": "No se ha podido guardar el valor predeterminado.",
"saving": "Guardando…"
+ },
+ "connected_apps": {
+ "description": "Cuentas que usan tus agentes. Cada llamada pasa por Multica, que aplica tus reglas y pide confirmación antes de enviar, eliminar o compartir.",
+ "add_app": "Añadir aplicación",
+ "loading": "Cargando aplicaciones…",
+ "load_failed": "No se pudieron cargar las aplicaciones.",
+ "team_title": "Cuentas del equipo",
+ "team_description": "Cuentas compartidas del espacio de trabajo, como el buzón de soporte o el GitHub de la empresa. Los administradores las conectan; los agentes que tienen acceso actúan con esa cuenta.",
+ "team_empty": "Aún no hay cuentas del equipo.",
+ "team_empty_member": "Aún no hay cuentas del equipo. Pide a un administrador del espacio de trabajo que conecte una.",
+ "personal_title": "Mis cuentas",
+ "personal_description": "Tus propias cuentas. Cuando inicias una ejecución, los agentes las usan en las aplicaciones configuradas con la cuenta de quien inicia la ejecución.",
+ "personal_empty": "No has conectado ninguna cuenta.",
+ "connected_by": "Conectada por {{name}}",
+ "last_used": "Último uso {{when}}",
+ "last_used_never": "Sin usar",
+ "used_by_one": "La usa {{count}} agente",
+ "used_by_other": "La usan {{count}} agentes",
+ "expired": "Necesita volver a conectarse",
+ "reconnect": "Volver a conectar",
+ "rules": "Reglas",
+ "activity": "Actividad",
+ "disconnect": "Desconectar",
+ "catalog_title": "Aplicaciones disponibles",
+ "catalog_label": "Aplicaciones que pueden añadir los miembros",
+ "catalog_description": "Las aplicaciones seleccionadas incluyen reglas predeterminadas revisadas. Todas las aplicaciones incluye todo lo que Composio puede conectar; las acciones que Multica no puede clasificar siempre piden confirmación. Una lista personalizada permite solo las aplicaciones que elijas.",
+ "catalog_all": "Todas las aplicaciones",
+ "catalog_curated": "Solo seleccionadas",
+ "catalog_custom": "Lista personalizada",
+ "toast_connected": "Cuenta conectada",
+ "toast_connect_failed": "No se pudo completar la conexión. Inténtalo de nuevo.",
+ "toast_disconnected": "Desconectada",
+ "toast_failed": "Algo salió mal. Inténtalo de nuevo.",
+ "add": {
+ "title": "Añadir una aplicación",
+ "description": "Conecta una cuenta para el equipo o para ti. El acceso de cada agente se configura en su página de Aplicaciones.",
+ "search": "Buscar aplicaciones…",
+ "empty": "No hay aplicaciones que coincidan.",
+ "curated": "Seleccionada",
+ "recommended_team": "Suele usarse una cuenta del equipo",
+ "recommended_personal": "Suele usarse una cuenta personal",
+ "connect_team": "Conectar para el equipo",
+ "connect_personal": "Conectar mi cuenta",
+ "connecting": "Conectando…",
+ "connected": "Conectada"
+ },
+ "disconnect_team": {
+ "title": "¿Desconectar la cuenta del equipo de {{app}}?",
+ "description": "Los agentes que usan la cuenta del equipo perderán el acceso de inmediato.",
+ "agents": "Agentes que la usan",
+ "no_agents": "Ningún agente la usa.",
+ "active_tasks": "Ejecuciones en curso: {{count}}",
+ "active_autopilots": "Automatizaciones activas: {{count}}",
+ "pending": "Confirmaciones que se cancelarán: {{count}}",
+ "cancel": "Cancelar",
+ "confirm": "Desconectar"
+ },
+ "disconnect_personal": {
+ "title": "¿Desconectar tu cuenta de {{app}}?",
+ "description": "Las ejecuciones que inicies ya no podrán usarla. Puedes volver a conectarla más adelante.",
+ "cancel": "Cancelar",
+ "confirm": "Desconectar"
+ },
+ "detail": {
+ "team_title": "{{app}} · cuenta del equipo",
+ "personal_title": "{{app}} · mi cuenta",
+ "rules_description": "Lo que pueden hacer los agentes con esta cuenta. El nivel de un agente solo puede hacer estas reglas más estrictas.",
+ "rules_read_only": "Solo los administradores del espacio de trabajo pueden cambiar las reglas de las cuentas del equipo.",
+ "default": "Predeterminado: {{policy}}",
+ "activity_empty": "Aún no hay llamadas.",
+ "activity_failed": "No se pudo cargar la actividad."
+ },
+ "classes": {
+ "read": {
+ "label": "Leer",
+ "description": "Buscar, listar y consultar"
+ },
+ "write": {
+ "label": "Escribir",
+ "description": "Crear y actualizar contenido"
+ },
+ "send": {
+ "label": "Enviar",
+ "description": "Enviar correos o mensajes, publicar e invitar"
+ },
+ "delete": {
+ "label": "Eliminar",
+ "description": "Eliminar o archivar"
+ },
+ "share": {
+ "label": "Compartir",
+ "description": "Cambiar permisos o compartir fuera"
+ }
+ },
+ "policies": {
+ "allow": "Permitir",
+ "confirm": "Preguntar antes",
+ "block": "Bloquear"
+ },
+ "outcomes": {
+ "ok": "Ejecutada",
+ "error": "Fallida",
+ "blocked": "Bloqueada",
+ "pending": "En espera",
+ "approved": "Aprobada",
+ "rejected": "Rechazada",
+ "rate_limited": "Límite de llamadas alcanzado"
+ },
+ "scopes": {
+ "team": "Cuenta del equipo",
+ "personal": "Cuenta de quien inicia la ejecución"
+ },
+ "levels": {
+ "read": "Solo lectura",
+ "confirm_writes": "Preguntar antes de escribir",
+ "write": "Puede escribir"
+ },
+ "request": {
+ "title_action": "{{agent}} quiere ejecutar {{tool}}",
+ "title_connect": "{{agent}} te pide conectar {{app}}",
+ "pending_count_one": "{{count}} acción de aplicación pendiente de confirmación",
+ "pending_count_other": "{{count}} acciones de aplicaciones pendientes de confirmación",
+ "waiting_for": "Esperando a {{name}}",
+ "expires": "Caduca {{when}}",
+ "redacted": "Solo {{name}} puede ver los detalles.",
+ "arguments": "Argumentos",
+ "edit": "Editar",
+ "invalid_json": "Los argumentos deben ser un objeto JSON.",
+ "approve": "Aprobar y ejecutar",
+ "approve_all": "Aprobar todas",
+ "reject": "Rechazar",
+ "reject_reason": "Motivo (opcional, el agente lo verá)",
+ "connect": "Conectar {{app}}",
+ "connected_continue": "Ya la he conectado",
+ "status": {
+ "approved": "Aprobada",
+ "rejected": "Rechazada",
+ "failed": "Fallida",
+ "expired": "Caducada",
+ "cancelled": "Cancelada"
+ },
+ "toast_approved": "Aprobada. El agente continuará.",
+ "toast_rejected": "Rechazada. El agente se adaptará.",
+ "toast_failed": "No se pudo registrar tu decisión.",
+ "not_connected": "Conecta primero la cuenta.",
+ "connected_resumed": "{{app}} conectada. El agente continúa donde se detuvo.",
+ "rate_limited": "Esta cuenta alcanzó su límite de llamadas por minuto. Vuelve a aprobar la solicitud dentro de un minuto.",
+ "rate_limited_some_one": "{{count}} solicitud alcanzó el límite por minuto. Vuelve a aprobarla dentro de un minuto.",
+ "rate_limited_some_other": "{{count}} solicitudes alcanzaron el límite por minuto. Vuelve a aprobarlas dentro de un minuto.",
+ "withdrawn": "Ya no puedes usar este agente, por lo que se retiró la solicitud."
+ },
+ "tools": {
+ "tab": "Herramientas",
+ "description": "La categoría de una herramienta determina qué regla se aplica. Corrige las clasificaciones automáticas incorrectas; el cambio se aplica a todas las cuentas de esta aplicación en el espacio de trabajo.",
+ "read_only": "Solo los administradores del espacio de trabajo pueden cambiar la clasificación de las herramientas.",
+ "search": "Buscar herramientas",
+ "empty": "No hay herramientas que coincidan.",
+ "auto": "Automática ({{class}})",
+ "truncated": "Se muestran {{shown}} de {{total}}. Busca para reducir la lista."
+ },
+ "custom": {
+ "title": "Lista personalizada de aplicaciones",
+ "description": "Los agentes solo ven las aplicaciones que elijas y nadie puede conectar cuentas de otras aplicaciones.",
+ "selected_one": "{{count}} aplicación seleccionada",
+ "selected_other": "{{count}} aplicaciones seleccionadas",
+ "cancel": "Cancelar",
+ "save": "Guardar lista",
+ "saved": "Lista de aplicaciones guardada",
+ "edit": "Editar lista",
+ "row_label": "Aplicaciones permitidas",
+ "row_description_one": "{{count}} aplicación permitida",
+ "row_description_other": "{{count}} aplicaciones permitidas"
+ }
}
}
diff --git a/packages/views/locales/fr/agents.json b/packages/views/locales/fr/agents.json
index e0eec91084..ebea18698f 100644
--- a/packages/views/locales/fr/agents.json
+++ b/packages/views/locales/fr/agents.json
@@ -300,7 +300,7 @@
"environment": "Environnement",
"custom_args": "Arguments personnalisés",
"mcp_config": "MCP",
- "composio_mcp": "Applications MCP",
+ "composio_mcp": "Apps",
"integrations": "Intégrations",
"runtime_config": "Routage",
"qoder_agent": "Qoder Cloud Agents",
@@ -722,22 +722,6 @@
"redacted_hint": "Seul le propriétaire de l'agent ou un administrateur de l'espace de travail peut lire cette configuration.",
"dialog_json_help": "Modifiez la configuration complète du serveur en JSON."
},
- "composio_mcp": {
- "subtitle": "Cochez une boîte à outils pour permettre à cet agent de la monter comme serveur MCP — mais uniquement lorsque c'est vous (son créateur) qui avez déclenché l'exécution, directement ou via une chaîne de sous-agents.",
- "loading": "Chargement de vos connexions…",
- "load_failed": "Impossible de charger vos applications connectées. Réessayez dans un instant.",
- "empty_title": "Aucune application connectée pour l'instant",
- "empty_link_to_settings": "Connectez-en un dans Paramètres → Intégrations",
- "open_settings": "Ouvrir les paramètres",
- "connected": "Connecté",
- "toggle_aria": "Autoriser {{toolkit}} pour cet agent",
- "saving": "Enregistrement…",
- "save_failed_toast": "Impossible d'enregistrer — veuillez réessayer",
- "redacted_title": "Configuré — masqué pour vous",
- "redacted_hint": "Seul le créateur de l'agent peut voir ou modifier les applications qu'il peut utiliser.",
- "shared_warning": "Cet agent est partagé. Les personnes qui peuvent l'exécuter pourront utiliser les applications Composio que vous activez ici. Passez en Privé ou restreignez la liste d'accès si ces applications exposent des données sensibles.",
- "workspace_warning": "Public pour l'espace de travail : tout membre de l'espace de travail peut utiliser ces applications Composio via cet agent."
- },
"runtime_config": {
"mode_label": "Mode de routage",
"mode_local": "Local",
@@ -852,6 +836,24 @@
"started_prefix": "Démarrée {{when}}",
"dispatched_prefix": "Envoyée {{when}}",
"queued_prefix": "Mise en file d'attente {{when}}"
+ },
+ "connected_apps": {
+ "subtitle": "Les apps que cet agent peut utiliser. Chacune agit avec le compte d'équipe ou celui de la personne qui lance l'exécution, au niveau choisi.",
+ "loading": "Chargement des apps…",
+ "load_failed": "Impossible de charger les apps de cet agent.",
+ "empty": "Aucune app pour l'instant.",
+ "add_placeholder": "Ajouter une app…",
+ "account": "Compte",
+ "level": "Niveau",
+ "remove": "Retirer {{app}}",
+ "team_connected": "Compte d'équipe connecté",
+ "team_missing": "Compte d'équipe non connecté",
+ "personal_connected": "Votre compte est connecté",
+ "personal_missing": "Vous n'avez pas connecté cette app",
+ "team_admin_only": "Seuls les admins de l'espace peuvent donner un compte d'équipe à un agent.",
+ "team_shared_warning": "Toute personne qui peut lancer cet agent agit avec le compte d'équipe pour ces apps.",
+ "manage_link": "Gérer les comptes dans Paramètres → Applications connectées",
+ "save_failed_toast": "Échec de l'enregistrement, veuillez réessayer"
}
},
"char_counter": {
diff --git a/packages/views/locales/fr/inbox.json b/packages/views/locales/fr/inbox.json
index 5ea8b34bcd..0072619590 100644
--- a/packages/views/locales/fr/inbox.json
+++ b/packages/views/locales/fr/inbox.json
@@ -95,7 +95,11 @@
"quick_create_unconfirmed": "Création avec un agent non confirmée",
"autopilot_paused": "Automatisation en pause",
"children_done": "Sous-tâches terminées",
- "autopilot_quota_exceeded": "Limite d'exécutions d'automatisation atteinte"
+ "autopilot_quota_exceeded": "Limite d'exécutions d'automatisation atteinte",
+ "app_action_requested": "Confirmation requise",
+ "app_action_reminder": "Confirmation bientôt expirée",
+ "app_connect_requested": "Connecter une app",
+ "app_action_result": "Résultat d'action d'app"
},
"labels": {
"set_status_to": "Statut défini sur",
diff --git a/packages/views/locales/fr/issues.json b/packages/views/locales/fr/issues.json
index df51416d68..ce82427633 100644
--- a/packages/views/locales/fr/issues.json
+++ b/packages/views/locales/fr/issues.json
@@ -1878,5 +1878,25 @@
"empty_title": "Aucune vue enregistrée pour l'instant",
"empty_description": "Réglez les filtres et l'affichage d'une liste de tâches, puis enregistrez-les comme vue."
}
+ },
+ "app_calls": {
+ "section_title": "Apps",
+ "chips_label": "Apps utilisées dans cette exécution",
+ "calls_count_one": "{{count}} appel",
+ "calls_count_other": "{{count}} appels",
+ "more": "+{{count}} de plus",
+ "scope": {
+ "team": "Compte d'équipe",
+ "personal": "Compte personnel"
+ },
+ "outcome": {
+ "ok": "Exécuté",
+ "error": "Échec",
+ "blocked": "Bloqué",
+ "pending": "En attente",
+ "approved": "Approuvé",
+ "rejected": "Refusé",
+ "rate_limited": "Limite atteinte"
+ }
}
}
diff --git a/packages/views/locales/fr/settings.json b/packages/views/locales/fr/settings.json
index 76c0a549c2..efea9583dd 100644
--- a/packages/views/locales/fr/settings.json
+++ b/packages/views/locales/fr/settings.json
@@ -955,35 +955,6 @@
"inbound_pending_hint": "Envoyez un message à ce bot dans Feishu/Lark pour vérifier la réception. Si rien n’arrive, vérifiez la connexion persistante, l’abonnement im.message.receive_v1 et la publication/approbation de l’application. Les associations existantes peuvent ne pas encore avoir de vérification enregistrée.",
"inbound_verified_hint": "Cette association a reçu un message valide. Cela ne confirme ni la connexion continue, ni l’exécution de l’agent, ni ses réponses."
},
- "composio": {
- "page_description": "Connectez des applications que vos agents peuvent utiliser.",
- "not_enabled_title": "Intégration Composio non activée",
- "not_enabled_description_prefix": "Définissez",
- "not_enabled_description_suffix": "sur le serveur pour activer les connexions aux boîtes à outils Composio.",
- "loading": "Chargement des boîtes à outils…",
- "load_failed": "Échec du chargement des boîtes à outils Composio.",
- "empty_title": "Aucune application connectable pour l'instant",
- "empty_description": "Aucune boîte à outils n'a encore de configuration d'authentification activée dans votre projet Composio. Activez-en une dans le tableau de bord Composio pour la rendre disponible ici.",
- "search_placeholder": "Rechercher des boîtes à outils…",
- "connect": "Connecter",
- "connecting": "Connexion…",
- "connected": "Connecté",
- "disconnect": "Déconnecter",
- "disconnecting": "Déconnexion…",
- "connect_failed": "Impossible de démarrer la connexion. Veuillez réessayer.",
- "disconnect_failed": "Impossible de déconnecter. Veuillez réessayer.",
- "toast_disconnected": "Déconnecté",
- "disconnect_confirm_title": "Déconnecter cette application ?",
- "disconnect_confirm_description": "Votre compte connecté sera révoqué chez Composio et vos agents perdront l'accès à cette boîte à outils. Vous pourrez vous reconnecter plus tard.",
- "disconnect_confirm_cancel": "Annuler",
- "connections_load_failed": "Impossible de charger vos connexions existantes : l'état de connexion peut être incomplet.",
- "toast_connected": "Connecté",
- "toast_connect_failed": "Impossible d'établir la connexion. Veuillez réessayer.",
- "last_used": "Dernière utilisation {{when}}",
- "last_used_never": "Jamais utilisé",
- "expired": "Jeton expiré",
- "reconnect": "Reconnecter"
- },
"slack": {
"section_title": "Slack",
"page_description": "Discutez avec les agents dans Slack ou créez une tâche avec /issue.",
@@ -1478,7 +1449,180 @@
"title": "Donner des outils aux agents",
"current": "Cette page",
"mcp": "Ajoutés par les administrateurs, partagés dans l'espace de travail puis attribués agent par agent.",
- "apps": "Autorisées avec votre propre compte via Composio et activées sur les agents qui vous appartiennent.",
+ "apps": "Comptes d'équipe ou personnels connectés via Multica, attribués à chaque agent avec un compte et un niveau de permission.",
"plugins": "Paquets installés pouvant ajouter des outils, des hooks planifiés et du stockage, chacun avec ses propres autorisations."
+ },
+ "connected_apps": {
+ "description": "Les comptes par lesquels vos agents agissent. Chaque appel passe par Multica, qui applique vos règles et demande avant d'envoyer, supprimer ou partager.",
+ "add_app": "Ajouter une app",
+ "loading": "Chargement des apps…",
+ "load_failed": "Impossible de charger les apps.",
+ "team_title": "Comptes d'équipe",
+ "team_description": "Les comptes partagés de l'espace de travail, comme une boîte support ou le GitHub de l'entreprise. Les admins les connectent ; les agents qui reçoivent le compte d'équipe agissent en son nom.",
+ "team_empty": "Aucun compte d'équipe pour l'instant.",
+ "team_empty_member": "Aucun compte d'équipe pour l'instant. Demandez à un admin de l'espace d'en connecter un.",
+ "personal_title": "Mes comptes",
+ "personal_description": "Vos propres comptes. Quand vous lancez une exécution, les apps réglées sur le compte du déclencheur les utilisent.",
+ "personal_empty": "Vous n'avez connecté aucun compte.",
+ "connected_by": "Connecté par {{name}}",
+ "last_used": "Dernière utilisation {{when}}",
+ "last_used_never": "Jamais utilisé",
+ "used_by_one": "Utilisé par {{count}} agent",
+ "used_by_other": "Utilisé par {{count}} agents",
+ "expired": "À reconnecter",
+ "reconnect": "Reconnecter",
+ "rules": "Règles",
+ "activity": "Activité",
+ "disconnect": "Déconnecter",
+ "catalog_title": "Apps disponibles",
+ "catalog_label": "Apps que les membres peuvent ajouter",
+ "catalog_description": "Les apps sélectionnées ont des règles par défaut vérifiées. « Toutes les apps » ajoute tout ce que Composio peut connecter ; les actions que Multica ne sait pas classer demandent toujours d'abord. Une liste personnalisée n'autorise que les apps choisies.",
+ "catalog_all": "Toutes les apps",
+ "catalog_curated": "Sélection uniquement",
+ "catalog_custom": "Liste personnalisée",
+ "toast_connected": "Compte connecté",
+ "toast_connect_failed": "La connexion n'a pas abouti. Veuillez réessayer.",
+ "toast_disconnected": "Déconnecté",
+ "toast_failed": "Une erreur est survenue. Veuillez réessayer.",
+ "add": {
+ "title": "Ajouter une app",
+ "description": "Connectez un compte pour l'équipe ou pour vous. Les agents qui l'utilisent se choisissent sur la page Apps de chaque agent.",
+ "search": "Rechercher une app…",
+ "empty": "Aucune app ne correspond.",
+ "curated": "Sélection",
+ "recommended_team": "Souvent un compte d'équipe",
+ "recommended_personal": "Souvent un compte personnel",
+ "connect_team": "Connecter pour l'équipe",
+ "connect_personal": "Connecter mon compte",
+ "connecting": "Connexion…",
+ "connected": "Connecté"
+ },
+ "disconnect_team": {
+ "title": "Déconnecter le compte {{app}} de l'équipe ?",
+ "description": "Les agents qui utilisent le compte d'équipe perdent l'accès immédiatement.",
+ "agents": "Agents qui l'utilisent",
+ "no_agents": "Aucun agent ne l'utilise.",
+ "active_tasks": "Exécutions en cours : {{count}}",
+ "active_autopilots": "Autopilotes actifs : {{count}}",
+ "pending": "Confirmations qui seront annulées : {{count}}",
+ "cancel": "Annuler",
+ "confirm": "Déconnecter"
+ },
+ "disconnect_personal": {
+ "title": "Déconnecter votre compte {{app}} ?",
+ "description": "Les exécutions que vous lancez ne pourront plus l'utiliser. Vous pourrez le reconnecter plus tard.",
+ "cancel": "Annuler",
+ "confirm": "Déconnecter"
+ },
+ "detail": {
+ "team_title": "{{app}} · compte d'équipe",
+ "personal_title": "{{app}} · mon compte",
+ "rules_description": "Ce que les agents peuvent faire avec ce compte. Le niveau d'un agent ne peut que les rendre plus stricts.",
+ "rules_read_only": "Seuls les admins de l'espace peuvent modifier les règles du compte d'équipe.",
+ "default": "Par défaut : {{policy}}",
+ "activity_empty": "Aucun appel pour l'instant.",
+ "activity_failed": "Impossible de charger l'activité."
+ },
+ "classes": {
+ "read": {
+ "label": "Lire",
+ "description": "Rechercher, lister, récupérer"
+ },
+ "write": {
+ "label": "Écrire",
+ "description": "Créer et modifier du contenu"
+ },
+ "send": {
+ "label": "Envoyer",
+ "description": "Envoyer des e-mails ou messages, publier, inviter"
+ },
+ "delete": {
+ "label": "Supprimer",
+ "description": "Supprimer ou archiver"
+ },
+ "share": {
+ "label": "Partager",
+ "description": "Modifier les droits ou partager à l'extérieur"
+ }
+ },
+ "policies": {
+ "allow": "Autoriser",
+ "confirm": "Demander d'abord",
+ "block": "Bloquer"
+ },
+ "outcomes": {
+ "ok": "Exécuté",
+ "error": "Échec",
+ "blocked": "Bloqué",
+ "pending": "En attente",
+ "approved": "Approuvé",
+ "rejected": "Refusé",
+ "rate_limited": "Limite atteinte"
+ },
+ "scopes": {
+ "team": "Compte d'équipe",
+ "personal": "Compte du déclencheur"
+ },
+ "levels": {
+ "read": "Lecture seule",
+ "confirm_writes": "Demander avant d'écrire",
+ "write": "Peut écrire"
+ },
+ "request": {
+ "title_action": "{{agent}} veut exécuter {{tool}}",
+ "title_connect": "{{agent}} vous demande de connecter {{app}}",
+ "pending_count_one": "{{count}} action d'app en attente de confirmation",
+ "pending_count_other": "{{count}} actions d'app en attente de confirmation",
+ "waiting_for": "En attente de {{name}}",
+ "expires": "Expire {{when}}",
+ "redacted": "Seul·e {{name}} peut voir les détails.",
+ "arguments": "Arguments",
+ "edit": "Modifier",
+ "invalid_json": "Les arguments doivent être un objet JSON.",
+ "approve": "Approuver et exécuter",
+ "approve_all": "Tout approuver",
+ "reject": "Refuser",
+ "reject_reason": "Raison (facultatif, visible par l'agent)",
+ "connect": "Connecter {{app}}",
+ "connected_continue": "C'est connecté",
+ "status": {
+ "approved": "Approuvé",
+ "rejected": "Refusé",
+ "failed": "Échec",
+ "expired": "Expiré",
+ "cancelled": "Annulé"
+ },
+ "toast_approved": "Approuvé. L'agent va continuer.",
+ "toast_rejected": "Refusé. L'agent va s'adapter.",
+ "toast_failed": "Impossible d'enregistrer votre décision.",
+ "not_connected": "Connectez d'abord le compte.",
+ "connected_resumed": "{{app}} connecté. L'agent reprend là où il s'était arrêté.",
+ "rate_limited": "Ce compte a atteint sa limite d'appels par minute. Approuvez à nouveau dans une minute.",
+ "rate_limited_some_one": "{{count}} demande a atteint la limite par minute. Approuvez-la à nouveau dans une minute.",
+ "rate_limited_some_other": "{{count}} demandes ont atteint la limite par minute. Approuvez-les à nouveau dans une minute.",
+ "withdrawn": "Vous ne pouvez plus utiliser cet agent ; la demande a été retirée."
+ },
+ "tools": {
+ "tab": "Outils",
+ "description": "La classe d'un outil détermine la règle qui s'applique. Corrigez tout outil mal classé automatiquement ; le changement vaut pour tous les comptes de cette app dans l'espace de travail.",
+ "read_only": "Seuls les administrateurs de l'espace de travail peuvent modifier la classification des outils.",
+ "search": "Rechercher des outils",
+ "empty": "Aucun outil ne correspond.",
+ "auto": "Automatique ({{class}})",
+ "truncated": "{{shown}} sur {{total}} affichés. Recherchez pour affiner."
+ },
+ "custom": {
+ "title": "Liste d'apps personnalisée",
+ "description": "Les agents ne voient que les apps choisies, et personne ne peut connecter de compte pour une autre app.",
+ "selected_one": "{{count}} app sélectionnée",
+ "selected_other": "{{count}} apps sélectionnées",
+ "cancel": "Annuler",
+ "save": "Enregistrer la liste",
+ "saved": "Liste d'apps enregistrée",
+ "edit": "Modifier la liste",
+ "row_label": "Apps autorisées",
+ "row_description_one": "{{count}} app autorisée",
+ "row_description_other": "{{count}} apps autorisées"
+ }
}
}
diff --git a/packages/views/locales/ja/agents.json b/packages/views/locales/ja/agents.json
index fd308c18b1..ab86aa8454 100644
--- a/packages/views/locales/ja/agents.json
+++ b/packages/views/locales/ja/agents.json
@@ -280,7 +280,7 @@
"environment": "環境",
"custom_args": "カスタム引数",
"mcp_config": "MCP",
- "composio_mcp": "MCP アプリ",
+ "composio_mcp": "アプリ",
"integrations": "連携",
"runtime_config": "ルーティング",
"qoder_agent": "Qoder Cloud Agents",
@@ -545,22 +545,6 @@
"redacted_hint": "この config を読み取れるのは、エージェントのオーナーまたはワークスペースの admin のみです。",
"dialog_json_help": "サーバー設定全体を JSON で編集します。"
},
- "composio_mcp": {
- "subtitle": "ツールキットにチェックを入れると、あなた(この agent の作成者)が直接または下位 agent のチェーン経由でこの agent をトリガーしたときに限り、MCP サーバーとしてマウントされます。",
- "loading": "接続を読み込み中…",
- "load_failed": "接続済みアプリを読み込めませんでした。しばらくしてから再試行してください。",
- "empty_title": "接続済みのアプリがありません",
- "empty_link_to_settings": "設定 → 連携 で接続する",
- "open_settings": "設定を開く",
- "connected": "接続済み",
- "toggle_aria": "この agent に {{toolkit}} を許可",
- "saving": "保存中…",
- "save_failed_toast": "保存できませんでした。もう一度お試しください",
- "redacted_title": "設定済み — あなたには非表示",
- "redacted_hint": "この agent が使用できるアプリを閲覧・変更できるのは作成者のみです。",
- "shared_warning": "このエージェントは共有されています。このエージェントを実行できる人は、ここで有効化した Composio アプリを利用できます。これらのアプリが機微なデータを扱う場合は、Private にするかアクセス範囲を絞ってください。",
- "workspace_warning": "ワークスペースに公開:ワークスペースの全メンバーがこのエージェントを通じてこれらの Composio アプリを利用できます。"
- },
"runtime_config": {
"mode_label": "ルーティングモード",
"mode_local": "Local",
@@ -673,6 +657,24 @@
"started_prefix": "{{when}} に開始",
"dispatched_prefix": "{{when}} にディスパッチ",
"queued_prefix": "{{when}} に待機開始"
+ },
+ "connected_apps": {
+ "subtitle": "このエージェントが使えるアプリです。各アプリはチームアカウントか、実行を起動した人のアカウントとして、選んだレベルで動作します。",
+ "loading": "アプリを読み込み中…",
+ "load_failed": "このエージェントのアプリを読み込めませんでした。",
+ "empty": "アプリはまだありません。",
+ "add_placeholder": "アプリを追加…",
+ "account": "アカウント",
+ "level": "レベル",
+ "remove": "{{app}} を削除",
+ "team_connected": "チームアカウント接続済み",
+ "team_missing": "チームアカウント未接続",
+ "personal_connected": "あなたのアカウントは接続済み",
+ "personal_missing": "このアプリはまだ接続していません",
+ "team_admin_only": "エージェントにチームアカウントを付与できるのはワークスペース管理者のみです。",
+ "team_shared_warning": "このエージェントを実行できる人は誰でも、これらのアプリをチームアカウントとして使います。",
+ "manage_link": "設定 → 接続済みアプリ でアカウントを管理",
+ "save_failed_toast": "保存できませんでした。もう一度お試しください"
}
},
"char_counter": {
diff --git a/packages/views/locales/ja/inbox.json b/packages/views/locales/ja/inbox.json
index 130e728156..a744076f1a 100644
--- a/packages/views/locales/ja/inbox.json
+++ b/packages/views/locales/ja/inbox.json
@@ -93,7 +93,11 @@
"quick_create_unconfirmed": "エージェントでの作成結果は未確認",
"autopilot_paused": "自動化を一時停止しました",
"children_done": "サブタスクがすべて終わりました",
- "autopilot_quota_exceeded": "自動化の実行上限に達しました"
+ "autopilot_quota_exceeded": "自動化の実行上限に達しました",
+ "app_action_requested": "確認が必要",
+ "app_action_reminder": "確認の期限が近い",
+ "app_connect_requested": "アプリの接続依頼",
+ "app_action_result": "アプリ操作の結果"
},
"labels": {
"set_status_to": "ステータスを変更:",
diff --git a/packages/views/locales/ja/issues.json b/packages/views/locales/ja/issues.json
index fc4780b9f4..d3741cb94a 100644
--- a/packages/views/locales/ja/issues.json
+++ b/packages/views/locales/ja/issues.json
@@ -1809,5 +1809,24 @@
"empty_title": "保存したビューはまだありません",
"empty_description": "タスク一覧でフィルターと表示方法を調整し、ビューとして保存します。"
}
+ },
+ "app_calls": {
+ "section_title": "アプリ",
+ "chips_label": "この実行で使ったアプリ",
+ "calls_count_other": "{{count}} 回",
+ "more": "ほか {{count}} 件",
+ "scope": {
+ "team": "チームアカウント",
+ "personal": "個人アカウント"
+ },
+ "outcome": {
+ "ok": "実行済み",
+ "error": "失敗",
+ "blocked": "ブロック",
+ "pending": "確認待ち",
+ "approved": "承認済み",
+ "rejected": "却下",
+ "rate_limited": "レート制限"
+ }
}
}
diff --git a/packages/views/locales/ja/settings.json b/packages/views/locales/ja/settings.json
index 984ebaad73..9ef3c9a692 100644
--- a/packages/views/locales/ja/settings.json
+++ b/packages/views/locales/ja/settings.json
@@ -950,35 +950,6 @@
"inbound_pending_hint": "Feishu/Lark でこのボットにメッセージを送り、受信を確認してください。届かない場合は長時間接続、im.message.receive_v1 の購読、アプリの公開・承認状態を確認してください。既存の連携には確認記録がない場合があります。",
"inbound_verified_hint": "今回の連携で有効なメッセージを受信しました。継続的な接続、エージェントの実行、返信の成功を保証するものではありません。"
},
- "composio": {
- "page_description": "エージェントが使えるアプリに接続します。",
- "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 connectable apps yet",
- "empty_description": "No toolkit has an enabled auth config in your Composio project yet. Enable one in the Composio dashboard to make it available here.",
- "search_placeholder": "Search toolkits…",
- "connect": "Connect",
- "connecting": "Connecting…",
- "connected": "Connected",
- "disconnect": "Disconnect",
- "disconnecting": "Disconnecting…",
- "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": "Slack でエージェントと対話し、/issue でタスクを作成できます。",
@@ -1467,7 +1438,175 @@
"title": "エージェントにツールを与える方法",
"current": "このページ",
"mcp": "管理者が追加してワークスペースで共有し、エージェントごとに割り当てます。",
- "apps": "自分のアカウントで Composio 経由で承認し、自分が所有するエージェントで有効にします。",
+ "apps": "Multica で接続したチームまたは個人のアカウント。エージェントごとにアカウントと権限レベルを割り当てます。",
"plugins": "インストールするとツール、定期フック、ストレージを追加でき、プラグインごとに権限を付与します。"
+ },
+ "connected_apps": {
+ "description": "エージェントが外部アプリを操作するアカウントです。すべての呼び出しは Multica を経由し、ルールを適用し、送信・削除・共有の前に確認を求めます。",
+ "add_app": "アプリを追加",
+ "loading": "アプリを読み込み中…",
+ "load_failed": "アプリを読み込めませんでした。",
+ "team_title": "チームアカウント",
+ "team_description": "サポート用メールや会社の GitHub など、ワークスペースが所有する共有アカウントです。管理者が接続し、チームアカウントを付与されたエージェントはその名義で操作します。",
+ "team_empty": "チームアカウントはまだありません。",
+ "team_empty_member": "チームアカウントはまだありません。ワークスペース管理者に接続を依頼してください。",
+ "personal_title": "自分のアカウント",
+ "personal_description": "あなた自身のアカウントです。あなたが起動した実行では、「起動した人のアカウント」に設定されたアプリがこれを使います。",
+ "personal_empty": "まだアカウントを接続していません。",
+ "connected_by": "{{name}} が接続",
+ "last_used": "最終使用 {{when}}",
+ "last_used_never": "未使用",
+ "used_by_other": "{{count}} 個のエージェントが使用",
+ "expired": "再接続が必要",
+ "reconnect": "再接続",
+ "rules": "ルール",
+ "activity": "アクティビティ",
+ "disconnect": "接続を解除",
+ "catalog_title": "利用できるアプリ",
+ "catalog_label": "メンバーが追加できるアプリ",
+ "catalog_description": "厳選アプリにはレビュー済みの既定ルールがあります。「すべてのアプリ」は Composio で接続できるすべてを含み、Multica が分類できない操作は必ず確認を求めます。カスタムリストでは選んだアプリだけを許可します。",
+ "catalog_all": "すべてのアプリ",
+ "catalog_curated": "厳選のみ",
+ "catalog_custom": "カスタムリスト",
+ "toast_connected": "アカウントを接続しました",
+ "toast_connect_failed": "接続を完了できませんでした。もう一度お試しください。",
+ "toast_disconnected": "接続を解除しました",
+ "toast_failed": "問題が発生しました。もう一度お試しください。",
+ "add": {
+ "title": "アプリを追加",
+ "description": "チームまたは自分用にアカウントを接続します。どのエージェントが使うかは各エージェントの「アプリ」ページで設定します。",
+ "search": "アプリを検索…",
+ "empty": "一致するアプリはありません。",
+ "curated": "厳選",
+ "recommended_team": "通常はチームアカウント",
+ "recommended_personal": "通常は個人アカウント",
+ "connect_team": "チーム用に接続",
+ "connect_personal": "自分のアカウントを接続",
+ "connecting": "接続中…",
+ "connected": "接続済み"
+ },
+ "disconnect_team": {
+ "title": "チームの {{app}} アカウントの接続を解除しますか?",
+ "description": "チームアカウントを使うエージェントはすぐにアクセスできなくなります。",
+ "agents": "使用中のエージェント",
+ "no_agents": "使用しているエージェントはありません。",
+ "active_tasks": "実行中: {{count}}",
+ "active_autopilots": "有効なオートパイロット: {{count}}",
+ "pending": "取り消される確認待ち: {{count}}",
+ "cancel": "キャンセル",
+ "confirm": "接続を解除"
+ },
+ "disconnect_personal": {
+ "title": "あなたの {{app}} アカウントの接続を解除しますか?",
+ "description": "あなたが起動した実行では使えなくなります。後で再接続できます。",
+ "cancel": "キャンセル",
+ "confirm": "接続を解除"
+ },
+ "detail": {
+ "team_title": "{{app}} · チームアカウント",
+ "personal_title": "{{app}} · 自分のアカウント",
+ "rules_description": "エージェントがこのアカウントでできること。エージェントのレベルはこれをより厳しくすることしかできません。",
+ "rules_read_only": "チームアカウントのルールを変更できるのはワークスペース管理者のみです。",
+ "default": "既定: {{policy}}",
+ "activity_empty": "まだ呼び出しはありません。",
+ "activity_failed": "アクティビティを読み込めませんでした。"
+ },
+ "classes": {
+ "read": {
+ "label": "読み取り",
+ "description": "検索・一覧・取得"
+ },
+ "write": {
+ "label": "書き込み",
+ "description": "コンテンツの作成・更新"
+ },
+ "send": {
+ "label": "送信",
+ "description": "メールやメッセージの送信、投稿、招待"
+ },
+ "delete": {
+ "label": "削除",
+ "description": "削除またはアーカイブ"
+ },
+ "share": {
+ "label": "共有",
+ "description": "権限の変更や外部への共有"
+ }
+ },
+ "policies": {
+ "allow": "許可",
+ "confirm": "先に確認",
+ "block": "ブロック"
+ },
+ "outcomes": {
+ "ok": "実行済み",
+ "error": "失敗",
+ "blocked": "ブロック",
+ "pending": "確認待ち",
+ "approved": "承認済み",
+ "rejected": "却下",
+ "rate_limited": "レート制限"
+ },
+ "scopes": {
+ "team": "チームアカウント",
+ "personal": "起動した人のアカウント"
+ },
+ "levels": {
+ "read": "読み取りのみ",
+ "confirm_writes": "書き込み前に確認",
+ "write": "書き込み可"
+ },
+ "request": {
+ "title_action": "{{agent}} が {{tool}} を実行しようとしています",
+ "title_connect": "{{agent}} が {{app}} の接続を依頼しています",
+ "pending_count_other": "{{count}} 件のアプリ操作が確認待ち",
+ "waiting_for": "{{name}} の確認待ち",
+ "expires": "{{when}}に期限切れ",
+ "redacted": "詳細は {{name}} だけが見られます。",
+ "arguments": "引数",
+ "edit": "編集",
+ "invalid_json": "引数は JSON オブジェクトである必要があります。",
+ "approve": "承認して実行",
+ "approve_all": "すべて承認",
+ "reject": "却下",
+ "reject_reason": "理由(任意、エージェントに表示されます)",
+ "connect": "{{app}} を接続",
+ "connected_continue": "接続しました",
+ "status": {
+ "approved": "承認済み",
+ "rejected": "却下",
+ "failed": "失敗",
+ "expired": "期限切れ",
+ "cancelled": "取り消し"
+ },
+ "toast_approved": "承認しました。エージェントが続行します。",
+ "toast_rejected": "却下しました。エージェントが方針を調整します。",
+ "toast_failed": "判断を記録できませんでした。",
+ "not_connected": "先にアカウントを接続してください。",
+ "connected_resumed": "{{app}} を接続しました。エージェントは中断したところから再開します。",
+ "rate_limited": "このアカウントは 1 分あたりの呼び出し上限に達しました。1 分後にもう一度承認してください。",
+ "rate_limited_some_other": "{{count}} 件のリクエストが 1 分あたりの上限に達しました。1 分後にもう一度承認してください。",
+ "withdrawn": "このエージェントを使えなくなったため、リクエストは取り下げられました。"
+ },
+ "tools": {
+ "tab": "ツール",
+ "description": "ツールの分類によって適用されるルールが決まります。自動分類が誤っているツールは修正できます。変更はワークスペース内のこのアプリのすべてのアカウントに適用されます。",
+ "read_only": "ツールの分類を変更できるのはワークスペース管理者のみです。",
+ "search": "ツールを検索",
+ "empty": "一致するツールはありません。",
+ "auto": "自動({{class}})",
+ "truncated": "{{total}} 件中 {{shown}} 件を表示しています。検索して絞り込んでください。"
+ },
+ "custom": {
+ "title": "カスタムアプリリスト",
+ "description": "エージェントには選んだアプリだけが表示され、ほかのアプリのアカウントは誰も接続できません。",
+ "selected_other": "{{count}} 個のアプリを選択中",
+ "cancel": "キャンセル",
+ "save": "リストを保存",
+ "saved": "アプリリストを保存しました",
+ "edit": "リストを編集",
+ "row_label": "許可するアプリ",
+ "row_description_other": "{{count}} 個のアプリを許可"
+ }
}
}
diff --git a/packages/views/locales/ko/agents.json b/packages/views/locales/ko/agents.json
index 897cb1f30b..4f5feda8d7 100644
--- a/packages/views/locales/ko/agents.json
+++ b/packages/views/locales/ko/agents.json
@@ -288,7 +288,7 @@
"environment": "환경",
"custom_args": "사용자 지정 인자",
"mcp_config": "MCP",
- "composio_mcp": "MCP 앱",
+ "composio_mcp": "앱",
"integrations": "연동",
"runtime_config": "라우팅",
"qoder_agent": "Qoder Cloud Agents",
@@ -553,22 +553,6 @@
"redacted_hint": "에이전트 소유자 또는 워크스페이스 관리자만 이 config를 읽을 수 있습니다.",
"dialog_json_help": "전체 서버 설정을 JSON으로 편집합니다."
},
- "composio_mcp": {
- "subtitle": "툴킷을 선택하면, 본인(이 에이전트의 생성자)이 직접 또는 하위 에이전트 체인을 통해 이 에이전트를 트리거할 때만 MCP 서버로 마운트됩니다.",
- "loading": "연결을 불러오는 중…",
- "load_failed": "연결된 앱을 불러오지 못했습니다. 잠시 후 다시 시도하세요.",
- "empty_title": "아직 연결된 앱이 없습니다",
- "empty_link_to_settings": "설정 → 연동에서 연결하기",
- "open_settings": "설정 열기",
- "connected": "연결됨",
- "toggle_aria": "이 에이전트에 {{toolkit}} 허용",
- "saving": "저장 중…",
- "save_failed_toast": "저장하지 못했습니다. 다시 시도하세요",
- "redacted_title": "설정됨 — 보기에서 숨김",
- "redacted_hint": "이 에이전트가 사용할 수 있는 앱은 생성자만 보거나 변경할 수 있습니다.",
- "shared_warning": "이 에이전트는 공유되어 있습니다. 이 에이전트를 실행할 수 있는 사람은 여기서 활성화한 Composio 앱을 사용할 수 있습니다. 이러한 앱이 민감한 데이터를 노출한다면 Private로 설정하거나 접근 범위를 좁히세요.",
- "workspace_warning": "워크스페이스에 공개: 워크스페이스의 모든 구성원이 이 에이전트를 통해 이러한 Composio 앱을 사용할 수 있습니다."
- },
"runtime_config": {
"mode_label": "라우팅 모드",
"mode_local": "Local",
@@ -681,6 +665,24 @@
"started_prefix": "{{when}} 시작됨",
"dispatched_prefix": "{{when}} 디스패치됨",
"queued_prefix": "{{when}} 대기 시작"
+ },
+ "connected_apps": {
+ "subtitle": "이 에이전트가 사용할 수 있는 앱입니다. 각 앱은 팀 계정 또는 실행한 사람의 계정으로, 선택한 수준에서 동작합니다.",
+ "loading": "앱을 불러오는 중…",
+ "load_failed": "이 에이전트의 앱을 불러오지 못했습니다.",
+ "empty": "아직 앱이 없습니다.",
+ "add_placeholder": "앱 추가…",
+ "account": "계정",
+ "level": "수준",
+ "remove": "{{app}} 제거",
+ "team_connected": "팀 계정 연결됨",
+ "team_missing": "팀 계정 미연결",
+ "personal_connected": "내 계정 연결됨",
+ "personal_missing": "이 앱을 아직 연결하지 않았습니다",
+ "team_admin_only": "에이전트에 팀 계정을 부여할 수 있는 사람은 워크스페이스 관리자뿐입니다.",
+ "team_shared_warning": "이 에이전트를 실행할 수 있는 사람은 누구나 이 앱들을 팀 계정으로 사용합니다.",
+ "manage_link": "설정 → 연결된 앱에서 계정 관리",
+ "save_failed_toast": "저장하지 못했습니다. 다시 시도하세요"
}
},
"char_counter": {
diff --git a/packages/views/locales/ko/inbox.json b/packages/views/locales/ko/inbox.json
index 216087905c..a148deb243 100644
--- a/packages/views/locales/ko/inbox.json
+++ b/packages/views/locales/ko/inbox.json
@@ -93,7 +93,11 @@
"quick_create_unconfirmed": "에이전트 생성 결과 미확인",
"autopilot_paused": "자동화 일시 중지됨",
"children_done": "하위 태스크가 모두 끝났습니다",
- "autopilot_quota_exceeded": "자동화 실행 한도 도달"
+ "autopilot_quota_exceeded": "자동화 실행 한도 도달",
+ "app_action_requested": "확인 필요",
+ "app_action_reminder": "확인 곧 만료",
+ "app_connect_requested": "앱 연결 요청",
+ "app_action_result": "앱 작업 결과"
},
"labels": {
"set_status_to": "상태 변경:",
diff --git a/packages/views/locales/ko/issues.json b/packages/views/locales/ko/issues.json
index 8a3782434d..31ace7316f 100644
--- a/packages/views/locales/ko/issues.json
+++ b/packages/views/locales/ko/issues.json
@@ -1809,5 +1809,24 @@
"empty_title": "아직 저장된 뷰가 없습니다",
"empty_description": "태스크 목록에서 필터와 표시 방식을 맞춘 뒤 뷰로 저장하세요."
}
+ },
+ "app_calls": {
+ "section_title": "앱",
+ "chips_label": "이 실행에서 사용한 앱",
+ "calls_count_other": "{{count}}회 호출",
+ "more": "+{{count}}개 더",
+ "scope": {
+ "team": "팀 계정",
+ "personal": "개인 계정"
+ },
+ "outcome": {
+ "ok": "실행됨",
+ "error": "실패",
+ "blocked": "차단됨",
+ "pending": "대기 중",
+ "approved": "승인됨",
+ "rejected": "거절됨",
+ "rate_limited": "속도 제한"
+ }
}
}
diff --git a/packages/views/locales/ko/settings.json b/packages/views/locales/ko/settings.json
index 11c7ee4b8c..e8e7ae7b1f 100644
--- a/packages/views/locales/ko/settings.json
+++ b/packages/views/locales/ko/settings.json
@@ -1219,35 +1219,6 @@
"inbound_pending_hint": "Feishu/Lark에서 이 봇에 메시지를 보내 수신을 확인하세요. 도착하지 않으면 지속 연결 모드, im.message.receive_v1 구독, 앱 게시 및 승인 상태를 확인하세요. 기존 연결에는 확인 기록이 없을 수 있습니다.",
"inbound_verified_hint": "이번 연결에서 유효한 메시지를 받았습니다. 지속적인 연결, 에이전트 실행 또는 답장 성공을 의미하지는 않습니다."
},
- "composio": {
- "page_description": "에이전트가 사용할 앱을 연결하세요.",
- "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 connectable apps yet",
- "empty_description": "No toolkit has an enabled auth config in your Composio project yet. Enable one in the Composio dashboard to make it available here.",
- "search_placeholder": "Search toolkits…",
- "connect": "Connect",
- "connecting": "Connecting…",
- "connected": "Connected",
- "disconnect": "Disconnect",
- "disconnecting": "Disconnecting…",
- "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": "Slack에서 에이전트와 대화하거나 /issue로 태스크를 만드세요.",
@@ -1467,7 +1438,175 @@
"title": "에이전트에 도구를 제공하는 방법",
"current": "현재 페이지",
"mcp": "관리자가 추가해 워크스페이스에서 공유하고, 에이전트별로 할당합니다.",
- "apps": "내 계정으로 Composio를 통해 승인하고, 내가 소유한 에이전트에서 사용합니다.",
+ "apps": "Multica로 연결한 팀 또는 개인 계정으로, 에이전트마다 계정과 권한 수준을 지정합니다.",
"plugins": "설치하면 도구, 예약 훅, 저장소를 추가할 수 있으며 플러그인마다 권한을 부여합니다."
+ },
+ "connected_apps": {
+ "description": "에이전트가 외부 앱을 사용할 때 쓰는 계정입니다. 모든 호출은 Multica를 거치며, 규칙을 적용하고 보내기·삭제·공유 전에 확인을 받습니다.",
+ "add_app": "앱 추가",
+ "loading": "앱을 불러오는 중…",
+ "load_failed": "앱을 불러오지 못했습니다.",
+ "team_title": "팀 계정",
+ "team_description": "고객 지원 메일함이나 회사 GitHub처럼 워크스페이스가 소유한 공유 계정입니다. 관리자가 연결하며, 팀 계정을 받은 에이전트는 그 계정으로 작업합니다.",
+ "team_empty": "아직 팀 계정이 없습니다.",
+ "team_empty_member": "아직 팀 계정이 없습니다. 워크스페이스 관리자에게 연결을 요청하세요.",
+ "personal_title": "내 계정",
+ "personal_description": "내 계정입니다. 내가 실행을 시작하면 '실행한 사람의 계정'으로 설정된 앱이 이 계정을 사용합니다.",
+ "personal_empty": "아직 연결한 계정이 없습니다.",
+ "connected_by": "{{name}} 님이 연결",
+ "last_used": "마지막 사용 {{when}}",
+ "last_used_never": "사용한 적 없음",
+ "used_by_other": "에이전트 {{count}}개가 사용 중",
+ "expired": "다시 연결 필요",
+ "reconnect": "다시 연결",
+ "rules": "규칙",
+ "activity": "활동",
+ "disconnect": "연결 해제",
+ "catalog_title": "사용 가능한 앱",
+ "catalog_label": "멤버가 추가할 수 있는 앱",
+ "catalog_description": "엄선된 앱에는 검토된 기본 규칙이 있습니다. '모든 앱'은 Composio로 연결할 수 있는 모든 앱을 포함하며, Multica가 분류하지 못한 작업은 항상 먼저 확인을 받습니다. 사용자 지정 목록은 선택한 앱만 허용합니다.",
+ "catalog_all": "모든 앱",
+ "catalog_curated": "엄선된 앱만",
+ "catalog_custom": "사용자 지정 목록",
+ "toast_connected": "계정이 연결되었습니다",
+ "toast_connect_failed": "연결을 완료하지 못했습니다. 다시 시도하세요.",
+ "toast_disconnected": "연결이 해제되었습니다",
+ "toast_failed": "문제가 발생했습니다. 다시 시도하세요.",
+ "add": {
+ "title": "앱 추가",
+ "description": "팀 또는 나를 위해 계정을 연결하세요. 어떤 에이전트가 사용할지는 각 에이전트의 앱 페이지에서 설정합니다.",
+ "search": "앱 검색…",
+ "empty": "일치하는 앱이 없습니다.",
+ "curated": "엄선",
+ "recommended_team": "보통 팀 계정",
+ "recommended_personal": "보통 개인 계정",
+ "connect_team": "팀 계정 연결",
+ "connect_personal": "내 계정 연결",
+ "connecting": "연결 중…",
+ "connected": "연결됨"
+ },
+ "disconnect_team": {
+ "title": "팀 {{app}} 계정 연결을 해제할까요?",
+ "description": "팀 계정을 쓰는 에이전트는 즉시 접근 권한을 잃습니다.",
+ "agents": "사용 중인 에이전트",
+ "no_agents": "사용 중인 에이전트가 없습니다.",
+ "active_tasks": "진행 중인 실행: {{count}}",
+ "active_autopilots": "활성 오토파일럿: {{count}}",
+ "pending": "취소될 확인 요청: {{count}}",
+ "cancel": "취소",
+ "confirm": "연결 해제"
+ },
+ "disconnect_personal": {
+ "title": "내 {{app}} 계정 연결을 해제할까요?",
+ "description": "내가 시작한 실행에서 더 이상 사용할 수 없습니다. 나중에 다시 연결할 수 있습니다.",
+ "cancel": "취소",
+ "confirm": "연결 해제"
+ },
+ "detail": {
+ "team_title": "{{app}} · 팀 계정",
+ "personal_title": "{{app}} · 내 계정",
+ "rules_description": "에이전트가 이 계정으로 할 수 있는 일입니다. 에이전트 수준은 이 규칙을 더 엄격하게만 만들 수 있습니다.",
+ "rules_read_only": "팀 계정 규칙은 워크스페이스 관리자만 변경할 수 있습니다.",
+ "default": "기본값: {{policy}}",
+ "activity_empty": "아직 호출이 없습니다.",
+ "activity_failed": "활동을 불러오지 못했습니다."
+ },
+ "classes": {
+ "read": {
+ "label": "읽기",
+ "description": "검색, 목록, 가져오기"
+ },
+ "write": {
+ "label": "쓰기",
+ "description": "콘텐츠 생성 및 수정"
+ },
+ "send": {
+ "label": "보내기",
+ "description": "메일·메시지 보내기, 게시, 초대"
+ },
+ "delete": {
+ "label": "삭제",
+ "description": "삭제 또는 보관"
+ },
+ "share": {
+ "label": "공유",
+ "description": "권한 변경 또는 외부 공유"
+ }
+ },
+ "policies": {
+ "allow": "허용",
+ "confirm": "먼저 확인",
+ "block": "차단"
+ },
+ "outcomes": {
+ "ok": "실행됨",
+ "error": "실패",
+ "blocked": "차단됨",
+ "pending": "확인 대기",
+ "approved": "승인됨",
+ "rejected": "거절됨",
+ "rate_limited": "속도 제한"
+ },
+ "scopes": {
+ "team": "팀 계정",
+ "personal": "실행한 사람의 계정"
+ },
+ "levels": {
+ "read": "읽기 전용",
+ "confirm_writes": "쓰기 전 확인",
+ "write": "쓰기 가능"
+ },
+ "request": {
+ "title_action": "{{agent}}이(가) {{tool}} 실행을 요청합니다",
+ "title_connect": "{{agent}}이(가) {{app}} 연결을 요청합니다",
+ "pending_count_other": "앱 작업 {{count}}개가 확인 대기 중",
+ "waiting_for": "{{name}} 님의 확인 대기 중",
+ "expires": "{{when}} 만료",
+ "redacted": "세부 내용은 {{name}} 님만 볼 수 있습니다.",
+ "arguments": "인수",
+ "edit": "편집",
+ "invalid_json": "인수는 JSON 객체여야 합니다.",
+ "approve": "승인 후 실행",
+ "approve_all": "모두 승인",
+ "reject": "거절",
+ "reject_reason": "이유 (선택, 에이전트에게 표시됨)",
+ "connect": "{{app}} 연결",
+ "connected_continue": "연결했습니다",
+ "status": {
+ "approved": "승인됨",
+ "rejected": "거절됨",
+ "failed": "실패",
+ "expired": "만료됨",
+ "cancelled": "취소됨"
+ },
+ "toast_approved": "승인했습니다. 에이전트가 이어서 진행합니다.",
+ "toast_rejected": "거절했습니다. 에이전트가 방식을 조정합니다.",
+ "toast_failed": "결정을 기록하지 못했습니다.",
+ "not_connected": "먼저 계정을 연결하세요.",
+ "connected_resumed": "{{app}} 연결됨. 에이전트가 멈춘 곳부터 이어서 진행합니다.",
+ "rate_limited": "이 계정이 분당 호출 한도에 도달했습니다. 1분 후에 다시 승인하세요.",
+ "rate_limited_some_other": "요청 {{count}}개가 분당 한도에 걸렸습니다. 1분 후에 다시 승인하세요.",
+ "withdrawn": "이 에이전트를 더 이상 사용할 수 없어 요청이 철회되었습니다."
+ },
+ "tools": {
+ "tab": "도구",
+ "description": "도구의 분류에 따라 적용되는 규칙이 정해집니다. 자동 분류가 잘못된 도구는 수정할 수 있으며, 변경 사항은 워크스페이스에서 이 앱의 모든 계정에 적용됩니다.",
+ "read_only": "도구 분류는 워크스페이스 관리자만 변경할 수 있습니다.",
+ "search": "도구 검색",
+ "empty": "일치하는 도구가 없습니다.",
+ "auto": "자동 ({{class}})",
+ "truncated": "{{total}}개 중 {{shown}}개 표시 중. 검색해서 좁혀 보세요."
+ },
+ "custom": {
+ "title": "사용자 지정 앱 목록",
+ "description": "에이전트는 선택한 앱만 볼 수 있고, 다른 앱의 계정은 누구도 연결할 수 없습니다.",
+ "selected_other": "앱 {{count}}개 선택됨",
+ "cancel": "취소",
+ "save": "목록 저장",
+ "saved": "앱 목록을 저장했습니다",
+ "edit": "목록 편집",
+ "row_label": "허용된 앱",
+ "row_description_other": "앱 {{count}}개 허용"
+ }
}
}
diff --git a/packages/views/locales/ru/agents.json b/packages/views/locales/ru/agents.json
index b497caacd0..f482c38e45 100644
--- a/packages/views/locales/ru/agents.json
+++ b/packages/views/locales/ru/agents.json
@@ -324,7 +324,7 @@
"environment": "Окружение",
"custom_args": "Аргументы",
"mcp_config": "MCP",
- "composio_mcp": "MCP-приложения",
+ "composio_mcp": "Приложения",
"integrations": "Интеграции",
"runtime_config": "Маршрутизация",
"qoder_agent": "Qoder Cloud Agents",
@@ -760,22 +760,6 @@
"redacted_hint": "Просматривать эту конфигурацию может только владелец агента или администратор рабочего пространства.",
"dialog_json_help": "Редактируйте полную конфигурацию сервера в формате JSON."
},
- "composio_mcp": {
- "subtitle": "Отметьте инструментарий, чтобы этот агент мог подключить его как MCP-сервер — но только когда запуск инициировали именно вы (его создатель), напрямую или через цепочку подагентов.",
- "loading": "Загрузка ваших подключений…",
- "load_failed": "Не удалось загрузить ваши подключённые приложения. Повторите попытку чуть позже.",
- "empty_title": "Пока нет подключённых приложений",
- "empty_link_to_settings": "Подключите в настройках → Интеграции",
- "connected": "Подключено",
- "toggle_aria": "Разрешить {{toolkit}} для этого агента",
- "saving": "Сохранение…",
- "save_failed_toast": "Не удалось сохранить — попробуйте ещё раз",
- "redacted_title": "Настроено — скрыто от вас",
- "redacted_hint": "Просматривать или менять, какие приложения может использовать агент, может только его создатель.",
- "shared_warning": "Этот агент доступен другим. Люди, которые могут его запускать, смогут использовать включённые здесь приложения Composio. Если эти приложения работают с чувствительными данными, сделайте агента приватным или сузьте список доступа.",
- "workspace_warning": "Публичный доступ для рабочего пространства: любой участник рабочего пространства сможет использовать эти приложения Composio через этого агента.",
- "open_settings": "Открыть настройки"
- },
"runtime_config": {
"mode_label": "Режим маршрутизации",
"mode_local": "Локальный",
@@ -894,6 +878,24 @@
"queued_prefix": "В очереди с {{when}}",
"runs_few": "запуска",
"runs_many": "запусков"
+ },
+ "connected_apps": {
+ "subtitle": "Приложения, доступные этому агенту. Каждое использует аккаунт команды или того, кто запустил выполнение, с выбранным уровнем доступа.",
+ "loading": "Загрузка приложений…",
+ "load_failed": "Не удалось загрузить приложения этого агента.",
+ "empty": "Приложений пока нет.",
+ "add_placeholder": "Добавить приложение…",
+ "account": "Аккаунт",
+ "level": "Уровень доступа",
+ "remove": "Удалить {{app}}",
+ "team_connected": "Аккаунт команды подключён",
+ "team_missing": "Аккаунт команды не подключён",
+ "personal_connected": "Ваш аккаунт подключён",
+ "personal_missing": "Вы ещё не подключили это приложение",
+ "team_admin_only": "Только администраторы рабочего пространства могут предоставить агенту аккаунт команды.",
+ "team_shared_warning": "Любой, кто может запускать этого агента, будет действовать в этих приложениях от имени аккаунта команды.",
+ "manage_link": "Управление аккаунтами: Настройки → Подключённые приложения",
+ "save_failed_toast": "Не удалось сохранить — попробуйте ещё раз"
}
},
"char_counter": {
diff --git a/packages/views/locales/ru/inbox.json b/packages/views/locales/ru/inbox.json
index 7474715f32..e9fb2eec57 100644
--- a/packages/views/locales/ru/inbox.json
+++ b/packages/views/locales/ru/inbox.json
@@ -99,7 +99,11 @@
"quick_create_unconfirmed": "Создание с помощью агента не подтверждено",
"autopilot_paused": "Автопилот приостановлен",
"children_done": "Подзадачи завершены",
- "autopilot_quota_exceeded": "Достигнут лимит запусков Автопилота"
+ "autopilot_quota_exceeded": "Достигнут лимит запусков Автопилота",
+ "app_action_requested": "Требуется ваше подтверждение",
+ "app_action_reminder": "Срок подтверждения скоро истечёт",
+ "app_connect_requested": "Подключить приложение",
+ "app_action_result": "Результат действия приложения"
},
"labels": {
"set_status_to": "Установлен статус",
diff --git a/packages/views/locales/ru/issues.json b/packages/views/locales/ru/issues.json
index f6a4ecf0b8..1392d5ef12 100644
--- a/packages/views/locales/ru/issues.json
+++ b/packages/views/locales/ru/issues.json
@@ -2022,5 +2022,27 @@
},
"unread_filter_error": {
"title": "Не удалось загрузить непрочитанные задачи"
+ },
+ "app_calls": {
+ "section_title": "Приложения",
+ "chips_label": "Приложения в этом выполнении",
+ "calls_count_one": "{{count}} вызов",
+ "calls_count_few": "{{count}} вызова",
+ "calls_count_many": "{{count}} вызовов",
+ "calls_count_other": "{{count}} вызова",
+ "more": "Ещё {{count}}",
+ "scope": {
+ "team": "Аккаунт команды",
+ "personal": "Личный аккаунт"
+ },
+ "outcome": {
+ "ok": "Выполнено",
+ "error": "Ошибка",
+ "blocked": "Заблокировано",
+ "pending": "Ожидание",
+ "approved": "Одобрено",
+ "rejected": "Отклонено",
+ "rate_limited": "Лимит вызовов достигнут"
+ }
}
}
diff --git a/packages/views/locales/ru/settings.json b/packages/views/locales/ru/settings.json
index 86184c0040..27229c61b4 100644
--- a/packages/views/locales/ru/settings.json
+++ b/packages/views/locales/ru/settings.json
@@ -964,35 +964,6 @@
"inbound_pending_hint": "Отправьте боту сообщение в Feishu/Lark для проверки приёма. Если оно не приходит, проверьте режим постоянного соединения, подписку im.message.receive_v1, публикацию и одобрение приложения. У существующих привязок результат проверки ещё может отсутствовать.",
"inbound_verified_hint": "Через эту привязку получено корректное сообщение. Это не подтверждает постоянное соединение, выполнение агентом или отправку ответов."
},
- "composio": {
- "page_description": "Подключите приложения, которые смогут использовать ваши агенты.",
- "not_enabled_title": "Интеграция с Composio не включена",
- "not_enabled_description_prefix": "Задайте",
- "not_enabled_description_suffix": "на сервере, чтобы включить подключение наборов инструментов Composio.",
- "loading": "Загрузка наборов инструментов…",
- "load_failed": "Не удалось загрузить наборы инструментов Composio.",
- "empty_title": "Пока нет доступных для подключения приложений",
- "empty_description": "Ни один набор инструментов пока не имеет включённой конфигурации авторизации в вашем проекте Composio. Включите её в панели Composio, чтобы сделать доступной здесь.",
- "search_placeholder": "Поиск наборов инструментов…",
- "connect": "Подключить",
- "connecting": "Подключение…",
- "connected": "Подключено",
- "disconnect": "Отключить",
- "disconnecting": "Отключение…",
- "connect_failed": "Не удалось начать подключение. Попробуйте снова.",
- "disconnect_failed": "Не удалось отключить. Попробуйте снова.",
- "toast_disconnected": "Отключено",
- "disconnect_confirm_title": "Отключить это приложение?",
- "disconnect_confirm_description": "Ваша подключённая учётная запись будет отозвана в Composio, и ваши агенты потеряют доступ к этому набору инструментов. Вы можете подключиться снова позже.",
- "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": "Общайтесь с агентами в Slack или создавайте задачи через /issue.",
@@ -1499,7 +1470,190 @@
"title": "Способы дать агентам инструменты",
"current": "Эта страница",
"mcp": "Добавляются администраторами и доступны всему рабочему пространству, затем назначаются отдельным агентам.",
- "apps": "Авторизуются через Composio с использованием вашей учётной записи и включаются для агентов, которыми вы владеете.",
+ "apps": "Аккаунты команды или личные аккаунты, подключённые через Multica. Для каждого агента выбираются аккаунт и уровень доступа.",
"plugins": "Установленные пакеты, которые могут добавлять инструменты, запланированные хуки и хранилище, каждый со своими правами доступа."
+ },
+ "connected_apps": {
+ "description": "Аккаунты, через которые действуют ваши агенты. Каждый вызов проходит через Multica, которая применяет ваши правила и запрашивает подтверждение перед отправкой, удалением или предоставлением доступа.",
+ "add_app": "Добавить приложение",
+ "loading": "Загрузка приложений…",
+ "load_failed": "Не удалось загрузить приложения.",
+ "team_title": "Аккаунты команды",
+ "team_description": "Общие аккаунты рабочего пространства, например почта поддержки или GitHub компании. Их подключают администраторы; агенты, которым предоставлен доступ, действуют от имени этих аккаунтов.",
+ "team_empty": "Пока нет аккаунтов команды.",
+ "team_empty_member": "Пока нет аккаунтов команды. Попросите администратора рабочего пространства подключить аккаунт.",
+ "personal_title": "Мои аккаунты",
+ "personal_description": "Ваши личные аккаунты. Когда вы запускаете выполнение, агенты используют их для приложений с настройкой «Аккаунт инициатора».",
+ "personal_empty": "Вы ещё не подключили ни одного аккаунта.",
+ "connected_by": "Подключил(а) {{name}}",
+ "last_used": "Последнее использование: {{when}}",
+ "last_used_never": "Ещё не использовался",
+ "used_by_one": "Использует {{count}} агент",
+ "used_by_few": "Используют {{count}} агента",
+ "used_by_many": "Используют {{count}} агентов",
+ "used_by_other": "Используют {{count}} агента",
+ "expired": "Нужно переподключить",
+ "reconnect": "Переподключить",
+ "rules": "Правила",
+ "activity": "Активность",
+ "disconnect": "Отключить",
+ "catalog_title": "Доступные приложения",
+ "catalog_label": "Приложения, которые могут добавлять участники",
+ "catalog_description": "Избранные приложения содержат проверенные правила по умолчанию. Режим «Все приложения» включает всё, что можно подключить через Composio; действия, которые Multica не может классифицировать, всегда требуют подтверждения. Свой список разрешает только выбранные приложения.",
+ "catalog_all": "Все приложения",
+ "catalog_curated": "Только избранные",
+ "catalog_custom": "Свой список",
+ "toast_connected": "Аккаунт подключён",
+ "toast_connect_failed": "Не удалось завершить подключение. Попробуйте ещё раз.",
+ "toast_disconnected": "Аккаунт отключён",
+ "toast_failed": "Что-то пошло не так. Попробуйте ещё раз.",
+ "add": {
+ "title": "Добавить приложение",
+ "description": "Подключите аккаунт для команды или для себя. Доступ агентов настраивается на вкладке «Приложения» каждого агента.",
+ "search": "Поиск приложений…",
+ "empty": "Подходящих приложений нет.",
+ "curated": "Избранное",
+ "recommended_team": "Обычно аккаунт команды",
+ "recommended_personal": "Обычно личный аккаунт",
+ "connect_team": "Подключить для команды",
+ "connect_personal": "Подключить мой аккаунт",
+ "connecting": "Подключение…",
+ "connected": "Подключено"
+ },
+ "disconnect_team": {
+ "title": "Отключить аккаунт команды в {{app}}?",
+ "description": "Агенты, использующие аккаунт команды, сразу потеряют доступ.",
+ "agents": "Агенты с доступом",
+ "no_agents": "Ни один агент не использует этот аккаунт.",
+ "active_tasks": "Выполнения в процессе: {{count}}",
+ "active_autopilots": "Активные автоматизации: {{count}}",
+ "pending": "Подтверждения, которые будут отменены: {{count}}",
+ "cancel": "Отмена",
+ "confirm": "Отключить"
+ },
+ "disconnect_personal": {
+ "title": "Отключить ваш аккаунт в {{app}}?",
+ "description": "Запускаемые вами выполнения больше не смогут его использовать. Позже аккаунт можно подключить снова.",
+ "cancel": "Отмена",
+ "confirm": "Отключить"
+ },
+ "detail": {
+ "team_title": "{{app}} · аккаунт команды",
+ "personal_title": "{{app}} · мой аккаунт",
+ "rules_description": "Действия, разрешённые агентам через этот аккаунт. Уровень доступа агента может только ужесточить эти правила.",
+ "rules_read_only": "Только администраторы рабочего пространства могут менять правила аккаунта команды.",
+ "default": "По умолчанию: {{policy}}",
+ "activity_empty": "Вызовов пока нет.",
+ "activity_failed": "Не удалось загрузить активность."
+ },
+ "classes": {
+ "read": {
+ "label": "Чтение",
+ "description": "Поиск, списки и получение данных"
+ },
+ "write": {
+ "label": "Запись",
+ "description": "Создание и изменение содержимого"
+ },
+ "send": {
+ "label": "Отправка",
+ "description": "Отправка писем и сообщений, публикации и приглашения"
+ },
+ "delete": {
+ "label": "Удаление",
+ "description": "Удаление или архивирование"
+ },
+ "share": {
+ "label": "Доступ",
+ "description": "Изменение прав или предоставление внешнего доступа"
+ }
+ },
+ "policies": {
+ "allow": "Разрешить",
+ "confirm": "Сначала спросить",
+ "block": "Запретить"
+ },
+ "outcomes": {
+ "ok": "Выполнено",
+ "error": "Ошибка",
+ "blocked": "Заблокировано",
+ "pending": "Ожидание",
+ "approved": "Одобрено",
+ "rejected": "Отклонено",
+ "rate_limited": "Лимит вызовов достигнут"
+ },
+ "scopes": {
+ "team": "Аккаунт команды",
+ "personal": "Аккаунт инициатора"
+ },
+ "levels": {
+ "read": "Только чтение",
+ "confirm_writes": "Подтверждать запись",
+ "write": "Запись разрешена"
+ },
+ "request": {
+ "title_action": "{{agent}} хочет выполнить {{tool}}",
+ "title_connect": "{{agent}} просит подключить {{app}}",
+ "pending_count_one": "{{count}} действие приложения ожидает подтверждения",
+ "pending_count_few": "{{count}} действия приложения ожидают подтверждения",
+ "pending_count_many": "{{count}} действий приложения ожидают подтверждения",
+ "pending_count_other": "{{count}} действия приложения ожидают подтверждения",
+ "waiting_for": "Ожидание: {{name}}",
+ "expires": "Истекает {{when}}",
+ "redacted": "Только {{name}} может видеть подробности.",
+ "arguments": "Аргументы",
+ "edit": "Изменить",
+ "invalid_json": "Аргументы должны быть объектом JSON.",
+ "approve": "Одобрить и выполнить",
+ "approve_all": "Одобрить все",
+ "reject": "Отклонить",
+ "reject_reason": "Причина (необязательно, агент её увидит)",
+ "connect": "Подключить {{app}}",
+ "connected_continue": "Уже подключено",
+ "status": {
+ "approved": "Одобрено",
+ "rejected": "Отклонено",
+ "failed": "Ошибка",
+ "expired": "Срок истёк",
+ "cancelled": "Отменено"
+ },
+ "toast_approved": "Одобрено. Агент продолжит работу.",
+ "toast_rejected": "Отклонено. Агент скорректирует свои действия.",
+ "toast_failed": "Не удалось сохранить ваше решение.",
+ "not_connected": "Сначала подключите аккаунт.",
+ "connected_resumed": "{{app}} подключено. Агент продолжит с того места, где остановился.",
+ "rate_limited": "Достигнут лимит вызовов в минуту для этого аккаунта. Повторите одобрение через минуту.",
+ "rate_limited_some_one": "{{count}} запрос достиг минутного лимита. Одобрите его повторно через минуту.",
+ "rate_limited_some_few": "{{count}} запроса достигли минутного лимита. Одобрите их повторно через минуту.",
+ "rate_limited_some_many": "{{count}} запросов достигли минутного лимита. Одобрите их повторно через минуту.",
+ "rate_limited_some_other": "{{count}} запроса достигли минутного лимита. Одобрите их повторно через минуту.",
+ "withdrawn": "Вы больше не можете использовать этого агента, поэтому запрос отозван."
+ },
+ "tools": {
+ "tab": "Инструменты",
+ "description": "Категория инструмента определяет применяемое правило. Исправьте ошибки автоматической классификации; изменение действует для всех аккаунтов этого приложения в рабочем пространстве.",
+ "read_only": "Только администраторы рабочего пространства могут менять категории инструментов.",
+ "search": "Поиск инструментов",
+ "empty": "Подходящих инструментов нет.",
+ "auto": "Автоматически ({{class}})",
+ "truncated": "Показано {{shown}} из {{total}}. Уточните поиск, чтобы сократить список."
+ },
+ "custom": {
+ "title": "Свой список приложений",
+ "description": "Агенты видят только выбранные вами приложения. Никто не сможет подключить аккаунт другого приложения.",
+ "selected_one": "Выбрано {{count}} приложение",
+ "selected_few": "Выбрано {{count}} приложения",
+ "selected_many": "Выбрано {{count}} приложений",
+ "selected_other": "Выбрано {{count}} приложения",
+ "cancel": "Отмена",
+ "save": "Сохранить список",
+ "saved": "Список приложений сохранён",
+ "edit": "Изменить список",
+ "row_label": "Разрешённые приложения",
+ "row_description_one": "Разрешено {{count}} приложение",
+ "row_description_few": "Разрешено {{count}} приложения",
+ "row_description_many": "Разрешено {{count}} приложений",
+ "row_description_other": "Разрешено {{count}} приложения"
+ }
}
}
diff --git a/packages/views/locales/zh-Hans/agents.json b/packages/views/locales/zh-Hans/agents.json
index 6ee649cd98..d6711687df 100644
--- a/packages/views/locales/zh-Hans/agents.json
+++ b/packages/views/locales/zh-Hans/agents.json
@@ -288,7 +288,7 @@
"environment": "环境变量",
"custom_args": "自定义参数",
"mcp_config": "MCP",
- "composio_mcp": "MCP 应用",
+ "composio_mcp": "应用",
"integrations": "集成",
"runtime_config": "路由",
"qoder_agent": "Qoder Cloud Agents",
@@ -703,22 +703,6 @@
"redacted_hint": "只有智能体 owner 或工作区 admin 可以查看此配置。",
"dialog_json_help": "以 JSON 编辑完整的服务器配置。"
},
- "composio_mcp": {
- "subtitle": "勾选 toolkit,只在你自己(这个智能体的创建者)直接或通过下级智能体链路触发这个智能体时,才把它挂载为 MCP server。",
- "loading": "正在加载你的连接…",
- "load_failed": "无法加载你已连接的应用,请稍后重试。",
- "empty_title": "还没有已连接的应用",
- "empty_link_to_settings": "去 \"设置 → 集成\" 连一个",
- "open_settings": "打开设置",
- "connected": "已连接",
- "toggle_aria": "允许该智能体使用 {{toolkit}}",
- "saving": "正在保存…",
- "save_failed_toast": "保存失败,请重试",
- "redacted_title": "已配置——对你隐藏",
- "redacted_hint": "只有该智能体的创建者才能查看或修改它可使用的应用。",
- "shared_warning": "该智能体已共享。能够运行该智能体的人可以通过它使用你在此启用的 Composio 应用。如果这些应用涉及敏感数据,请改用\"私有\"或缩小访问范围。",
- "workspace_warning": "公开给工作区:工作区内任何成员都可以通过该智能体使用这些 Composio 应用。"
- },
"runtime_config": {
"mode_label": "路由模式",
"mode_local": "Local",
@@ -831,6 +815,24 @@
"started_prefix": "{{when}}启动",
"dispatched_prefix": "{{when}}派发",
"queued_prefix": "{{when}}排队"
+ },
+ "connected_apps": {
+ "subtitle": "这个智能体可以使用的应用。每个应用以团队账号或触发者的账号身份操作,权限级别由你设定。",
+ "loading": "正在加载应用…",
+ "load_failed": "无法加载此智能体的应用。",
+ "empty": "还没有应用。",
+ "add_placeholder": "添加应用…",
+ "account": "账号",
+ "level": "权限",
+ "remove": "移除 {{app}}",
+ "team_connected": "团队账号已连接",
+ "team_missing": "团队账号未连接",
+ "personal_connected": "你的账号已连接",
+ "personal_missing": "你还没有连接这个应用",
+ "team_admin_only": "只有工作区管理员可以给智能体团队账号。",
+ "team_shared_warning": "能运行这个智能体的人,都会以团队账号身份使用这些应用。",
+ "manage_link": "在 设置 → 已连接应用 中管理账号",
+ "save_failed_toast": "保存失败,请重试"
}
},
"char_counter": {
diff --git a/packages/views/locales/zh-Hans/inbox.json b/packages/views/locales/zh-Hans/inbox.json
index df953bb023..c9fd8719db 100644
--- a/packages/views/locales/zh-Hans/inbox.json
+++ b/packages/views/locales/zh-Hans/inbox.json
@@ -93,7 +93,11 @@
"quick_create_unconfirmed": "通过智能体创建结果未确认",
"autopilot_paused": "自动化已暂停",
"children_done": "子任务已全部结束",
- "autopilot_quota_exceeded": "自动化执行次数已用完"
+ "autopilot_quota_exceeded": "自动化执行次数已用完",
+ "app_action_requested": "等待你确认",
+ "app_action_reminder": "确认即将过期",
+ "app_connect_requested": "请连接应用",
+ "app_action_result": "应用操作结果"
},
"labels": {
"set_status_to": "状态设为",
diff --git a/packages/views/locales/zh-Hans/issues.json b/packages/views/locales/zh-Hans/issues.json
index c08ce27c1c..badbfe2451 100644
--- a/packages/views/locales/zh-Hans/issues.json
+++ b/packages/views/locales/zh-Hans/issues.json
@@ -1809,5 +1809,24 @@
"empty_title": "还没有保存的视图",
"empty_description": "在任务列表里调好筛选和显示方式,然后另存为视图。"
}
+ },
+ "app_calls": {
+ "section_title": "应用",
+ "chips_label": "本次运行用到的应用",
+ "calls_count_other": "{{count}} 次调用",
+ "more": "还有 {{count}} 个",
+ "scope": {
+ "team": "团队账号",
+ "personal": "个人账号"
+ },
+ "outcome": {
+ "ok": "已执行",
+ "error": "失败",
+ "blocked": "已拦截",
+ "pending": "等待确认",
+ "approved": "已批准",
+ "rejected": "已拒绝",
+ "rate_limited": "已限流"
+ }
}
}
diff --git a/packages/views/locales/zh-Hans/settings.json b/packages/views/locales/zh-Hans/settings.json
index ec7e15c263..a3a3cec568 100644
--- a/packages/views/locales/zh-Hans/settings.json
+++ b/packages/views/locales/zh-Hans/settings.json
@@ -950,35 +950,6 @@
"inbound_pending_hint": "请在飞书/Lark 中给此机器人发送消息以验证接收。若未收到,请检查长连接模式、im.message.receive_v1 事件订阅以及应用发布和审批状态。已有绑定可能尚无验证记录。",
"inbound_verified_hint": "本次绑定已收到有效消息;这不代表持续在线、智能体执行成功或回复成功。"
},
- "composio": {
- "page_description": "连接智能体可使用的应用。",
- "not_enabled_title": "Composio 集成未启用",
- "not_enabled_description_prefix": "在服务器上设置",
- "not_enabled_description_suffix": "以启用 Composio toolkit 连接。",
- "loading": "正在加载 toolkit…",
- "load_failed": "加载 Composio toolkit 失败。",
- "empty_title": "还没有可连接的应用",
- "empty_description": "你的 Composio 项目里还没有启用 auth config 的 toolkit。请在 Composio 后台启用一个 auth config,它才会出现在这里。",
- "search_placeholder": "搜索 toolkit…",
- "connect": "连接",
- "connecting": "连接中…",
- "connected": "已连接",
- "disconnect": "断开",
- "disconnecting": "断开中...",
- "connect_failed": "无法发起连接,请重试。",
- "disconnect_failed": "无法断开连接,请重试。",
- "toast_disconnected": "已断开",
- "disconnect_confirm_title": "断开这个应用?",
- "disconnect_confirm_description": "你的已连接账号将在 Composio 侧被撤销,你的智能体将失去对该 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": "在 Slack 中与智能体对话,或用 /issue 创建任务。",
@@ -1467,7 +1438,175 @@
"title": "为智能体接入工具的方式",
"current": "当前页面",
"mcp": "由管理员添加、在工作区内共享,再按智能体分配。",
- "apps": "用你自己的账号通过 Composio 授权,在你拥有的智能体上启用。",
+ "apps": "通过 Multica 连接的团队或个人账号,按智能体分配账号和权限级别。",
"plugins": "安装后可提供工具、定时 hook 和存储,每个插件单独授权。"
+ },
+ "connected_apps": {
+ "description": "智能体通过这些账号操作外部应用。每次调用都经过 Multica:按规则执行,发送、删除、分享前先征得同意。",
+ "add_app": "添加应用",
+ "loading": "正在加载应用…",
+ "load_failed": "无法加载应用。",
+ "team_title": "团队账号",
+ "team_description": "工作区共有的账号,例如客服邮箱或公司 GitHub。由管理员连接;被授予团队账号的智能体以该账号身份操作。",
+ "team_empty": "还没有团队账号。",
+ "team_empty_member": "还没有团队账号。请联系工作区管理员连接。",
+ "personal_title": "我的账号",
+ "personal_description": "你自己的账号。由你触发的运行中,设为「触发者账号」的应用会使用这些账号。",
+ "personal_empty": "你还没有连接任何账号。",
+ "connected_by": "由 {{name}} 连接",
+ "last_used": "最近使用 {{when}}",
+ "last_used_never": "尚未使用",
+ "used_by_other": "{{count}} 个智能体在用",
+ "expired": "需要重新连接",
+ "reconnect": "重新连接",
+ "rules": "规则",
+ "activity": "调用记录",
+ "disconnect": "断开",
+ "catalog_title": "可用应用",
+ "catalog_label": "成员可添加的应用",
+ "catalog_description": "精选应用带有审核过的默认规则。「全部应用」包含 Composio 能连接的所有应用;Multica 无法识别的操作一律先征得同意。「指定名单」只允许你选中的应用。",
+ "catalog_all": "全部应用",
+ "catalog_curated": "仅精选",
+ "catalog_custom": "指定名单",
+ "toast_connected": "账号已连接",
+ "toast_connect_failed": "连接未完成,请重试。",
+ "toast_disconnected": "已断开",
+ "toast_failed": "操作失败,请重试。",
+ "add": {
+ "title": "添加应用",
+ "description": "为团队或为自己连接账号。哪些智能体使用它,在各智能体的「应用」页设置。",
+ "search": "搜索应用…",
+ "empty": "没有匹配的应用。",
+ "curated": "精选",
+ "recommended_team": "通常用团队账号",
+ "recommended_personal": "通常用个人账号",
+ "connect_team": "连接团队账号",
+ "connect_personal": "连接我的账号",
+ "connecting": "正在连接…",
+ "connected": "已连接"
+ },
+ "disconnect_team": {
+ "title": "断开团队的 {{app}} 账号?",
+ "description": "使用团队账号的智能体会立即失去访问权限。",
+ "agents": "正在使用的智能体",
+ "no_agents": "没有智能体在用。",
+ "active_tasks": "进行中的运行:{{count}}",
+ "active_autopilots": "启用中的自动化:{{count}}",
+ "pending": "将被取消的待确认请求:{{count}}",
+ "cancel": "取消",
+ "confirm": "断开"
+ },
+ "disconnect_personal": {
+ "title": "断开你的 {{app}} 账号?",
+ "description": "你触发的运行将无法再使用它。之后可以重新连接。",
+ "cancel": "取消",
+ "confirm": "断开"
+ },
+ "detail": {
+ "team_title": "{{app}} · 团队账号",
+ "personal_title": "{{app}} · 我的账号",
+ "rules_description": "智能体可以通过这个账号做什么。智能体的权限级别只会让规则更严格。",
+ "rules_read_only": "只有工作区管理员可以修改团队账号的规则。",
+ "default": "默认:{{policy}}",
+ "activity_empty": "还没有调用。",
+ "activity_failed": "无法加载调用记录。"
+ },
+ "classes": {
+ "read": {
+ "label": "读取",
+ "description": "搜索、列出、获取"
+ },
+ "write": {
+ "label": "写入",
+ "description": "创建和更新内容"
+ },
+ "send": {
+ "label": "发送",
+ "description": "发邮件或消息、发布、邀请"
+ },
+ "delete": {
+ "label": "删除",
+ "description": "删除或归档"
+ },
+ "share": {
+ "label": "分享",
+ "description": "修改权限或对外分享"
+ }
+ },
+ "policies": {
+ "allow": "允许",
+ "confirm": "先确认",
+ "block": "禁止"
+ },
+ "outcomes": {
+ "ok": "已执行",
+ "error": "失败",
+ "blocked": "已拦截",
+ "pending": "等待确认",
+ "approved": "已批准",
+ "rejected": "已拒绝",
+ "rate_limited": "已限流"
+ },
+ "scopes": {
+ "team": "团队账号",
+ "personal": "触发者的账号"
+ },
+ "levels": {
+ "read": "只读",
+ "confirm_writes": "写操作先确认",
+ "write": "可写"
+ },
+ "request": {
+ "title_action": "{{agent}} 想执行 {{tool}}",
+ "title_connect": "{{agent}} 请你连接 {{app}}",
+ "pending_count_other": "{{count}} 个应用操作等待确认",
+ "waiting_for": "等待 {{name}} 确认",
+ "expires": "{{when}}过期",
+ "redacted": "只有 {{name}} 能看到详情。",
+ "arguments": "参数",
+ "edit": "编辑",
+ "invalid_json": "参数必须是 JSON 对象。",
+ "approve": "批准并执行",
+ "approve_all": "全部批准",
+ "reject": "拒绝",
+ "reject_reason": "原因(可选,智能体会看到)",
+ "connect": "连接 {{app}}",
+ "connected_continue": "我已连接",
+ "status": {
+ "approved": "已批准",
+ "rejected": "已拒绝",
+ "failed": "执行失败",
+ "expired": "已过期",
+ "cancelled": "已取消"
+ },
+ "toast_approved": "已批准,智能体将继续。",
+ "toast_rejected": "已拒绝,智能体会调整做法。",
+ "toast_failed": "无法记录你的决定。",
+ "not_connected": "请先连接账号。",
+ "connected_resumed": "{{app}} 已连接,智能体会从中断处继续。",
+ "rate_limited": "这个账号已达到每分钟调用上限,请一分钟后再批准。",
+ "rate_limited_some_other": "有 {{count}} 个请求触发了每分钟上限,请一分钟后再批准。",
+ "withdrawn": "你已无法使用这个智能体,请求已撤回。"
+ },
+ "tools": {
+ "tab": "工具",
+ "description": "工具的分类决定适用哪条规则。自动分类有误的工具可以在这里纠正,改动对本工作区里这个应用的所有账号生效。",
+ "read_only": "只有工作区管理员可以修改工具分类。",
+ "search": "搜索工具",
+ "empty": "没有匹配的工具。",
+ "auto": "自动({{class}})",
+ "truncated": "共 {{total}} 个,显示前 {{shown}} 个。搜索可缩小范围。"
+ },
+ "custom": {
+ "title": "指定应用名单",
+ "description": "智能体只能看到你选中的应用,其他应用也无法再连接账号。",
+ "selected_other": "已选 {{count}} 个应用",
+ "cancel": "取消",
+ "save": "保存名单",
+ "saved": "应用名单已保存",
+ "edit": "编辑名单",
+ "row_label": "允许的应用",
+ "row_description_other": "已允许 {{count}} 个应用"
+ }
}
}
diff --git a/packages/views/locales/zh-Hant/agents.json b/packages/views/locales/zh-Hant/agents.json
index ac7cc6f815..036cb2bead 100644
--- a/packages/views/locales/zh-Hant/agents.json
+++ b/packages/views/locales/zh-Hant/agents.json
@@ -288,7 +288,7 @@
"environment": "環境變數",
"custom_args": "自定義引數",
"mcp_config": "MCP",
- "composio_mcp": "MCP 應用",
+ "composio_mcp": "應用",
"integrations": "整合",
"runtime_config": "路由",
"qoder_agent": "Qoder Cloud Agents",
@@ -703,22 +703,6 @@
"redacted_hint": "只有 AI 代理 owner 或工作區 admin 可以檢視此配置。",
"dialog_json_help": "以 JSON 編輯完整的伺服器配置。"
},
- "composio_mcp": {
- "subtitle": "勾選 toolkit,只在你自己(這個 AI 代理的建立者)直接或透過下級 AI 代理鏈路觸發這個 AI 代理時,才把它掛載為 MCP server。",
- "loading": "正在載入你的連線…",
- "load_failed": "無法載入你已連線的應用,請稍後重試。",
- "empty_title": "還沒有已連線的應用",
- "empty_link_to_settings": "去 \"設定 → 整合\" 連一個",
- "open_settings": "開啟設定",
- "connected": "已連線",
- "toggle_aria": "允許該 AI 代理使用 {{toolkit}}",
- "saving": "正在儲存…",
- "save_failed_toast": "儲存失敗,請重試",
- "redacted_title": "已配置——對你隱藏",
- "redacted_hint": "只有該 AI 代理的建立者才能檢視或修改它可使用的應用。",
- "shared_warning": "該 AI 代理已共享。能夠執行該 AI 代理的人可以透過它使用你在此啟用的 Composio 應用。如果這些應用涉及敏感資料,請改用\"私有\"或縮小訪問範圍。",
- "workspace_warning": "公開給工作區:工作區內任何成員都可以透過該 AI 代理使用這些 Composio 應用。"
- },
"runtime_config": {
"mode_label": "路由模式",
"mode_local": "Local",
@@ -831,6 +815,24 @@
"started_prefix": "{{when}}啟動",
"dispatched_prefix": "{{when}}派發",
"queued_prefix": "{{when}}排隊"
+ },
+ "connected_apps": {
+ "subtitle": "這個 AI 代理可以使用的應用。每個應用以團隊帳號或觸發者的帳號身分操作,權限等級由你設定。",
+ "loading": "正在載入應用…",
+ "load_failed": "無法載入此 AI 代理的應用。",
+ "empty": "還沒有應用。",
+ "add_placeholder": "新增應用…",
+ "account": "帳號",
+ "level": "權限",
+ "remove": "移除 {{app}}",
+ "team_connected": "團隊帳號已連線",
+ "team_missing": "團隊帳號未連線",
+ "personal_connected": "你的帳號已連線",
+ "personal_missing": "你還沒有連線這個應用",
+ "team_admin_only": "只有工作區管理員可以給 AI 代理團隊帳號。",
+ "team_shared_warning": "能執行這個 AI 代理的人,都會以團隊帳號身分使用這些應用。",
+ "manage_link": "在 設定 → 已連線應用 中管理帳號",
+ "save_failed_toast": "儲存失敗,請重試"
}
},
"char_counter": {
diff --git a/packages/views/locales/zh-Hant/inbox.json b/packages/views/locales/zh-Hant/inbox.json
index 8bd66ebab1..1e5985bbee 100644
--- a/packages/views/locales/zh-Hant/inbox.json
+++ b/packages/views/locales/zh-Hant/inbox.json
@@ -93,7 +93,11 @@
"quick_create_unconfirmed": "透過 AI 代理建立結果未確認",
"autopilot_paused": "自動化已暫停",
"children_done": "子任務已全部結束",
- "autopilot_quota_exceeded": "自動化執行次數已用完"
+ "autopilot_quota_exceeded": "自動化執行次數已用完",
+ "app_action_requested": "等待你確認",
+ "app_action_reminder": "確認即將過期",
+ "app_connect_requested": "請連線應用",
+ "app_action_result": "應用操作結果"
},
"labels": {
"set_status_to": "狀態設為",
diff --git a/packages/views/locales/zh-Hant/issues.json b/packages/views/locales/zh-Hant/issues.json
index 7ae419bf3c..cf771180e1 100644
--- a/packages/views/locales/zh-Hant/issues.json
+++ b/packages/views/locales/zh-Hant/issues.json
@@ -1809,5 +1809,24 @@
"empty_title": "還沒有儲存的檢視",
"empty_description": "在任務列表裡調好篩選和顯示方式,然後另存為檢視。"
}
+ },
+ "app_calls": {
+ "section_title": "應用",
+ "chips_label": "本次執行用到的應用",
+ "calls_count_other": "{{count}} 次呼叫",
+ "more": "還有 {{count}} 個",
+ "scope": {
+ "team": "團隊帳號",
+ "personal": "個人帳號"
+ },
+ "outcome": {
+ "ok": "已執行",
+ "error": "失敗",
+ "blocked": "已攔截",
+ "pending": "等待確認",
+ "approved": "已核准",
+ "rejected": "已拒絕",
+ "rate_limited": "已限流"
+ }
}
}
diff --git a/packages/views/locales/zh-Hant/settings.json b/packages/views/locales/zh-Hant/settings.json
index 2bdea74ceb..472d630310 100644
--- a/packages/views/locales/zh-Hant/settings.json
+++ b/packages/views/locales/zh-Hant/settings.json
@@ -950,35 +950,6 @@
"inbound_pending_hint": "請在飛書/Lark 中傳送訊息給此機器人以驗證接收。若未收到,請檢查長連線模式、im.message.receive_v1 事件訂閱,以及應用程式發布和審核狀態。既有綁定可能尚無驗證紀錄。",
"inbound_verified_hint": "本次綁定已收到有效訊息;這不代表持續連線、AI 代理執行成功或回覆成功。"
},
- "composio": {
- "page_description": "連線 AI 代理可使用的應用。",
- "not_enabled_title": "Composio 整合未啟用",
- "not_enabled_description_prefix": "在伺服器上設定",
- "not_enabled_description_suffix": "以啟用 Composio toolkit 連線。",
- "loading": "正在載入 toolkit…",
- "load_failed": "載入 Composio toolkit 失敗。",
- "empty_title": "還沒有可連線的應用",
- "empty_description": "你的 Composio 專案裡還沒有啟用 auth config 的 toolkit。請在 Composio 後臺啟用一個 auth config,它才會出現在這裡。",
- "search_placeholder": "搜尋 toolkit…",
- "connect": "連線",
- "connecting": "連線中…",
- "connected": "已連線",
- "disconnect": "斷開",
- "disconnecting": "斷開中...",
- "connect_failed": "無法發起連線,請重試。",
- "disconnect_failed": "無法斷開連線,請重試。",
- "toast_disconnected": "已斷開",
- "disconnect_confirm_title": "斷開這個應用?",
- "disconnect_confirm_description": "你的已連線帳號將在 Composio 側被撤銷,你的 AI 代理將失去對該 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": "在 Slack 中與 AI 代理對話,或用 /issue 建立任務。",
@@ -1467,7 +1438,175 @@
"title": "為 AI 代理接入工具的方式",
"current": "當前頁面",
"mcp": "由管理員新增、在工作區內共享,再按 AI 代理分配。",
- "apps": "用你自己的帳號透過 Composio 授權,在你擁有的 AI 代理上啟用。",
+ "apps": "透過 Multica 連線的團隊或個人帳號,依 AI 代理分配帳號和權限等級。",
"plugins": "安裝後可提供工具、定時 hook 和儲存,每個外掛單獨授權。"
+ },
+ "connected_apps": {
+ "description": "AI 代理透過這些帳號操作外部應用。每次呼叫都經過 Multica:依規則執行,傳送、刪除、分享前先徵得同意。",
+ "add_app": "新增應用",
+ "loading": "正在載入應用…",
+ "load_failed": "無法載入應用。",
+ "team_title": "團隊帳號",
+ "team_description": "工作區共有的帳號,例如客服信箱或公司 GitHub。由管理員連線;被授予團隊帳號的 AI 代理以該帳號身分操作。",
+ "team_empty": "還沒有團隊帳號。",
+ "team_empty_member": "還沒有團隊帳號。請聯絡工作區管理員連線。",
+ "personal_title": "我的帳號",
+ "personal_description": "你自己的帳號。由你觸發的執行中,設為「觸發者帳號」的應用會使用這些帳號。",
+ "personal_empty": "你還沒有連線任何帳號。",
+ "connected_by": "由 {{name}} 連線",
+ "last_used": "最近使用 {{when}}",
+ "last_used_never": "尚未使用",
+ "used_by_other": "{{count}} 個 AI 代理在用",
+ "expired": "需要重新連線",
+ "reconnect": "重新連線",
+ "rules": "規則",
+ "activity": "呼叫紀錄",
+ "disconnect": "中斷連線",
+ "catalog_title": "可用應用",
+ "catalog_label": "成員可新增的應用",
+ "catalog_description": "精選應用附有審核過的預設規則。「全部應用」包含 Composio 能連線的所有應用;Multica 無法辨識的操作一律先徵得同意。「指定名單」只允許你選中的應用。",
+ "catalog_all": "全部應用",
+ "catalog_curated": "僅精選",
+ "catalog_custom": "指定名單",
+ "toast_connected": "帳號已連線",
+ "toast_connect_failed": "連線未完成,請重試。",
+ "toast_disconnected": "已中斷連線",
+ "toast_failed": "操作失敗,請重試。",
+ "add": {
+ "title": "新增應用",
+ "description": "為團隊或為自己連線帳號。哪些 AI 代理使用它,在各 AI 代理的「應用」頁設定。",
+ "search": "搜尋應用…",
+ "empty": "沒有符合的應用。",
+ "curated": "精選",
+ "recommended_team": "通常用團隊帳號",
+ "recommended_personal": "通常用個人帳號",
+ "connect_team": "連線團隊帳號",
+ "connect_personal": "連線我的帳號",
+ "connecting": "正在連線…",
+ "connected": "已連線"
+ },
+ "disconnect_team": {
+ "title": "中斷團隊的 {{app}} 帳號?",
+ "description": "使用團隊帳號的 AI 代理會立即失去存取權限。",
+ "agents": "正在使用的 AI 代理",
+ "no_agents": "沒有 AI 代理在用。",
+ "active_tasks": "進行中的執行:{{count}}",
+ "active_autopilots": "啟用中的自動化:{{count}}",
+ "pending": "將被取消的待確認請求:{{count}}",
+ "cancel": "取消",
+ "confirm": "中斷連線"
+ },
+ "disconnect_personal": {
+ "title": "中斷你的 {{app}} 帳號?",
+ "description": "你觸發的執行將無法再使用它。之後可以重新連線。",
+ "cancel": "取消",
+ "confirm": "中斷連線"
+ },
+ "detail": {
+ "team_title": "{{app}} · 團隊帳號",
+ "personal_title": "{{app}} · 我的帳號",
+ "rules_description": "AI 代理可以透過這個帳號做什麼。AI 代理的權限等級只會讓規則更嚴格。",
+ "rules_read_only": "只有工作區管理員可以修改團隊帳號的規則。",
+ "default": "預設:{{policy}}",
+ "activity_empty": "還沒有呼叫。",
+ "activity_failed": "無法載入呼叫紀錄。"
+ },
+ "classes": {
+ "read": {
+ "label": "讀取",
+ "description": "搜尋、列出、取得"
+ },
+ "write": {
+ "label": "寫入",
+ "description": "建立和更新內容"
+ },
+ "send": {
+ "label": "傳送",
+ "description": "寄信或傳訊息、發布、邀請"
+ },
+ "delete": {
+ "label": "刪除",
+ "description": "刪除或封存"
+ },
+ "share": {
+ "label": "分享",
+ "description": "修改權限或對外分享"
+ }
+ },
+ "policies": {
+ "allow": "允許",
+ "confirm": "先確認",
+ "block": "禁止"
+ },
+ "outcomes": {
+ "ok": "已執行",
+ "error": "失敗",
+ "blocked": "已攔截",
+ "pending": "等待確認",
+ "approved": "已核准",
+ "rejected": "已拒絕",
+ "rate_limited": "已限流"
+ },
+ "scopes": {
+ "team": "團隊帳號",
+ "personal": "觸發者的帳號"
+ },
+ "levels": {
+ "read": "唯讀",
+ "confirm_writes": "寫入前先確認",
+ "write": "可寫入"
+ },
+ "request": {
+ "title_action": "{{agent}} 想執行 {{tool}}",
+ "title_connect": "{{agent}} 請你連線 {{app}}",
+ "pending_count_other": "{{count}} 個應用操作等待確認",
+ "waiting_for": "等待 {{name}} 確認",
+ "expires": "{{when}}過期",
+ "redacted": "只有 {{name}} 能看到詳情。",
+ "arguments": "參數",
+ "edit": "編輯",
+ "invalid_json": "參數必須是 JSON 物件。",
+ "approve": "核准並執行",
+ "approve_all": "全部核准",
+ "reject": "拒絕",
+ "reject_reason": "原因(選填,AI 代理會看到)",
+ "connect": "連線 {{app}}",
+ "connected_continue": "我已連線",
+ "status": {
+ "approved": "已核准",
+ "rejected": "已拒絕",
+ "failed": "執行失敗",
+ "expired": "已過期",
+ "cancelled": "已取消"
+ },
+ "toast_approved": "已核准,AI 代理將繼續。",
+ "toast_rejected": "已拒絕,AI 代理會調整做法。",
+ "toast_failed": "無法記錄你的決定。",
+ "not_connected": "請先連線帳號。",
+ "connected_resumed": "{{app}} 已連線,代理會從中斷處繼續。",
+ "rate_limited": "這個帳號已達到每分鐘呼叫上限,請一分鐘後再核准。",
+ "rate_limited_some_other": "有 {{count}} 個請求觸發了每分鐘上限,請一分鐘後再核准。",
+ "withdrawn": "你已無法使用這個代理,請求已撤回。"
+ },
+ "tools": {
+ "tab": "工具",
+ "description": "工具的分類決定適用哪條規則。自動分類有誤的工具可以在這裡修正,變更對本工作區裡這個應用的所有帳號生效。",
+ "read_only": "只有工作區管理員可以修改工具分類。",
+ "search": "搜尋工具",
+ "empty": "沒有符合的工具。",
+ "auto": "自動({{class}})",
+ "truncated": "共 {{total}} 個,顯示前 {{shown}} 個。搜尋可縮小範圍。"
+ },
+ "custom": {
+ "title": "指定應用名單",
+ "description": "代理只能看到你選中的應用,其他應用也無法再連線帳號。",
+ "selected_other": "已選 {{count}} 個應用",
+ "cancel": "取消",
+ "save": "儲存名單",
+ "saved": "應用名單已儲存",
+ "edit": "編輯名單",
+ "row_label": "允許的應用",
+ "row_description_other": "已允許 {{count}} 個應用"
+ }
}
}
diff --git a/packages/views/settings/components/add-app-dialog.tsx b/packages/views/settings/components/add-app-dialog.tsx
new file mode 100644
index 0000000000..5d4dc45c53
--- /dev/null
+++ b/packages/views/settings/components/add-app-dialog.tsx
@@ -0,0 +1,158 @@
+"use client";
+
+import { useMemo, useState } from "react";
+import { toast } from "sonner";
+import { Check, Loader2 } from "@multica/ui/icons";
+import { Badge } from "@multica/ui/components/ui/badge";
+import { Button } from "@multica/ui/components/ui/button";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogHeader,
+ DialogTitle,
+} from "@multica/ui/components/ui/dialog";
+import { Input } from "@multica/ui/components/ui/input";
+import { api } from "@multica/core/api";
+import type { AppAccountScope, AppCatalogEntry, AppsOverview } from "@multica/core/types";
+import { ComposioToolkitLogo } from "../../common/composio-toolkit-logo";
+import { useT } from "../../i18n";
+
+/**
+ * The add-app dialog: every app the workspace allows, curated ones first.
+ * Each row connects a team account (admins) or the caller's own; the
+ * recommended one is the primary button.
+ */
+export function AddAppDialog({
+ open,
+ onOpenChange,
+ canManage,
+ overview,
+ catalog,
+ catalogLoading,
+ catalogError,
+}: {
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ canManage: boolean;
+ overview: AppsOverview;
+ catalog: AppCatalogEntry[];
+ catalogLoading: boolean;
+ catalogError: boolean;
+}) {
+ const { t } = useT("settings");
+ const [query, setQuery] = useState("");
+ const [connecting, setConnecting] = useState<string | null>(null);
+
+ const connected = useMemo(() => {
+ const set = new Set<string>();
+ for (const c of overview.team) if (c.status === "active") set.add(`team:${c.toolkit_slug}`);
+ for (const c of overview.personal) if (c.status === "active") set.add(`personal:${c.toolkit_slug}`);
+ return set;
+ }, [overview]);
+
+ const filtered = useMemo(() => {
+ const q = query.trim().toLowerCase();
+ if (!q) return catalog;
+ return catalog.filter(
+ (app) =>
+ app.name.toLowerCase().includes(q) ||
+ app.slug.includes(q) ||
+ (app.category ?? "").toLowerCase().includes(q),
+ );
+ }, [catalog, query]);
+
+ async function connect(app: AppCatalogEntry, scope: AppAccountScope) {
+ if (connecting) return;
+ setConnecting(`${scope}:${app.slug}`);
+ try {
+ const { redirect_url } = await api.connectApp(scope, app.slug);
+ window.location.href = redirect_url;
+ } catch (e) {
+ toast.error(e instanceof Error && e.message ? e.message : t(($) => $.connected_apps.toast_failed));
+ setConnecting(null);
+ }
+ }
+
+ const connectButton = (app: AppCatalogEntry, scope: AppAccountScope) => {
+ const key = `${scope}:${app.slug}`;
+ const label =
+ scope === "team"
+ ? t(($) => $.connected_apps.add.connect_team)
+ : t(($) => $.connected_apps.add.connect_personal);
+ if (connected.has(key)) {
+ return (
+ <span key={scope} className="inline-flex items-center gap-1 text-caption text-muted-foreground">
+ <Check className="size-3" />
+ {label}
+ </span>
+ );
+ }
+ const recommended = (app.recommended_scope ?? "personal") === scope;
+ return (
+ <Button
+ key={scope}
+ size="xs"
+ variant={recommended ? "default" : "outline"}
+ disabled={connecting !== null}
+ onClick={() => connect(app, scope)}
+ >
+ {connecting === key && <Loader2 className="animate-spin" />}
+ {connecting === key ? t(($) => $.connected_apps.add.connecting) : label}
+ </Button>
+ );
+ };
+
+ return (
+ <Dialog open={open} onOpenChange={onOpenChange}>
+ <DialogContent className="sm:max-w-2xl">
+ <DialogHeader>
+ <DialogTitle>{t(($) => $.connected_apps.add.title)}</DialogTitle>
+ <DialogDescription>{t(($) => $.connected_apps.add.description)}</DialogDescription>
+ </DialogHeader>
+ <Input
+ autoFocus
+ value={query}
+ onChange={(e) => setQuery(e.target.value)}
+ placeholder={t(($) => $.connected_apps.add.search)}
+ />
+ <div className="max-h-[60vh] min-h-48 overflow-y-auto rounded-lg border">
+ {catalogLoading ? (
+ <p className="p-4 text-caption text-muted-foreground">{t(($) => $.connected_apps.loading)}</p>
+ ) : catalogError ? (
+ <p className="p-4 text-caption text-destructive">{t(($) => $.connected_apps.load_failed)}</p>
+ ) : filtered.length === 0 ? (
+ <p className="p-4 text-caption text-muted-foreground">{t(($) => $.connected_apps.add.empty)}</p>
+ ) : (
+ <ul className="divide-y">
+ {filtered.map((app) => (
+ <li key={app.slug} className="flex items-center gap-3 px-3 py-2.5">
+ <ComposioToolkitLogo slug={app.slug} name={app.name} fallbackLogo={app.logo} />
+ <div className="min-w-0 flex-1">
+ <p className="flex items-center gap-2 truncate text-body font-medium">
+ {app.name || app.slug}
+ {app.curated && (
+ <Badge variant="secondary">{t(($) => $.connected_apps.add.curated)}</Badge>
+ )}
+ </p>
+ <p className="truncate text-caption text-muted-foreground">
+ {app.recommended_scope === "team"
+ ? t(($) => $.connected_apps.add.recommended_team)
+ : app.recommended_scope === "personal"
+ ? t(($) => $.connected_apps.add.recommended_personal)
+ : app.category}
+ </p>
+ </div>
+ <div className="flex shrink-0 items-center gap-2">
+ {canManage && connectButton(app, "team")}
+ {connectButton(app, "personal")}
+ </div>
+ </li>
+ ))}
+ </ul>
+ )}
+ </div>
+ </DialogContent>
+ </Dialog>
+ );
+}
diff --git a/packages/views/settings/components/app-account-dialog.tsx b/packages/views/settings/components/app-account-dialog.tsx
new file mode 100644
index 0000000000..aef84161f1
--- /dev/null
+++ b/packages/views/settings/components/app-account-dialog.tsx
@@ -0,0 +1,301 @@
+"use client";
+
+import { useMemo, useState } from "react";
+import { useQuery } from "@tanstack/react-query";
+import { toast } from "sonner";
+import {
+ Dialog,
+ DialogContent,
+ DialogHeader,
+ DialogTitle,
+} from "@multica/ui/components/ui/dialog";
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from "@multica/ui/components/ui/select";
+import { Input } from "@multica/ui/components/ui/input";
+import { Tabs, TabsContent, TabsList, TabsTrigger } from "@multica/ui/components/ui/tabs";
+import { useWorkspaceId } from "@multica/core/hooks";
+import {
+ appActivityOptions,
+ appRulesOptions,
+ appToolsOptions,
+ useUpdateAppRules,
+ useUpdateAppToolClass,
+} from "@multica/core/connected-apps";
+import type {
+ AppAccountScope,
+ AppActionClass,
+ AppActionPolicy,
+ AppRule,
+ AppTool,
+} from "@multica/core/types";
+import { useT, useTimeAgo } from "../../i18n";
+
+const POLICIES: readonly AppActionPolicy[] = ["allow", "confirm", "block"];
+const CLASSES: readonly AppActionClass[] = ["read", "write", "send", "delete", "share"];
+const AUTO = "auto";
+const MAX_TOOLS_SHOWN = 100;
+
+/** One account's rules (what agents may do through it), how the app's tools
+ * are classified, and recent calls. */
+export function AppAccountDialog({
+ scope,
+ slug,
+ name,
+ canEdit,
+ canClassify,
+ onClose,
+}: {
+ scope: AppAccountScope;
+ slug: string;
+ name: string;
+ canEdit: boolean;
+ /** Tool classes are workspace-wide, so only admins correct them. */
+ canClassify: boolean;
+ onClose: () => void;
+}) {
+ const { t } = useT("settings");
+ return (
+ <Dialog open onOpenChange={(open) => !open && onClose()}>
+ <DialogContent className="sm:max-w-xl">
+ <DialogHeader>
+ <DialogTitle>
+ {scope === "team"
+ ? t(($) => $.connected_apps.detail.team_title, { app: name })
+ : t(($) => $.connected_apps.detail.personal_title, { app: name })}
+ </DialogTitle>
+ </DialogHeader>
+ <Tabs defaultValue="rules">
+ <TabsList>
+ <TabsTrigger value="rules">{t(($) => $.connected_apps.rules)}</TabsTrigger>
+ <TabsTrigger value="tools">{t(($) => $.connected_apps.tools.tab)}</TabsTrigger>
+ <TabsTrigger value="activity">{t(($) => $.connected_apps.activity)}</TabsTrigger>
+ </TabsList>
+ <TabsContent value="rules" className="pt-3">
+ <RulesEditor scope={scope} slug={slug} canEdit={canEdit} />
+ </TabsContent>
+ <TabsContent value="tools" className="pt-3">
+ <ToolsEditor slug={slug} canEdit={canClassify} />
+ </TabsContent>
+ <TabsContent value="activity" className="pt-3">
+ <ActivityList scope={scope} slug={slug} />
+ </TabsContent>
+ </Tabs>
+ </DialogContent>
+ </Dialog>
+ );
+}
+
+function RulesEditor({ scope, slug, canEdit }: { scope: AppAccountScope; slug: string; canEdit: boolean }) {
+ const { t } = useT("settings");
+ const wsId = useWorkspaceId();
+ const rules = useQuery(appRulesOptions(wsId, slug, scope));
+ const update = useUpdateAppRules(slug, scope);
+ const policyLabel = (policy: AppActionPolicy) => t(($) => $.connected_apps.policies[policy]);
+
+ const save = (rule: AppRule, policy: AppActionPolicy) => {
+ update.mutate([{ action_class: rule.action_class, policy }], {
+ onError: () => toast.error(t(($) => $.connected_apps.toast_failed)),
+ });
+ };
+
+ if (rules.isLoading) {
+ return <p className="text-caption text-muted-foreground">{t(($) => $.connected_apps.loading)}</p>;
+ }
+ if (rules.isError || !rules.data) {
+ return <p className="text-caption text-destructive">{t(($) => $.connected_apps.load_failed)}</p>;
+ }
+ return (
+ <div className="space-y-3">
+ <p className="text-caption text-muted-foreground">
+ {canEdit
+ ? t(($) => $.connected_apps.detail.rules_description)
+ : t(($) => $.connected_apps.detail.rules_read_only)}
+ </p>
+ <ul className="divide-y rounded-lg border">
+ {rules.data.map((rule) => (
+ <li key={rule.action_class} className="flex items-center gap-3 px-3 py-2.5">
+ <div className="min-w-0 flex-1">
+ <p className="text-body font-medium">
+ {t(($) => $.connected_apps.classes[rule.action_class].label)}
+ </p>
+ <p className="text-caption text-muted-foreground">
+ {t(($) => $.connected_apps.classes[rule.action_class].description)}
+ {rule.custom &&
+ ` · ${t(($) => $.connected_apps.detail.default, { policy: policyLabel(rule.default_policy) })}`}
+ </p>
+ </div>
+ <Select
+ items={POLICIES.map((value) => ({ value, label: policyLabel(value) }))}
+ value={rule.policy}
+ disabled={!canEdit || update.isPending}
+ onValueChange={(value) => {
+ if (value && value !== rule.policy) save(rule, value as AppActionPolicy);
+ }}
+ >
+ <SelectTrigger
+ size="sm"
+ className="w-32"
+ aria-label={t(($) => $.connected_apps.classes[rule.action_class].label)}
+ >
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent align="end">
+ {POLICIES.map((value) => (
+ <SelectItem key={value} value={value}>
+ {policyLabel(value)}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </li>
+ ))}
+ </ul>
+ </div>
+ );
+}
+
+function ToolsEditor({ slug, canEdit }: { slug: string; canEdit: boolean }) {
+ const { t } = useT("settings");
+ const wsId = useWorkspaceId();
+ const tools = useQuery(appToolsOptions(wsId, slug));
+ const [search, setSearch] = useState("");
+ const filtered = useMemo(() => {
+ const q = search.trim().toLowerCase();
+ const all = tools.data ?? [];
+ if (!q) return all;
+ return all.filter(
+ (tool) => tool.slug.toLowerCase().includes(q) || tool.name.toLowerCase().includes(q),
+ );
+ }, [tools.data, search]);
+
+ if (tools.isLoading) {
+ return <p className="text-caption text-muted-foreground">{t(($) => $.connected_apps.loading)}</p>;
+ }
+ if (tools.isError || !tools.data) {
+ return <p className="text-caption text-destructive">{t(($) => $.connected_apps.load_failed)}</p>;
+ }
+ const shown = filtered.slice(0, MAX_TOOLS_SHOWN);
+ return (
+ <div className="space-y-3">
+ <p className="text-caption text-muted-foreground">
+ {canEdit
+ ? t(($) => $.connected_apps.tools.description)
+ : t(($) => $.connected_apps.tools.read_only)}
+ </p>
+ <Input
+ value={search}
+ onChange={(e) => setSearch(e.target.value)}
+ placeholder={t(($) => $.connected_apps.tools.search)}
+ aria-label={t(($) => $.connected_apps.tools.search)}
+ />
+ {shown.length === 0 ? (
+ <p className="text-caption text-muted-foreground">{t(($) => $.connected_apps.tools.empty)}</p>
+ ) : (
+ <ul className="max-h-80 divide-y overflow-y-auto rounded-lg border">
+ {shown.map((tool) => (
+ <ToolRow key={tool.slug} slug={slug} tool={tool} canEdit={canEdit} />
+ ))}
+ </ul>
+ )}
+ {filtered.length > shown.length && (
+ <p className="text-caption text-muted-foreground">
+ {t(($) => $.connected_apps.tools.truncated, { shown: shown.length, total: filtered.length })}
+ </p>
+ )}
+ </div>
+ );
+}
+
+function ToolRow({ slug, tool, canEdit }: { slug: string; tool: AppTool; canEdit: boolean }) {
+ const { t } = useT("settings");
+ const update = useUpdateAppToolClass(slug);
+ const classLabel = (c: AppActionClass) => t(($) => $.connected_apps.classes[c].label);
+ const autoLabel = t(($) => $.connected_apps.tools.auto, { class: classLabel(tool.auto_class) });
+ const value = tool.overridden ? tool.class : AUTO;
+ return (
+ <li className="flex items-center gap-3 px-3 py-2">
+ <div className="min-w-0 flex-1">
+ <p className="truncate text-caption font-medium" title={tool.slug}>{tool.name || tool.slug}</p>
+ {tool.description && (
+ <p className="truncate text-caption text-muted-foreground" title={tool.description}>{tool.description}</p>
+ )}
+ </div>
+ <Select
+ items={[
+ { value: AUTO, label: autoLabel },
+ ...CLASSES.map((c) => ({ value: c, label: classLabel(c) })),
+ ]}
+ value={value}
+ disabled={!canEdit || update.isPending}
+ onValueChange={(next) => {
+ if (!next || next === value) return;
+ update.mutate(
+ { tool: tool.slug, actionClass: next === AUTO ? null : (next as AppActionClass) },
+ { onError: () => toast.error(t(($) => $.connected_apps.toast_failed)) },
+ );
+ }}
+ >
+ <SelectTrigger size="sm" className="w-40" aria-label={tool.name || tool.slug}>
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent align="end">
+ <SelectItem value={AUTO}>{autoLabel}</SelectItem>
+ {CLASSES.map((c) => (
+ <SelectItem key={c} value={c}>
+ {classLabel(c)}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </li>
+ );
+}
+
+function ActivityList({ scope, slug }: { scope: AppAccountScope; slug: string }) {
+ const { t } = useT("settings");
+ const wsId = useWorkspaceId();
+ const timeAgo = useTimeAgo();
+ const calls = useQuery(appActivityOptions(wsId, slug, scope));
+ const outcomeLabel = (outcome: string) => {
+ switch (outcome) {
+ case "ok":
+ case "error":
+ case "blocked":
+ case "pending":
+ case "approved":
+ case "rejected":
+ case "rate_limited":
+ return t(($) => $.connected_apps.outcomes[outcome]);
+ default:
+ return outcome;
+ }
+ };
+
+ if (calls.isLoading) {
+ return <p className="text-caption text-muted-foreground">{t(($) => $.connected_apps.loading)}</p>;
+ }
+ if (calls.isError) {
+ return <p className="text-caption text-destructive">{t(($) => $.connected_apps.detail.activity_failed)}</p>;
+ }
+ if (!calls.data?.length) {
+ return <p className="text-caption text-muted-foreground">{t(($) => $.connected_apps.detail.activity_empty)}</p>;
+ }
+ return (
+ <ul className="max-h-80 divide-y overflow-y-auto rounded-lg border">
+ {calls.data.map((call) => (
+ <li key={call.id} className="flex items-center gap-3 px-3 py-2 text-caption">
+ <span className="min-w-0 flex-1 truncate font-mono">{call.tool_slug}</span>
+ <span className={call.outcome === "error" || call.outcome === "blocked" ? "text-destructive" : "text-muted-foreground"}>
+ {outcomeLabel(call.outcome)}
+ </span>
+ <span className="w-24 shrink-0 text-right text-muted-foreground">{timeAgo(call.created_at)}</span>
+ </li>
+ ))}
+ </ul>
+ );
+}
diff --git a/packages/views/settings/components/apps-settings.tsx b/packages/views/settings/components/apps-settings.tsx
new file mode 100644
index 0000000000..4e0e277977
--- /dev/null
+++ b/packages/views/settings/components/apps-settings.tsx
@@ -0,0 +1,434 @@
+"use client";
+
+import { useEffect, useMemo, useRef, useState } from "react";
+import { useQuery, useQueryClient } from "@tanstack/react-query";
+import { toast } from "sonner";
+import { AlertTriangle, Plus, Trash2 } from "@multica/ui/icons";
+import { Button } from "@multica/ui/components/ui/button";
+import {
+ AlertDialog,
+ AlertDialogAction,
+ AlertDialogCancel,
+ AlertDialogContent,
+ AlertDialogDescription,
+ AlertDialogFooter,
+ AlertDialogHeader,
+ AlertDialogTitle,
+} from "@multica/ui/components/ui/alert-dialog";
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from "@multica/ui/components/ui/select";
+import { api } from "@multica/core/api";
+import { useWorkspaceId } from "@multica/core/hooks";
+import {
+ appCatalogOptions,
+ appsOverviewOptions,
+ connectedAppsKeys,
+ teamAppImpactOptions,
+ useDisconnectTeamApp,
+ useUpdateAppSettings,
+} from "@multica/core/connected-apps";
+import { useActorName } from "@multica/core/workspace/hooks";
+import type {
+ AppAccountScope,
+ AppCatalogEntry,
+ AppCatalogMode,
+ AppConnection,
+} from "@multica/core/types";
+import { ComposioToolkitLogo } from "../../common/composio-toolkit-logo";
+import { useT, useTimeAgo } from "../../i18n";
+import { useNavigation } from "../../navigation";
+import { AddAppDialog } from "./add-app-dialog";
+import { AppAccountDialog } from "./app-account-dialog";
+import { CustomCatalogDialog } from "./custom-catalog-dialog";
+import { SettingsCard, SettingsRow, SettingsSection } from "./settings-layout";
+
+type AccountTarget = { scope: AppAccountScope; connection: AppConnection; name: string };
+
+/**
+ * Settings › Connected apps (MUL-8516): the workspace's team accounts, the
+ * caller's own accounts, and which apps the workspace allows. Which agent
+ * uses which app is set on the agent.
+ */
+export function AppsSettings() {
+ const { t } = useT("settings");
+ const wsId = useWorkspaceId();
+ const qc = useQueryClient();
+ const navigation = useNavigation();
+ const overview = useQuery(appsOverviewOptions(wsId));
+ const catalog = useQuery(appCatalogOptions(wsId));
+ const updateSettings = useUpdateAppSettings();
+
+ const [adding, setAdding] = useState(false);
+ const [detail, setDetail] = useState<AccountTarget | null>(null);
+ const [disconnecting, setDisconnecting] = useState<AccountTarget | null>(null);
+ const [editingList, setEditingList] = useState(false);
+
+ // The hosted connect flow returns with `?connected=<slug>` or
+ // `?error=composio_connect_failed`. Consume it once, then drop the params so
+ // a refresh does not toast again.
+ const connectedParam = navigation.searchParams.get("connected");
+ const errorParam = navigation.searchParams.get("error");
+ const consumed = useRef<string | null>(null);
+ useEffect(() => {
+ const key = connectedParam
+ ? `connected:${connectedParam}`
+ : errorParam === "composio_connect_failed"
+ ? "error"
+ : null;
+ if (!key || consumed.current === key) return;
+ consumed.current = key;
+ if (connectedParam) {
+ toast.success(t(($) => $.connected_apps.toast_connected));
+ void qc.invalidateQueries({ queryKey: connectedAppsKeys.all(wsId) });
+ } else {
+ toast.error(t(($) => $.connected_apps.toast_connect_failed));
+ }
+ const params = new URLSearchParams(navigation.searchParams);
+ params.set("tab", "apps");
+ for (const k of ["integration", "connected", "error", "scope"]) params.delete(k);
+ navigation.replace(`${navigation.pathname}?${params.toString()}`);
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [connectedParam, errorParam]);
+
+ const appBySlug = useMemo(() => {
+ const m = new Map<string, AppCatalogEntry>();
+ for (const app of catalog.data?.apps ?? []) m.set(app.slug, app);
+ return m;
+ }, [catalog.data]);
+
+ const agentCount = useMemo(() => {
+ const m = new Map<string, number>();
+ for (const app of overview.data?.agent_apps ?? []) {
+ const key = `${app.account_scope}:${app.toolkit_slug}`;
+ m.set(key, (m.get(key) ?? 0) + 1);
+ }
+ return m;
+ }, [overview.data]);
+
+ if (overview.isLoading) {
+ return <p className="text-body text-muted-foreground">{t(($) => $.connected_apps.loading)}</p>;
+ }
+ if (overview.isError || !overview.data) {
+ return <p className="text-body text-destructive">{t(($) => $.connected_apps.load_failed)}</p>;
+ }
+ const data = overview.data;
+ const canManage = data.can_manage;
+ const nameOf = (slug: string) => appBySlug.get(slug)?.name || slug;
+ const catalogModeLabel = (mode: AppCatalogMode) =>
+ mode === "curated"
+ ? t(($) => $.connected_apps.catalog_curated)
+ : mode === "custom"
+ ? t(($) => $.connected_apps.catalog_custom)
+ : t(($) => $.connected_apps.catalog_all);
+ const allowedCount = data.allowed_toolkits?.length ?? 0;
+
+ const rows = (scope: AppAccountScope, connections: AppConnection[]) =>
+ connections
+ .filter((c) => c.status !== "revoked")
+ .map((c) => (
+ <AccountRow
+ key={c.id}
+ scope={scope}
+ connection={c}
+ app={appBySlug.get(c.toolkit_slug)}
+ agents={agentCount.get(`${scope}:${c.toolkit_slug}`) ?? 0}
+ canManage={scope === "personal" || canManage}
+ onOpen={() => setDetail({ scope, connection: c, name: nameOf(c.toolkit_slug) })}
+ onDisconnect={() => setDisconnecting({ scope, connection: c, name: nameOf(c.toolkit_slug) })}
+ />
+ ));
+ const teamRows = rows("team", data.team);
+ const personalRows = rows("personal", data.personal);
+
+ return (
+ <div className="space-y-8">
+ <div className="flex items-start justify-between gap-4">
+ <p className="text-caption text-muted-foreground">{t(($) => $.connected_apps.description)}</p>
+ <Button size="sm" onClick={() => setAdding(true)}>
+ <Plus />
+ {t(($) => $.connected_apps.add_app)}
+ </Button>
+ </div>
+
+ <SettingsSection
+ anchor="team-accounts"
+ title={t(($) => $.connected_apps.team_title)}
+ description={t(($) => $.connected_apps.team_description)}
+ >
+ {teamRows.length > 0 ? (
+ <SettingsCard>{teamRows}</SettingsCard>
+ ) : (
+ <EmptyCard
+ text={
+ canManage
+ ? t(($) => $.connected_apps.team_empty)
+ : t(($) => $.connected_apps.team_empty_member)
+ }
+ />
+ )}
+ </SettingsSection>
+
+ <SettingsSection
+ anchor="my-accounts"
+ title={t(($) => $.connected_apps.personal_title)}
+ description={t(($) => $.connected_apps.personal_description)}
+ >
+ {personalRows.length > 0 ? (
+ <SettingsCard>{personalRows}</SettingsCard>
+ ) : (
+ <EmptyCard text={t(($) => $.connected_apps.personal_empty)} />
+ )}
+ </SettingsSection>
+
+ <SettingsSection anchor="catalog" title={t(($) => $.connected_apps.catalog_title)}>
+ <SettingsCard>
+ <SettingsRow
+ label={t(($) => $.connected_apps.catalog_label)}
+ description={t(($) => $.connected_apps.catalog_description)}
+ size="select"
+ >
+ <Select
+ items={(["all", "curated", "custom"] as const).map((value) => ({
+ value,
+ label: catalogModeLabel(value),
+ }))}
+ value={data.catalog_mode}
+ disabled={!canManage || updateSettings.isPending}
+ onValueChange={(value) => {
+ if (!value || value === data.catalog_mode) return;
+ // A custom catalog is only saved together with its list.
+ if (value === "custom") {
+ setEditingList(true);
+ return;
+ }
+ updateSettings.mutate({ catalog_mode: value as AppCatalogMode }, {
+ onError: () => toast.error(t(($) => $.connected_apps.toast_failed)),
+ });
+ }}
+ >
+ <SelectTrigger size="sm" className="w-full" aria-label={t(($) => $.connected_apps.catalog_label)}>
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent align="end">
+ <SelectItem value="all">{catalogModeLabel("all")}</SelectItem>
+ <SelectItem value="curated">{catalogModeLabel("curated")}</SelectItem>
+ <SelectItem value="custom">{catalogModeLabel("custom")}</SelectItem>
+ </SelectContent>
+ </Select>
+ </SettingsRow>
+ {data.catalog_mode === "custom" && (
+ <SettingsRow
+ label={t(($) => $.connected_apps.custom.row_label)}
+ description={t(($) => $.connected_apps.custom.row_description, { count: allowedCount })}
+ >
+ <Button size="sm" variant="outline" disabled={!canManage} onClick={() => setEditingList(true)}>
+ {t(($) => $.connected_apps.custom.edit)}
+ </Button>
+ </SettingsRow>
+ )}
+ </SettingsCard>
+ </SettingsSection>
+
+ <AddAppDialog
+ open={adding}
+ onOpenChange={setAdding}
+ canManage={canManage}
+ overview={data}
+ catalog={catalog.data?.apps ?? []}
+ catalogLoading={catalog.isLoading}
+ catalogError={catalog.isError}
+ />
+ {detail && (
+ <AppAccountDialog
+ scope={detail.scope}
+ slug={detail.connection.toolkit_slug}
+ name={detail.name}
+ canEdit={detail.scope === "personal" || canManage}
+ canClassify={canManage}
+ onClose={() => setDetail(null)}
+ />
+ )}
+ {editingList && (
+ <CustomCatalogDialog initial={data.allowed_toolkits ?? []} onClose={() => setEditingList(false)} />
+ )}
+ {disconnecting?.scope === "team" && (
+ <DisconnectTeamDialog target={disconnecting} onClose={() => setDisconnecting(null)} />
+ )}
+ {disconnecting?.scope === "personal" && (
+ <DisconnectPersonalDialog target={disconnecting} onClose={() => setDisconnecting(null)} />
+ )}
+ </div>
+ );
+}
+
+function EmptyCard({ text }: { text: string }) {
+ return (
+ <div className="rounded-lg border border-dashed px-4 py-6 text-center text-caption text-muted-foreground">
+ {text}
+ </div>
+ );
+}
+
+function AccountRow({
+ scope,
+ connection,
+ app,
+ agents,
+ canManage,
+ onOpen,
+ onDisconnect,
+}: {
+ scope: AppAccountScope;
+ connection: AppConnection;
+ app?: AppCatalogEntry;
+ agents: number;
+ canManage: boolean;
+ onOpen: () => void;
+ onDisconnect: () => void;
+}) {
+ const { t } = useT("settings");
+ const timeAgo = useTimeAgo();
+ const { getActorName } = useActorName();
+ const name = app?.name || connection.toolkit_slug;
+ const expired = connection.status === "expired";
+ const meta = [
+ scope === "team" && connection.connected_by
+ ? t(($) => $.connected_apps.connected_by, { name: getActorName("member", connection.connected_by) })
+ : null,
+ connection.last_used_at
+ ? t(($) => $.connected_apps.last_used, { when: timeAgo(connection.last_used_at) })
+ : t(($) => $.connected_apps.last_used_never),
+ agents > 0 ? t(($) => $.connected_apps.used_by, { count: agents }) : null,
+ ].filter(Boolean);
+
+ return (
+ <div className="flex items-center gap-3 px-4 py-3">
+ <ComposioToolkitLogo slug={connection.toolkit_slug} name={name} fallbackLogo={app?.logo} />
+ <div className="min-w-0 flex-1">
+ <p className="truncate text-body font-medium">{name}</p>
+ <p className="truncate text-caption text-muted-foreground">
+ {expired ? (
+ <span className="inline-flex items-center gap-1 text-warning">
+ <AlertTriangle className="size-3" />
+ {t(($) => $.connected_apps.expired)}
+ </span>
+ ) : (
+ meta.join(" · ")
+ )}
+ </p>
+ </div>
+ <Button variant="ghost" size="sm" onClick={onOpen}>
+ {t(($) => $.connected_apps.rules)}
+ </Button>
+ {canManage && (
+ <Button
+ variant="ghost"
+ size="icon-sm"
+ aria-label={t(($) => $.connected_apps.disconnect)}
+ onClick={onDisconnect}
+ >
+ <Trash2 />
+ </Button>
+ )}
+ </div>
+ );
+}
+
+function DisconnectTeamDialog({ target, onClose }: { target: AccountTarget; onClose: () => void }) {
+ const { t } = useT("settings");
+ const wsId = useWorkspaceId();
+ const impact = useQuery(teamAppImpactOptions(wsId, target.connection.toolkit_slug));
+ const disconnect = useDisconnectTeamApp();
+ const data = impact.data;
+
+ return (
+ <AlertDialog open onOpenChange={(open) => !open && !disconnect.isPending && onClose()}>
+ <AlertDialogContent>
+ <AlertDialogHeader>
+ <AlertDialogTitle>{t(($) => $.connected_apps.disconnect_team.title, { app: target.name })}</AlertDialogTitle>
+ <AlertDialogDescription>{t(($) => $.connected_apps.disconnect_team.description)}</AlertDialogDescription>
+ </AlertDialogHeader>
+ {data && (
+ <div className="space-y-2 text-caption">
+ <p className="font-medium">{t(($) => $.connected_apps.disconnect_team.agents)}</p>
+ <p className="text-muted-foreground">
+ {data.agents.length > 0
+ ? data.agents.map((a) => a.name).join(", ")
+ : t(($) => $.connected_apps.disconnect_team.no_agents)}
+ </p>
+ <ul className="space-y-0.5 text-muted-foreground">
+ <li>{t(($) => $.connected_apps.disconnect_team.active_tasks, { count: data.active_tasks })}</li>
+ <li>{t(($) => $.connected_apps.disconnect_team.active_autopilots, { count: data.active_autopilots })}</li>
+ <li>{t(($) => $.connected_apps.disconnect_team.pending, { count: data.pending_requests })}</li>
+ </ul>
+ </div>
+ )}
+ <AlertDialogFooter>
+ <AlertDialogCancel disabled={disconnect.isPending}>
+ {t(($) => $.connected_apps.disconnect_team.cancel)}
+ </AlertDialogCancel>
+ <AlertDialogAction
+ variant="destructive"
+ disabled={disconnect.isPending}
+ onClick={() =>
+ disconnect.mutate(target.connection.id, {
+ onSuccess: () => {
+ toast.success(t(($) => $.connected_apps.toast_disconnected));
+ onClose();
+ },
+ onError: () => toast.error(t(($) => $.connected_apps.toast_failed)),
+ })
+ }
+ >
+ {t(($) => $.connected_apps.disconnect_team.confirm)}
+ </AlertDialogAction>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
+ );
+}
+
+function DisconnectPersonalDialog({ target, onClose }: { target: AccountTarget; onClose: () => void }) {
+ const { t } = useT("settings");
+ const wsId = useWorkspaceId();
+ const qc = useQueryClient();
+ const [pending, setPending] = useState(false);
+
+ return (
+ <AlertDialog open onOpenChange={(open) => !open && !pending && onClose()}>
+ <AlertDialogContent>
+ <AlertDialogHeader>
+ <AlertDialogTitle>{t(($) => $.connected_apps.disconnect_personal.title, { app: target.name })}</AlertDialogTitle>
+ <AlertDialogDescription>{t(($) => $.connected_apps.disconnect_personal.description)}</AlertDialogDescription>
+ </AlertDialogHeader>
+ <AlertDialogFooter>
+ <AlertDialogCancel disabled={pending}>{t(($) => $.connected_apps.disconnect_personal.cancel)}</AlertDialogCancel>
+ <AlertDialogAction
+ variant="destructive"
+ disabled={pending}
+ onClick={async () => {
+ setPending(true);
+ try {
+ await api.deleteComposioConnection(target.connection.id);
+ await qc.invalidateQueries({ queryKey: connectedAppsKeys.all(wsId) });
+ toast.success(t(($) => $.connected_apps.toast_disconnected));
+ onClose();
+ } catch {
+ toast.error(t(($) => $.connected_apps.toast_failed));
+ } finally {
+ setPending(false);
+ }
+ }}
+ >
+ {t(($) => $.connected_apps.disconnect_personal.confirm)}
+ </AlertDialogAction>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
+ );
+}
diff --git a/packages/views/settings/components/composio-tab.test.tsx b/packages/views/settings/components/composio-tab.test.tsx
deleted file mode 100644
index 124421e108..0000000000
--- a/packages/views/settings/components/composio-tab.test.tsx
+++ /dev/null
@@ -1,194 +0,0 @@
-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,
- hash: "",
- 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=apps");
- });
-
- 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=apps");
- });
-
- 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.tsx
deleted file mode 100644
index f6f598ac6e..0000000000
--- a/packages/views/settings/components/composio-tab.tsx
+++ /dev/null
@@ -1,353 +0,0 @@
-"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 "@multica/ui/icons";
-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 connectable Composio toolkit catalog and lets the
-// user connect / disconnect the apps their agents can act on.
-//
-// Key UX rule (MUL-4009): the backend only returns toolkits with an enabled
-// auth config in the Composio project, so every card here is connectable —
-// toolkits with no auth config are filtered out server-side rather than shown
-// with a dead "not configured" hint. The `toolkit.connectable` guard on the
-// Connect button is kept as a client-side backstop (older/misbehaving servers
-// could still send a non-connectable entry); such an entry simply renders no
-// action affordance rather than a broken 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));
- }
- // The OAuth service returns to the retired `?tab=integrations` URL. Drop
- // the one-shot params and point the URL at this page, keeping everything
- // else, so a refresh neither re-toasts nor leaves the legacy tab behind.
- const params = new URLSearchParams(navigation.searchParams);
- params.set("tab", "apps");
- params.delete("integration");
- 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]);
-
- // The reconnect branch is prepared, but the backend does not yet emit "expired".
- 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]);
-
- 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]);
-
- // Deployment-disabled 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">
- {toolkitsQuery.isLoading ? (
- <Card>
- <CardContent>
- <p className="text-body text-muted-foreground">{t(($) => $.composio.loading)}</p>
- </CardContent>
- </Card>
- ) : toolkitsQuery.isError ? (
- <Card>
- <CardContent>
- <p className="text-body text-destructive">{t(($) => $.composio.load_failed)}</p>
- </CardContent>
- </Card>
- ) : toolkits.length === 0 ? (
- <Card>
- <CardContent className="space-y-2">
- <p className="text-body font-medium">{t(($) => $.composio.empty_title)}</p>
- <p className="text-caption 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-caption 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-body 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-micro text-muted-foreground">
- {lastUsedAt
- ? t(($) => $.composio.last_used, { when: timeAgo(lastUsedAt) })
- : t(($) => $.composio.last_used_never)}
- </p>
- ) : toolkit.category ? (
- <p className="truncate text-micro 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-caption 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 ? (
- <div className="flex items-center gap-2">
- <span className="inline-flex items-center gap-1 text-caption 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>
- ) : null}
- </CardContent>
- </Card>
- );
-}
diff --git a/packages/views/settings/components/connected-apps-tab.tsx b/packages/views/settings/components/connected-apps-tab.tsx
index ae46ade500..d6aa9054ad 100644
--- a/packages/views/settings/components/connected-apps-tab.tsx
+++ b/packages/views/settings/components/connected-apps-tab.tsx
@@ -6,7 +6,7 @@ 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";
-import { ComposioTab } from "./composio-tab";
+import { AppsSettings } from "./apps-settings";
import { SettingsTab } from "./settings-layout";
/**
@@ -25,17 +25,14 @@ export function useComposioAvailable(): boolean {
}
/**
- * App connections belong to the signed-in account, not the workspace: the
- * user authorizes their own Gmail or Notion and enables it on agents they own.
+ * Connected apps belong to the workspace: team accounts are shared and
+ * admin-managed, personal accounts are each member's own (MUL-8516).
*/
export function ConnectedAppsTab() {
const { t } = useT("settings");
return (
- <SettingsTab
- title={t(($) => $.page.tabs.apps)}
- scope="account"
- >
- <ComposioTab />
+ <SettingsTab title={t(($) => $.page.tabs.apps)} scope="workspace">
+ <AppsSettings />
</SettingsTab>
);
}
diff --git a/packages/views/settings/components/custom-catalog-dialog.tsx b/packages/views/settings/components/custom-catalog-dialog.tsx
new file mode 100644
index 0000000000..53438f2087
--- /dev/null
+++ b/packages/views/settings/components/custom-catalog-dialog.tsx
@@ -0,0 +1,129 @@
+"use client";
+
+import { useMemo, useState } from "react";
+import { useQuery } from "@tanstack/react-query";
+import { toast } from "sonner";
+import { Loader2 } from "@multica/ui/icons";
+import { Badge } from "@multica/ui/components/ui/badge";
+import { Button } from "@multica/ui/components/ui/button";
+import { Checkbox } from "@multica/ui/components/ui/checkbox";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from "@multica/ui/components/ui/dialog";
+import { Input } from "@multica/ui/components/ui/input";
+import { useWorkspaceId } from "@multica/core/hooks";
+import { fullAppCatalogOptions, useUpdateAppSettings } from "@multica/core/connected-apps";
+import { ComposioToolkitLogo } from "../../common/composio-toolkit-logo";
+import { useT } from "../../i18n";
+
+/**
+ * Picks the apps of a custom catalog. Saving switches the workspace to it:
+ * agents see only these apps, and nobody can add an account for another.
+ */
+export function CustomCatalogDialog({
+ initial,
+ onClose,
+}: {
+ initial: string[];
+ onClose: () => void;
+}) {
+ const { t } = useT("settings");
+ const wsId = useWorkspaceId();
+ const catalog = useQuery(fullAppCatalogOptions(wsId));
+ const update = useUpdateAppSettings();
+ const [query, setQuery] = useState("");
+ const [selected, setSelected] = useState(() => new Set(initial));
+
+ const apps = useMemo(() => {
+ const q = query.trim().toLowerCase();
+ const all = catalog.data?.apps ?? [];
+ const matches = q
+ ? all.filter((app) => app.name.toLowerCase().includes(q) || app.slug.includes(q))
+ : all;
+ // Chosen apps first so the current list reads at a glance.
+ return [...matches].sort((a, b) => Number(selected.has(b.slug)) - Number(selected.has(a.slug)));
+ // Re-sorting on every toggle would move the row under the cursor.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [catalog.data, query]);
+
+ const toggle = (slug: string, checked: boolean) =>
+ setSelected((prev) => {
+ const next = new Set(prev);
+ if (checked) next.add(slug);
+ else next.delete(slug);
+ return next;
+ });
+
+ const save = () =>
+ update.mutate(
+ { catalog_mode: "custom", allowed_toolkits: [...selected] },
+ {
+ onSuccess: () => {
+ toast.success(t(($) => $.connected_apps.custom.saved));
+ onClose();
+ },
+ onError: () => toast.error(t(($) => $.connected_apps.toast_failed)),
+ },
+ );
+
+ return (
+ <Dialog open onOpenChange={(open) => !open && !update.isPending && onClose()}>
+ <DialogContent className="sm:max-w-xl">
+ <DialogHeader>
+ <DialogTitle>{t(($) => $.connected_apps.custom.title)}</DialogTitle>
+ <DialogDescription>{t(($) => $.connected_apps.custom.description)}</DialogDescription>
+ </DialogHeader>
+ <Input
+ autoFocus
+ value={query}
+ onChange={(e) => setQuery(e.target.value)}
+ placeholder={t(($) => $.connected_apps.add.search)}
+ />
+ <div className="max-h-[50vh] min-h-48 overflow-y-auto rounded-lg border">
+ {catalog.isLoading ? (
+ <p className="p-4 text-caption text-muted-foreground">{t(($) => $.connected_apps.loading)}</p>
+ ) : catalog.isError ? (
+ <p className="p-4 text-caption text-destructive">{t(($) => $.connected_apps.load_failed)}</p>
+ ) : apps.length === 0 ? (
+ <p className="p-4 text-caption text-muted-foreground">{t(($) => $.connected_apps.add.empty)}</p>
+ ) : (
+ <ul className="divide-y">
+ {apps.map((app) => (
+ <li key={app.slug}>
+ <label className="flex cursor-pointer items-center gap-3 px-3 py-2">
+ <Checkbox
+ checked={selected.has(app.slug)}
+ onCheckedChange={(checked) => toggle(app.slug, checked === true)}
+ />
+ <ComposioToolkitLogo slug={app.slug} name={app.name} fallbackLogo={app.logo} className="size-6" />
+ <span className="min-w-0 flex-1 truncate text-body">{app.name || app.slug}</span>
+ {app.curated && <Badge variant="secondary">{t(($) => $.connected_apps.add.curated)}</Badge>}
+ </label>
+ </li>
+ ))}
+ </ul>
+ )}
+ </div>
+ <DialogFooter className="items-center sm:justify-between">
+ <span className="text-caption text-muted-foreground">
+ {t(($) => $.connected_apps.custom.selected, { count: selected.size })}
+ </span>
+ <div className="flex gap-2">
+ <Button variant="outline" disabled={update.isPending} onClick={onClose}>
+ {t(($) => $.connected_apps.custom.cancel)}
+ </Button>
+ <Button disabled={selected.size === 0 || update.isPending} onClick={save}>
+ {update.isPending && <Loader2 className="animate-spin" />}
+ {t(($) => $.connected_apps.custom.save)}
+ </Button>
+ </div>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ );
+}
diff --git a/packages/views/settings/components/settings-page.test.tsx b/packages/views/settings/components/settings-page.test.tsx
index fed899b782..d682b6713f 100644
--- a/packages/views/settings/components/settings-page.test.tsx
+++ b/packages/views/settings/components/settings-page.test.tsx
@@ -352,7 +352,7 @@ describe("SettingsPage information architecture", () => {
);
});
- it("lists Connected apps with the personal pages only when Composio is available", () => {
+ it("lists Connected apps with the workspace connections only when Composio is available", () => {
const first = renderWithI18n(<SettingsPage />);
expect(screen.queryByRole("link", { name: "Connected apps" })).toBeNull();
first.unmount();
@@ -361,8 +361,9 @@ describe("SettingsPage information architecture", () => {
navigationState.search = "tab=integrations&connected=notion";
renderWithI18n(<SettingsPage />);
const personal = within(nav()).getByRole("region", { name: /Personal/ });
+ expect(within(personal).queryByRole("link", { name: "Connected apps" })).toBeNull();
expect(
- within(personal).getByRole("link", { name: "Connected apps" }),
+ within(nav()).getByRole("link", { name: "Connected apps" }),
).toHaveAttribute("aria-current", "page");
expect(screen.getByText("ConnectedAppsTab")).toBeInTheDocument();
});
diff --git a/packages/views/settings/components/settings-page.tsx b/packages/views/settings/components/settings-page.tsx
index 559d18ba23..dde093fcc4 100644
--- a/packages/views/settings/components/settings-page.tsx
+++ b/packages/views/settings/components/settings-page.tsx
@@ -169,9 +169,6 @@ export function SettingsPage({ extraDeviceTabs = [] }: SettingsPageProps = {}) {
Keyboard,
<KeyboardShortcutsTab />,
),
- ...(appsAvailable
- ? [entry("apps", t(($) => $.page.tabs.apps), Plug, <ConnectedAppsTab />)]
- : []),
entry("tokens", t(($) => $.page.tabs.tokens), KeyRound, <TokensTab />),
],
},
@@ -246,6 +243,9 @@ export function SettingsPage({ extraDeviceTabs = [] }: SettingsPageProps = {}) {
MessagesSquare,
<ChannelsTab />,
),
+ ...(appsAvailable
+ ? [entry("apps", t(($) => $.page.tabs.apps), Plug, <ConnectedAppsTab />)]
+ : []),
entry("mcp", t(($) => $.page.tabs.mcp), Server, <McpTab />, {
adminOnly: true,
}),
diff --git a/packages/views/settings/components/use-settings-search-index.ts b/packages/views/settings/components/use-settings-search-index.ts
index 61ea6d7a1d..b9b7537dde 100644
--- a/packages/views/settings/components/use-settings-search-index.ts
+++ b/packages/views/settings/components/use-settings-search-index.ts
@@ -125,7 +125,7 @@ export function useSettingsSearchIndex(
{
tab: "apps",
title: t(($) => $.page.tabs.apps),
- description: t(($) => $.composio.page_description),
+ description: t(($) => $.connected_apps.description),
},
// Workspace
{ tab: "workspace", anchor: "name", title: t(($) => $.workspace.name_label) },
diff --git a/server/cmd/migrate/main.go b/server/cmd/migrate/main.go
index fcdb4f67cf..83b62187bc 100644
--- a/server/cmd/migrate/main.go
+++ b/server/cmd/migrate/main.go
@@ -140,6 +140,17 @@ var pgBigmOperatorClass = extensionOperatorClass{
// they are still pending: a fresh self-hosted install, which is exactly where an
// interrupted build would otherwise leave a permanently unusable index.
var concurrentIndexCleanups = map[string]string{
+ "628_app_action_request_chat_idx": "idx_app_action_request_chat",
+ "627_app_tool_call_issue_idx": "idx_app_tool_call_issue",
+ "626_app_action_request_task_idx": "idx_app_action_request_task",
+ "625_app_tool_call_workspace_idx": "idx_app_tool_call_workspace",
+ "624_app_action_request_pending_idx": "idx_app_action_request_pending",
+ "623_app_action_request_issue_idx": "idx_app_action_request_issue",
+ "622_app_action_rule_scope_idx": "idx_app_action_rule_scope",
+ "621_agent_app_workspace_toolkit_idx": "idx_agent_app_workspace_toolkit",
+ "620_agent_app_agent_toolkit_idx": "idx_agent_app_agent_toolkit",
+ "619_workspace_composio_connection_status_idx": "idx_workspace_composio_connection_status",
+ "618_workspace_composio_connection_account_idx": "idx_workspace_composio_connection_account",
"613_skill_version_index": "idx_skill_version_skill_version",
"606_agent_task_queue_runtime_active_index": "idx_agent_task_queue_runtime_active",
"604_wecom_install_session_begin_rate_idx": "idx_wecom_install_session_begin_rate",
diff --git a/server/cmd/server/main.go b/server/cmd/server/main.go
index 5bb3253a13..781635ca5b 100644
--- a/server/cmd/server/main.go
+++ b/server/cmd/server/main.go
@@ -765,6 +765,9 @@ func main() {
// Source-context cleanup is object-store work, so it gets its own goroutine
// instead of a slot in the runtime sweep tick.
go runSourceContextSweeper(sweepCtx, taskSvc)
+ if h.ConnectedApps != nil {
+ go h.ConnectedApps.RunSweeper(sweepCtx)
+ }
go heartbeatScheduler.Run(sweepCtx)
go runAutopilotFailureMonitor(autopilotCtx, queries, bus, envFailureMonitorConfig())
if autopilotSvc.QuotaEnabled() {
diff --git a/server/cmd/server/router.go b/server/cmd/server/router.go
index f92744e804..2da0173564 100644
--- a/server/cmd/server/router.go
+++ b/server/cmd/server/router.go
@@ -24,6 +24,7 @@ import (
"github.com/multica-ai/multica/server/internal/attachmentpreview"
"github.com/multica-ai/multica/server/internal/auth"
"github.com/multica-ai/multica/server/internal/cloudruntime"
+ "github.com/multica-ai/multica/server/internal/connectedapps"
"github.com/multica-ai/multica/server/internal/daemonws"
"github.com/multica-ai/multica/server/internal/entitlement"
"github.com/multica-ai/multica/server/internal/events"
@@ -1340,6 +1341,22 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus
slog.Error("composio: service init failed; composio integration disabled", "error", serr)
} else {
h.Composio = svc
+ // Connected Apps v2 (MUL-8516): runs reach their apps
+ // through the Multica gateway, which holds the Composio
+ // key and applies account rules and confirmations.
+ appsSvc, aerr := connectedapps.New(connectedapps.Config{
+ Queries: queries,
+ Composio: svc,
+ TokenSecret: connectedapps.DeriveTokenSecret(stateSecret),
+ PublicBaseURL: callbackBase,
+ Bus: bus,
+ })
+ if aerr != nil {
+ slog.Error("connected apps: init failed; agents run without apps", "error", aerr)
+ } else {
+ appsSvc.SetResumer(h)
+ h.ConnectedApps = appsSvc
+ }
// 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
@@ -1348,8 +1365,8 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus
// 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
+ if h.TaskService != nil && h.ConnectedApps != nil {
+ h.TaskService.Composio = h.ConnectedApps
}
slog.Info("composio integration enabled")
}
@@ -1618,6 +1635,9 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus
// 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)
+ // Apps MCP gateway (MUL-8516). Outside the Auth group: a run presents its
+ // task-scoped bearer token, verified by the gateway itself.
+ r.Post("/api/apps/mcp", h.AppsGateway)
// Daemon API routes (require daemon token or valid user token)
r.Route("/api/daemon", func(r chi.Router) {
@@ -2359,6 +2379,8 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus
r.Route("/{id}", func(r chi.Router) {
r.Get("/", h.GetAgent)
r.Put("/", h.UpdateAgent)
+ r.Get("/apps", h.ListAgentApps)
+ r.With(handler.RequireHumanActor).Put("/apps", h.UpdateAgentApps)
r.Post("/archive", h.ArchiveAgent)
r.Post("/restore", h.RestoreAgent)
r.Post("/cancel-tasks", h.CancelAgentTasks)
@@ -2559,6 +2581,32 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus
r.Get("/api/chat/history", h.GetChatChannelHistory)
r.Get("/api/chat/thread", h.GetChatThread)
+ // Connected Apps (MUL-8516)
+ // Connected Apps management and decisions are for people; runs
+ // reach apps only through /api/apps/mcp.
+ r.Route("/api/apps", func(r chi.Router) {
+ r.Use(handler.RequireHumanActor)
+ r.Get("/", h.GetAppsOverview)
+ r.Get("/catalog", h.ListAppCatalog)
+ r.Put("/settings", h.UpdateAppSettings)
+ r.Post("/team/connect", h.ConnectTeamApp)
+ r.Get("/team/impact", h.GetTeamAppImpact)
+ r.Delete("/team/connections/{id}", h.DisconnectTeamApp)
+ r.Post("/personal/connect", h.ConnectPersonalApp)
+ r.Get("/rules", h.GetAppRules)
+ r.Put("/rules", h.UpdateAppRules)
+ r.Get("/activity", h.ListAppActivity)
+ r.Get("/tools", h.ListAppTools)
+ r.Put("/tools/class", h.UpdateAppToolClass)
+ })
+ r.With(handler.RequireHumanActor).Get("/api/app-calls", h.ListIssueAppCalls)
+ r.Route("/api/app-requests", func(r chi.Router) {
+ r.Use(handler.RequireHumanActor)
+ r.Get("/", h.ListAppRequests)
+ r.Post("/{id}/approve", h.ApproveAppRequest)
+ r.Post("/{id}/reject", h.RejectAppRequest)
+ })
+
// Inbox
r.Route("/api/inbox", func(r chi.Router) {
r.Get("/", h.ListInbox)
diff --git a/server/internal/connectedapps/catalog.go b/server/internal/connectedapps/catalog.go
new file mode 100644
index 0000000000..44af167d04
--- /dev/null
+++ b/server/internal/connectedapps/catalog.go
@@ -0,0 +1,125 @@
+// Package connectedapps owns how agents use external apps (MUL-8516): which
+// account a run acts as, what each tool call is allowed to do, and the
+// confirmation flow for calls that need a person's approval.
+//
+// Agents never see a provider credential. A run reaches its apps through the
+// Multica MCP gateway, which resolves the account, classifies the tool, applies
+// the workspace and personal rules, and only then executes through the
+// provider.
+package connectedapps
+
+import "strings"
+
+// Account scopes an agent app can act through.
+const (
+ ScopeTeam = "team"
+ ScopePersonal = "personal"
+)
+
+// Agent permission levels for one app.
+const (
+ LevelRead = "read"
+ LevelConfirmWrites = "confirm_writes"
+ LevelWrite = "write"
+)
+
+// Workspace catalog modes.
+const (
+ CatalogAll = "all"
+ CatalogCurated = "curated"
+ CatalogCustom = "custom"
+)
+
+// CuratedApp is an app Multica has tested end to end. Curated apps carry a
+// badge in the catalog, a recommended account type, and hand-checked tool
+// classes; every other app works through automatic classification.
+type CuratedApp struct {
+ Slug string
+ // Scope is the recommended account type: team, personal, or "" for either.
+ Scope string
+ // Defaults overrides the workspace default policy for this app.
+ Defaults map[string]string
+ // Overrides pins the class of specific tools, keyed by upper-case tool slug.
+ Overrides map[string]string
+}
+
+var curatedApps = []CuratedApp{
+ {Slug: "gmail", Scope: ScopePersonal},
+ {Slug: "googlecalendar", Scope: ScopePersonal, Overrides: map[string]string{
+ "GOOGLECALENDAR_CREATE_EVENT": ClassSend,
+ "GOOGLECALENDAR_UPDATE_EVENT": ClassSend,
+ "GOOGLECALENDAR_PATCH_EVENT": ClassSend,
+ "GOOGLECALENDAR_QUICK_ADD": ClassSend,
+ "GOOGLECALENDAR_FIND_FREE_SLOTS": ClassRead,
+ }},
+ {Slug: "outlook", Scope: ScopePersonal},
+ {Slug: "slack", Scope: ScopePersonal},
+ {Slug: "notion"},
+ {Slug: "googledrive"},
+ {Slug: "googledocs"},
+ {Slug: "googlesheets"},
+ {Slug: "confluence"},
+ {Slug: "linear"},
+ {Slug: "jira"},
+ {Slug: "asana"},
+ {Slug: "figma"},
+ {Slug: "sentry", Scope: ScopeTeam},
+ {Slug: "posthog", Scope: ScopeTeam},
+ {Slug: "hubspot", Scope: ScopeTeam},
+ {Slug: "zendesk", Scope: ScopeTeam},
+ {Slug: "intercom", Scope: ScopeTeam},
+ {Slug: "stripe", Scope: ScopeTeam, Defaults: map[string]string{
+ ClassWrite: PolicyBlock,
+ ClassSend: PolicyBlock,
+ ClassDelete: PolicyBlock,
+ }},
+ {Slug: "airtable", Scope: ScopeTeam},
+}
+
+var curatedBySlug = func() map[string]CuratedApp {
+ m := make(map[string]CuratedApp, len(curatedApps))
+ for _, app := range curatedApps {
+ m[app.Slug] = app
+ }
+ return m
+}()
+
+// Curated returns the curated entry for slug.
+func Curated(slug string) (CuratedApp, bool) {
+ app, ok := curatedBySlug[NormalizeSlug(slug)]
+ return app, ok
+}
+
+// CuratedSlugs returns the curated apps in catalog order.
+func CuratedSlugs() []string {
+ out := make([]string, 0, len(curatedApps))
+ for _, app := range curatedApps {
+ out = append(out, app.Slug)
+ }
+ return out
+}
+
+// NormalizeSlug lowercases and trims a toolkit slug.
+func NormalizeSlug(slug string) string {
+ return strings.ToLower(strings.TrimSpace(slug))
+}
+
+// ValidScope reports whether scope is an account scope.
+func ValidScope(scope string) bool {
+ return scope == ScopeTeam || scope == ScopePersonal
+}
+
+// DefaultLevel is the level an app joins an agent at. Only the owner can run
+// a private agent, so the owner is the one who would confirm each write;
+// shared agents ask first.
+func DefaultLevel(agentPermissionMode string) string {
+ if agentPermissionMode == "private" {
+ return LevelWrite
+ }
+ return LevelConfirmWrites
+}
+
+// ValidLevel reports whether level is an agent permission level.
+func ValidLevel(level string) bool {
+ return level == LevelRead || level == LevelConfirmWrites || level == LevelWrite
+}
diff --git a/server/internal/connectedapps/classify.go b/server/internal/connectedapps/classify.go
new file mode 100644
index 0000000000..0440226329
--- /dev/null
+++ b/server/internal/connectedapps/classify.go
@@ -0,0 +1,231 @@
+package connectedapps
+
+import "strings"
+
+// Action classes. Every tool call is one of these; rules are written per class.
+const (
+ ClassRead = "read"
+ ClassWrite = "write"
+ ClassSend = "send"
+ ClassDelete = "delete"
+ ClassShare = "share"
+)
+
+// Classes lists the action classes in the order settings render them.
+var Classes = []string{ClassRead, ClassWrite, ClassSend, ClassDelete, ClassShare}
+
+// ValidClass reports whether class is an action class.
+func ValidClass(class string) bool {
+ for _, c := range Classes {
+ if c == class {
+ return true
+ }
+ }
+ return false
+}
+
+var verbClasses = func() map[string]string {
+ m := map[string]string{}
+ add := func(class string, verbs ...string) {
+ for _, v := range verbs {
+ m[v] = class
+ }
+ }
+ add(ClassRead,
+ "GET", "GETS", "LIST", "LISTS", "FETCH", "FETCHES", "SEARCH", "SEARCHES", "FIND", "FINDS",
+ "READ", "READS", "RETRIEVE", "RETRIEVES", "QUERY", "QUERIES", "DOWNLOAD", "VIEW", "CHECK",
+ "COUNT", "DESCRIBE", "LOOKUP", "LOAD", "EXPORT", "SHOW", "BROWSE", "PREVIEW", "LOOK",
+ )
+ add(ClassWrite,
+ "CREATE", "CREATES", "UPDATE", "UPDATES", "ADD", "ADDS", "INSERT", "SET", "EDIT", "MODIFY",
+ "PATCH", "PUT", "APPEND", "UPSERT", "MOVE", "RENAME", "UPLOAD", "DUPLICATE", "COPY", "MARK",
+ "STAR", "UNSTAR", "LABEL", "MERGE", "ASSIGN", "UNASSIGN", "CLOSE", "REOPEN", "ENABLE",
+ "DISABLE", "START", "STOP", "RUN", "EXECUTE", "TRIGGER", "REPLACE", "RESTORE", "IMPORT",
+ "CONVERT", "APPLY", "PIN", "UNPIN", "REACT", "LIKE", "COMPLETE", "RESOLVE", "APPROVE",
+ "TAG", "MAKE", "SCHEDULE", "SAVE", "WRITE", "CHANGE", "LINK", "UNLINK", "ATTACH", "DRAFT",
+ )
+ add(ClassSend,
+ "SEND", "SENDS", "REPLY", "REPLIES", "FORWARD", "POST", "PUBLISH", "NOTIFY",
+ "BROADCAST", "INVITE", "CALL", "SMS", "TWEET", "RESPOND", "SUBMIT", "EMAIL", "MESSAGE",
+ )
+ add(ClassDelete,
+ "DELETE", "DELETES", "REMOVE", "REMOVES", "TRASH", "PURGE", "DESTROY", "ERASE", "CANCEL",
+ "REVOKE", "UNSUBSCRIBE", "ARCHIVE", "CLEAR", "EMPTY", "DROP", "WIPE", "KICK", "BAN",
+ )
+ add(ClassShare, "SHARE", "SHARES", "GRANT", "UNSHARE", "TRANSFER")
+ return m
+}()
+
+// Nouns that turn a write into a share: the call changes who can see or act.
+var shareNouns = map[string]bool{
+ "SHARING": true, "PERMISSION": true, "PERMISSIONS": true, "ACL": true, "COLLABORATOR": true,
+ "COLLABORATORS": true, "MEMBER": true, "MEMBERS": true, "ACCESS": true, "OWNER": true,
+ "OWNERSHIP": true, "PUBLIC": true, "ADMIN": true, "ADMINS": true, "ROLE": true,
+ "ROLES": true, "PRIVILEGE": true, "PRIVILEGES": true, "VISIBILITY": true,
+}
+
+// Nouns that turn a write into a delete ("move to trash").
+var deleteNouns = map[string]bool{"TRASH": true, "BIN": true}
+
+// Objects that reach other people once written: scheduling a message, or
+// creating an event that invites attendees, is a send.
+var sendObjects = map[string]bool{
+ "MESSAGE": true, "MESSAGES": true, "EMAIL": true, "EMAILS": true, "MAIL": true,
+ "EVENT": true, "EVENTS": true, "INVITATION": true, "INVITATIONS": true, "INVITE": true,
+ "INVITES": true, "MEETING": true, "MEETINGS": true, "REPLY": true, "DM": true,
+}
+
+// Words between a verb and its object ("create a new event").
+var fillerWords = map[string]bool{"A": true, "AN": true, "THE": true, "NEW": true}
+
+// Argument names that address other people. A write carrying one of them
+// reaches those people, so it is confirmed like a send.
+var recipientArgs = map[string]bool{
+ "to": true, "cc": true, "bcc": true, "recipient": true, "recipients": true,
+ "recipient_email": true, "recipient_emails": true, "attendees": true, "invitees": true,
+ "guests": true, "participants": true, "required_attendees": true, "optional_attendees": true,
+}
+
+// Boolean or enum arguments that make the provider notify people.
+var notifyArgs = map[string]bool{
+ "send_updates": true, "send_notifications": true, "send_invitations": true,
+ "notify": true, "notify_users": true, "send_notification_email": true,
+}
+
+// Flags that turn an update into a delete: Notion's UPDATE_PAGE with
+// archived=true (or in_trash=true) and Drive's file update with trashed=true
+// move the item to trash. Setting them false restores it, which stays a write.
+var deleteArgs = map[string]bool{
+ "archived": true, "archive": true, "is_archived": true, "in_trash": true,
+ "trashed": true, "deleted": true, "is_deleted": true,
+}
+
+// Classify returns the action class of a tool. Curated overrides win; then the
+// first verb in the tool slug decides, with nouns upgrading a write to share or
+// delete. MCP annotations break the tie for slugs without a known verb. A tool
+// nothing recognizes is "send": unknown effects get the confirmation default
+// rather than silently running.
+func Classify(toolkitSlug, toolSlug string, tags []string) string {
+ upper := strings.ToUpper(strings.TrimSpace(toolSlug))
+ if app, ok := Curated(toolkitSlug); ok {
+ if class, ok := app.Overrides[upper]; ok {
+ return class
+ }
+ }
+ prefix := strings.ToUpper(NormalizeSlug(toolkitSlug)) + "_"
+ tokens := strings.Split(strings.TrimPrefix(upper, prefix), "_")
+
+ class, verbAt := "", -1
+ for i, tok := range tokens {
+ if c, ok := verbClasses[tok]; ok {
+ class, verbAt = c, i
+ break
+ }
+ }
+ if class == ClassWrite {
+ for _, tok := range tokens {
+ if shareNouns[tok] {
+ return ClassShare
+ }
+ if deleteNouns[tok] {
+ return ClassDelete
+ }
+ }
+ if !isDraft(tokens) {
+ if obj := objectAfter(tokens, verbAt); sendObjects[obj] {
+ return ClassSend
+ }
+ }
+ }
+ if class != "" {
+ return class
+ }
+ for _, tag := range tags {
+ switch strings.ToLower(strings.TrimSpace(tag)) {
+ case "destructivehint":
+ return ClassDelete
+ case "readonlyhint":
+ return ClassRead
+ }
+ }
+ return ClassSend
+}
+
+func isDraft(tokens []string) bool {
+ for _, tok := range tokens {
+ if tok == "DRAFT" || tok == "DRAFTS" {
+ return true
+ }
+ }
+ return false
+}
+
+// objectAfter returns the first content word after the verb.
+func objectAfter(tokens []string, verbAt int) string {
+ for _, tok := range tokens[verbAt+1:] {
+ if !fillerWords[tok] {
+ return tok
+ }
+ }
+ return ""
+}
+
+// ClassifyCall refines a tool's class with the arguments of one call: a write
+// that archives or trashes its target is a delete, and a write addressed to
+// other people, or asking the app to notify them, is a send. Drafts are never
+// sends; they reach nobody until sent.
+func ClassifyCall(class, toolSlug string, args map[string]any) string {
+ if class != ClassWrite || len(args) == 0 {
+ return class
+ }
+ for key, value := range args {
+ if deleteArgs[strings.ToLower(strings.TrimSpace(key))] && truthy(value) {
+ return ClassDelete
+ }
+ }
+ if isDraft(strings.Split(strings.ToUpper(toolSlug), "_")) {
+ return class
+ }
+ for key, value := range args {
+ k := strings.ToLower(strings.TrimSpace(key))
+ if recipientArgs[k] && hasValue(value) {
+ return ClassSend
+ }
+ if notifyArgs[k] && truthy(value) {
+ return ClassSend
+ }
+ }
+ return class
+}
+
+func hasValue(v any) bool {
+ switch t := v.(type) {
+ case nil:
+ return false
+ case string:
+ return strings.TrimSpace(t) != ""
+ case []any:
+ return len(t) > 0
+ case map[string]any:
+ return len(t) > 0
+ default:
+ return true
+ }
+}
+
+func truthy(v any) bool {
+ switch t := v.(type) {
+ case bool:
+ return t
+ case float64:
+ return t != 0
+ case string:
+ switch strings.ToLower(strings.TrimSpace(t)) {
+ case "", "none", "false", "no", "0":
+ return false
+ }
+ return true
+ default:
+ return false
+ }
+}
diff --git a/server/internal/connectedapps/gateway.go b/server/internal/connectedapps/gateway.go
new file mode 100644
index 0000000000..31ef1ee7ae
--- /dev/null
+++ b/server/internal/connectedapps/gateway.go
@@ -0,0 +1,545 @@
+package connectedapps
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "io"
+ "log/slog"
+ "net/http"
+ "sort"
+ "strings"
+
+ "github.com/jackc/pgx/v5/pgtype"
+ "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"
+)
+
+const (
+ maxGatewayBody = 1 << 20
+ maxResultBytes = 60_000
+ maxSearchResults = 40
+ mcpVersion = "2025-03-26"
+)
+
+// Gateway tool names.
+const (
+ toolListApps = "apps_list"
+ toolSearchTools = "apps_search_tools"
+ toolGetTool = "apps_get_tool"
+ toolRunTool = "apps_run_tool"
+ toolRequestConnection = "apps_request_connection"
+)
+
+type rpcRequest struct {
+ JSONRPC string `json:"jsonrpc"`
+ ID json.RawMessage `json:"id,omitempty"`
+ Method string `json:"method"`
+ Params json.RawMessage `json:"params,omitempty"`
+}
+
+type rpcError struct {
+ Code int `json:"code"`
+ Message string `json:"message"`
+}
+
+type rpcResponse struct {
+ JSONRPC string `json:"jsonrpc"`
+ ID json.RawMessage `json:"id"`
+ Result any `json:"result,omitempty"`
+ Error *rpcError `json:"error,omitempty"`
+}
+
+// run is everything the gateway knows about the calling run.
+type run struct {
+ task db.AgentTaskQueue
+ agent db.Agent
+ workspaceID pgtype.UUID
+ triggeredBy pgtype.UUID
+ catalog Catalog
+ apps map[string]db.AgentApp
+}
+
+// ServeHTTP is the MCP gateway (streamable HTTP, JSON responses only). A run
+// authenticates with the bearer token minted at claim; the token only works
+// while its task is dispatched or running.
+func (s *Service) ServeHTTP(w http.ResponseWriter, r *http.Request) {
+ if r.Method != http.MethodPost {
+ w.Header().Set("Allow", http.MethodPost)
+ http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
+ return
+ }
+ token, _ := strings.CutPrefix(r.Header.Get("Authorization"), "Bearer ")
+ taskID, err := VerifyTaskToken(s.secret, token, s.now())
+ if err != nil {
+ http.Error(w, "unauthorized", http.StatusUnauthorized)
+ return
+ }
+ rn, err := s.loadRun(r.Context(), taskID)
+ if err != nil {
+ http.Error(w, "unauthorized", http.StatusUnauthorized)
+ return
+ }
+ body, err := io.ReadAll(io.LimitReader(r.Body, maxGatewayBody+1))
+ if err != nil || len(body) > maxGatewayBody {
+ http.Error(w, "request too large", http.StatusRequestEntityTooLarge)
+ return
+ }
+
+ trimmed := strings.TrimSpace(string(body))
+ var reqs []rpcRequest
+ batch := strings.HasPrefix(trimmed, "[")
+ if batch {
+ err = json.Unmarshal(body, &reqs)
+ } else {
+ var one rpcRequest
+ err = json.Unmarshal(body, &one)
+ reqs = []rpcRequest{one}
+ }
+ if err != nil {
+ writeJSON(w, rpcResponse{JSONRPC: "2.0", ID: json.RawMessage("null"), Error: &rpcError{Code: -32700, Message: "parse error"}})
+ return
+ }
+ var out []rpcResponse
+ for _, req := range reqs {
+ resp, notify := s.dispatch(r.Context(), rn, req)
+ if !notify {
+ out = append(out, resp)
+ }
+ }
+ if len(out) == 0 {
+ w.WriteHeader(http.StatusAccepted)
+ return
+ }
+ if batch {
+ writeJSON(w, out)
+ return
+ }
+ writeJSON(w, out[0])
+}
+
+func writeJSON(w http.ResponseWriter, v any) {
+ w.Header().Set("Content-Type", "application/json")
+ _ = json.NewEncoder(w).Encode(v)
+}
+
+func (s *Service) loadRun(ctx context.Context, taskID string) (*run, error) {
+ id, err := util.ParseUUID(taskID)
+ if err != nil {
+ return nil, err
+ }
+ task, err := s.q.GetAgentTask(ctx, id)
+ if err != nil {
+ return nil, err
+ }
+ if task.Status != "dispatched" && task.Status != "running" {
+ return nil, fmt.Errorf("task %s is %s", taskID, task.Status)
+ }
+ agent, err := s.q.GetAgent(ctx, task.AgentID)
+ if err != nil {
+ return nil, err
+ }
+ apps, err := s.q.ListAgentApps(ctx, agent.ID)
+ if err != nil {
+ return nil, err
+ }
+ rn := &run{
+ task: task,
+ agent: agent,
+ workspaceID: agent.WorkspaceID,
+ triggeredBy: task.OriginatorUserID,
+ catalog: s.Catalog(ctx, agent.WorkspaceID),
+ apps: map[string]db.AgentApp{},
+ }
+ for _, app := range apps {
+ if rn.catalog.Allows(app.ToolkitSlug) {
+ rn.apps[NormalizeSlug(app.ToolkitSlug)] = app
+ }
+ }
+ return rn, nil
+}
+
+func (s *Service) dispatch(ctx context.Context, rn *run, req rpcRequest) (rpcResponse, bool) {
+ resp := rpcResponse{JSONRPC: "2.0", ID: req.ID}
+ notification := len(req.ID) == 0 || string(req.ID) == "null"
+ switch req.Method {
+ case "initialize":
+ var p struct {
+ ProtocolVersion string `json:"protocolVersion"`
+ }
+ _ = json.Unmarshal(req.Params, &p)
+ version := p.ProtocolVersion
+ if version == "" {
+ version = mcpVersion
+ }
+ resp.Result = map[string]any{
+ "protocolVersion": version,
+ "capabilities": map[string]any{"tools": map[string]any{}},
+ "serverInfo": map[string]any{"name": "multica-apps", "version": "1"},
+ "instructions": gatewayInstructions,
+ }
+ case "ping":
+ resp.Result = map[string]any{}
+ case "tools/list":
+ resp.Result = map[string]any{"tools": gatewayTools()}
+ case "tools/call":
+ var p struct {
+ Name string `json:"name"`
+ Arguments map[string]any `json:"arguments"`
+ }
+ if err := json.Unmarshal(req.Params, &p); err != nil {
+ resp.Error = &rpcError{Code: -32602, Message: "invalid params"}
+ break
+ }
+ resp.Result = s.callTool(ctx, rn, p.Name, p.Arguments)
+ default:
+ if strings.HasPrefix(req.Method, "notifications/") {
+ return resp, true
+ }
+ resp.Error = &rpcError{Code: -32601, Message: "method not found"}
+ }
+ return resp, notification
+}
+
+const gatewayInstructions = "Multica apps. Use apps_list to see your apps, apps_search_tools to find a tool, apps_get_tool for its input schema, then apps_run_tool. " +
+ "Some calls need a person's confirmation: apps_run_tool then answers that the call was submitted. When that happens, end your turn — " +
+ "you will be resumed with the outcome after they decide. Never retry a submitted call or work around a blocked one."
+
+func gatewayTools() []map[string]any {
+ str := func(desc string) map[string]any { return map[string]any{"type": "string", "description": desc} }
+ return []map[string]any{
+ {
+ "name": toolListApps,
+ "description": "List the external apps you can use in this run, whose account each acts as, your permission level, and whether the account is connected.",
+ "inputSchema": map[string]any{"type": "object", "properties": map[string]any{}},
+ },
+ {
+ "name": toolSearchTools,
+ "description": "Search the tools of one app. Returns tool slugs, what they do, and whether a call runs directly, needs confirmation, or is blocked.",
+ "inputSchema": map[string]any{
+ "type": "object",
+ "properties": map[string]any{
+ "app": str("App slug from apps_list, e.g. gmail"),
+ "query": str("Words describing what you want to do, e.g. 'send email'. Optional."),
+ },
+ "required": []string{"app"},
+ },
+ },
+ {
+ "name": toolGetTool,
+ "description": "Get one tool's input schema. Call before apps_run_tool.",
+ "inputSchema": map[string]any{
+ "type": "object",
+ "properties": map[string]any{"tool": str("Tool slug, e.g. GMAIL_SEND_EMAIL")},
+ "required": []string{"tool"},
+ },
+ },
+ {
+ "name": toolRunTool,
+ "description": "Run an app tool. Reads and allowed writes run immediately. A call that needs confirmation is submitted to the person who triggered this run " +
+ "and this tool answers 'submitted'; end your turn then — you will be resumed with the result. Blocked calls return an error; do not try to work around them.",
+ "inputSchema": map[string]any{
+ "type": "object",
+ "properties": map[string]any{
+ "tool": str("Tool slug, e.g. GMAIL_SEND_EMAIL"),
+ "arguments": map[string]any{"type": "object", "description": "Arguments matching the tool's input schema"},
+ "summary": str("One sentence for the person confirming: what this call does and why."),
+ },
+ "required": []string{"tool", "arguments"},
+ },
+ },
+ {
+ "name": toolRequestConnection,
+ "description": "Ask the person who triggered this run to connect their account for an app that shows not_connected. End your turn after calling it.",
+ "inputSchema": map[string]any{
+ "type": "object",
+ "properties": map[string]any{
+ "app": str("App slug from apps_list"),
+ "summary": str("One sentence: why you need this app."),
+ },
+ "required": []string{"app"},
+ },
+ },
+ }
+}
+
+func textResult(text string, isError bool) map[string]any {
+ return map[string]any{
+ "content": []map[string]any{{"type": "text", "text": text}},
+ "isError": isError,
+ }
+}
+
+func jsonResult(v any) map[string]any {
+ raw, err := json.MarshalIndent(v, "", " ")
+ if err != nil {
+ return textResult("failed to encode result", true)
+ }
+ text := string(raw)
+ if len(text) > maxResultBytes {
+ text = text[:maxResultBytes] + "\n…(truncated)"
+ }
+ return textResult(text, false)
+}
+
+func argString(args map[string]any, key string) string {
+ v, _ := args[key].(string)
+ return strings.TrimSpace(v)
+}
+
+func (s *Service) callTool(ctx context.Context, rn *run, name string, args map[string]any) map[string]any {
+ switch name {
+ case toolListApps:
+ return s.toolListApps(ctx, rn)
+ case toolSearchTools:
+ return s.toolSearch(ctx, rn, argString(args, "app"), argString(args, "query"))
+ case toolGetTool:
+ return s.toolGet(ctx, rn, argString(args, "tool"))
+ case toolRunTool:
+ toolArgs, _ := args["arguments"].(map[string]any)
+ if toolArgs == nil {
+ toolArgs = map[string]any{}
+ }
+ return s.toolRun(ctx, rn, argString(args, "tool"), toolArgs, argString(args, "summary"))
+ case toolRequestConnection:
+ return s.toolRequestConnection(ctx, rn, argString(args, "app"), argString(args, "summary"))
+ }
+ return textResult("unknown tool "+name, true)
+}
+
+func (s *Service) toolListApps(ctx context.Context, rn *run) map[string]any {
+ type appView struct {
+ App string `json:"app"`
+ Name string `json:"name"`
+ Account string `json:"account"`
+ Level string `json:"level"`
+ Status string `json:"status"`
+ }
+ out := []appView{}
+ for slug, app := range rn.apps {
+ status := "connected"
+ if _, err := s.resolveAccount(ctx, rn.workspaceID, rn.triggeredBy, slug, app.AccountScope); err != nil {
+ status = "not_connected"
+ }
+ out = append(out, appView{
+ App: slug, Name: runtimeapps.DisplayNameForToolkitSlug(slug),
+ Account: app.AccountScope, Level: app.Level, Status: status,
+ })
+ }
+ sort.Slice(out, func(i, j int) bool { return out[i].App < out[j].App })
+ return jsonResult(map[string]any{"apps": out})
+}
+
+// appForTool finds the agent app a tool slug belongs to by its prefix.
+func (rn *run) appForTool(tool string) (db.AgentApp, bool) {
+ upper := strings.ToUpper(tool)
+ best := ""
+ for slug := range rn.apps {
+ prefix := strings.ToUpper(slug) + "_"
+ if strings.HasPrefix(upper, prefix) && len(slug) > len(best) {
+ best = slug
+ }
+ }
+ app, ok := rn.apps[best]
+ return app, ok && best != ""
+}
+
+// policyFor returns the policy a call of class would get right now.
+func (s *Service) policyFor(ctx context.Context, rn *run, app db.AgentApp, class string) (string, account, error) {
+ slug := NormalizeSlug(app.ToolkitSlug)
+ acct, err := s.resolveAccount(ctx, rn.workspaceID, rn.triggeredBy, slug, app.AccountScope)
+ if err != nil {
+ return "", account{scope: app.AccountScope}, err
+ }
+ rule, err := s.accountRule(ctx, rn.workspaceID, slug, acct, class)
+ if err != nil {
+ return "", acct, err
+ }
+ return Decide(slug, app.Level, class, rule), acct, nil
+}
+
+func (s *Service) toolSearch(ctx context.Context, rn *run, slug, query string) map[string]any {
+ slug = NormalizeSlug(slug)
+ app, ok := rn.apps[slug]
+ if !ok {
+ return textResult(fmt.Sprintf("app %q is not available to you in this run; call apps_list", slug), true)
+ }
+ tools, err := s.composio.ListToolkitTools(ctx, slug)
+ if err != nil {
+ slog.Warn("connectedapps: list tools failed", "toolkit", slug, "error", err)
+ return textResult("could not load this app's tools right now; try again later", true)
+ }
+ terms := strings.Fields(strings.ToLower(query))
+ type hit struct {
+ Tool string `json:"tool"`
+ Description string `json:"description"`
+ Class string `json:"class"`
+ Policy string `json:"policy"`
+ score int
+ }
+ overrides := s.ClassOverrides(ctx, rn.workspaceID, slug)
+ policies := map[string]string{}
+ var hits []hit
+ for _, t := range tools {
+ hay := strings.ToLower(t.Slug + " " + t.Name + " " + t.Description)
+ score := 0
+ for _, term := range terms {
+ if strings.Contains(hay, term) {
+ score++
+ }
+ }
+ if len(terms) > 0 && score == 0 {
+ continue
+ }
+ class, ok := overrides[strings.ToUpper(t.Slug)]
+ if !ok {
+ class = Classify(slug, t.Slug, t.Tags)
+ }
+ policy, ok := policies[class]
+ if !ok {
+ policy, _, err = s.policyFor(ctx, rn, app, class)
+ if err != nil {
+ policy = "account_not_connected"
+ }
+ policies[class] = policy
+ }
+ desc := t.Description
+ if len(desc) > 220 {
+ desc = desc[:220] + "…"
+ }
+ hits = append(hits, hit{Tool: t.Slug, Description: desc, Class: class, Policy: policy, score: score})
+ }
+ sort.SliceStable(hits, func(i, j int) bool { return hits[i].score > hits[j].score })
+ if len(hits) > maxSearchResults {
+ hits = hits[:maxSearchResults]
+ }
+ return jsonResult(map[string]any{"app": slug, "tools": hits})
+}
+
+func (s *Service) toolGet(ctx context.Context, rn *run, toolSlug string) map[string]any {
+ app, ok := rn.appForTool(toolSlug)
+ if !ok {
+ return textResult("this tool does not belong to an app you can use in this run", true)
+ }
+ tool, err := s.composio.GetTool(ctx, app.ToolkitSlug, toolSlug)
+ if err != nil {
+ return textResult("tool not found", true)
+ }
+ class := s.classify(ctx, rn.workspaceID, app.ToolkitSlug, tool)
+ policy, _, err := s.policyFor(ctx, rn, app, class)
+ if err != nil {
+ policy = "account_not_connected"
+ }
+ return jsonResult(map[string]any{
+ "tool": tool.Slug,
+ "description": tool.Description,
+ "class": class,
+ "policy": policy,
+ "input_schema": tool.InputParameters,
+ })
+}
+
+func (s *Service) toolRun(ctx context.Context, rn *run, toolSlug string, args map[string]any, summary string) map[string]any {
+ app, ok := rn.appForTool(toolSlug)
+ if !ok {
+ return textResult("this tool does not belong to an app you can use in this run", true)
+ }
+ slug := NormalizeSlug(app.ToolkitSlug)
+ tool, err := s.composio.GetTool(ctx, slug, toolSlug)
+ if err != nil {
+ return textResult("tool not found", true)
+ }
+ class := ClassifyCall(s.classify(ctx, rn.workspaceID, slug, tool), tool.Slug, args)
+ call := toolCall{
+ workspaceID: rn.workspaceID, taskID: rn.task.ID, agentID: rn.agent.ID,
+ issueID: rn.task.IssueID, chatSessionID: rn.task.ChatSessionID, triggeredBy: rn.triggeredBy,
+ toolkit: slug, tool: tool.Slug, class: class,
+ }
+ policy, acct, err := s.policyFor(ctx, rn, app, class)
+ call.acct = acct
+ if err != nil {
+ if err == ErrAccountMissing {
+ return textResult(fmt.Sprintf("the %s account for %s is not connected. Call %s to ask for it, then end your turn.", app.AccountScope, slug, toolRequestConnection), true)
+ }
+ return textResult("could not resolve the account for this app", true)
+ }
+ switch policy {
+ case PolicyBlock:
+ call.outcome = "blocked"
+ first := s.firstBlock(ctx, call)
+ s.recordCall(ctx, call)
+ if first && rn.triggeredBy.Valid {
+ s.notify(ctx, db.AppActionRequest{
+ WorkspaceID: rn.workspaceID, Status: "blocked", Kind: KindAction,
+ TaskID: rn.task.ID, AgentID: rn.agent.ID, IssueID: rn.task.IssueID, ChatSessionID: rn.task.ChatSessionID,
+ ApproverUserID: rn.triggeredBy, AccountScope: app.AccountScope,
+ ToolkitSlug: slug, ToolSlug: tool.Slug, ActionClass: class,
+ }, NotifActionResult)
+ }
+ return textResult(fmt.Sprintf("blocked: %s calls (%s) are not allowed for you on %s. Do not work around this; tell the person what you would have done.", class, tool.Slug, slug), true)
+ case PolicyConfirm:
+ if !rn.triggeredBy.Valid {
+ call.outcome = "blocked"
+ s.recordCall(ctx, call)
+ return textResult("blocked: this call needs a person's confirmation, but no person triggered this run", true)
+ }
+ req, err := s.submit(ctx, rn, app, tool, class, args, summary)
+ if err != nil {
+ slog.Warn("connectedapps: submit request failed", "tool", tool.Slug, "error", err)
+ return textResult("could not submit this call for confirmation", true)
+ }
+ call.outcome, call.requestID = "pending", req.ID
+ s.recordCall(ctx, call)
+ return textResult(fmt.Sprintf("submitted: request %s is waiting for confirmation. End your turn now; you will be resumed with the result after the person decides. Do not call this tool again for the same action.", util.UUIDToString(req.ID)), false)
+ }
+ if s.overLimit(ctx, rn.workspaceID, slug, acct) {
+ call.outcome = "rate_limited"
+ s.recordCall(ctx, call)
+ return textResult(fmt.Sprintf("rate limited: this %s account already ran %d calls in the last minute. Wait a minute before the next call, and batch work where the app allows it.", slug, s.perMinute), true)
+ }
+ resp, err := s.composio.ExecuteTool(ctx, acct.connectedAccountID, *tool, args)
+ s.touch(ctx, rn.workspaceID, acct)
+ if err != nil {
+ call.outcome, call.err = "error", truncate(err.Error(), 500)
+ s.recordCall(ctx, call)
+ return textResult("the app call failed: "+truncate(err.Error(), 500), true)
+ }
+ if !resp.Successful {
+ call.outcome, call.err = "error", truncate(resp.Error, 500)
+ s.recordCall(ctx, call)
+ return textResult("the app returned an error: "+truncate(resp.Error, 2000), true)
+ }
+ call.outcome = "ok"
+ s.recordCall(ctx, call)
+ return jsonResult(resp.Data)
+}
+
+func (s *Service) toolRequestConnection(ctx context.Context, rn *run, slug, summary string) map[string]any {
+ slug = NormalizeSlug(slug)
+ app, ok := rn.apps[slug]
+ if !ok {
+ return textResult(fmt.Sprintf("app %q is not available to you in this run", slug), true)
+ }
+ if _, err := s.resolveAccount(ctx, rn.workspaceID, rn.triggeredBy, slug, app.AccountScope); err == nil {
+ return textResult("the account is already connected; use the app directly", false)
+ }
+ if app.AccountScope == ScopeTeam {
+ return textResult("this app uses the team account, which a workspace admin connects in Settings › Apps. Tell the person in your reply and end your turn.", true)
+ }
+ if !rn.triggeredBy.Valid {
+ return textResult("no person triggered this run, so nobody can be asked to connect an account", true)
+ }
+ req, err := s.createRequest(ctx, rn, "connect", app, "", "", map[string]any{}, summary)
+ if err != nil {
+ return textResult("could not send the connection request", true)
+ }
+ return textResult(fmt.Sprintf("requested: %s is asked to connect %s (request %s). End your turn now; you will be resumed after they connect.", "the person who triggered this run", slug, util.UUIDToString(req.ID)), false)
+}
+
+func truncate(s string, n int) string {
+ if len(s) <= n {
+ return s
+ }
+ return s[:n] + "…"
+}
diff --git a/server/internal/connectedapps/policy.go b/server/internal/connectedapps/policy.go
new file mode 100644
index 0000000000..13fc6e9230
--- /dev/null
+++ b/server/internal/connectedapps/policy.go
@@ -0,0 +1,81 @@
+package connectedapps
+
+// Policies a rule can set for an action class.
+const (
+ PolicyAllow = "allow"
+ PolicyConfirm = "confirm"
+ PolicyBlock = "block"
+)
+
+// ValidPolicy reports whether policy is a rule policy.
+func ValidPolicy(policy string) bool {
+ return policy == PolicyAllow || policy == PolicyConfirm || policy == PolicyBlock
+}
+
+var defaultPolicies = map[string]string{
+ ClassRead: PolicyAllow,
+ ClassWrite: PolicyAllow,
+ ClassSend: PolicyConfirm,
+ ClassDelete: PolicyConfirm,
+ ClassShare: PolicyBlock,
+}
+
+func strictness(policy string) int {
+ switch policy {
+ case PolicyAllow:
+ return 0
+ case PolicyConfirm:
+ return 1
+ default:
+ return 2
+ }
+}
+
+// Stricter returns the stricter of two policies.
+func Stricter(a, b string) string {
+ if strictness(a) >= strictness(b) {
+ return a
+ }
+ return b
+}
+
+// DefaultPolicy is the policy an account uses for class when it has no rule:
+// the curated app's default, else the workspace default.
+func DefaultPolicy(toolkitSlug, class string) string {
+ if app, ok := Curated(toolkitSlug); ok {
+ if p, ok := app.Defaults[class]; ok {
+ return p
+ }
+ }
+ if p, ok := defaultPolicies[class]; ok {
+ return p
+ }
+ return PolicyConfirm
+}
+
+// levelCap is the loosest policy an agent level permits for class.
+func levelCap(level, class string) string {
+ if class == ClassRead {
+ return PolicyAllow
+ }
+ switch level {
+ case LevelRead:
+ return PolicyBlock
+ case LevelWrite:
+ return PolicyAllow
+ default:
+ return PolicyConfirm
+ }
+}
+
+// Decide returns the policy for one call. rule is the account's rule for the
+// class ("" when unset). The account's rule (or default) and the agent's level
+// both apply; the stricter one wins, so an agent setting can only tighten what
+// the account owner allows and never loosen it.
+func Decide(toolkitSlug, level, class, rule string) string {
+ account := rule
+ if !ValidPolicy(account) {
+ account = DefaultPolicy(toolkitSlug, class)
+ }
+ return Stricter(account, levelCap(level, class))
+}
diff --git a/server/internal/connectedapps/policy_test.go b/server/internal/connectedapps/policy_test.go
new file mode 100644
index 0000000000..a86694543c
--- /dev/null
+++ b/server/internal/connectedapps/policy_test.go
@@ -0,0 +1,157 @@
+package connectedapps
+
+import (
+ "testing"
+ "time"
+)
+
+func TestClassify(t *testing.T) {
+ cases := []struct {
+ toolkit, tool string
+ tags []string
+ want string
+ }{
+ {"gmail", "GMAIL_FETCH_EMAILS", nil, ClassRead},
+ {"gmail", "GMAIL_FETCH_MESSAGE_BY_THREAD_ID", nil, ClassRead},
+ {"gmail", "GMAIL_CREATE_EMAIL_DRAFT", nil, ClassWrite},
+ {"gmail", "GMAIL_SEND_EMAIL", nil, ClassSend},
+ {"gmail", "GMAIL_REPLY_TO_THREAD", nil, ClassSend},
+ {"gmail", "GMAIL_MOVE_TO_TRASH", nil, ClassDelete},
+ {"slack", "SLACK_CHAT_POST_MESSAGE", nil, ClassSend},
+ {"slack", "SLACK_LIST_ALL_CHANNELS", nil, ClassRead},
+ {"notion", "NOTION_ADD_PAGE_CONTENT", nil, ClassWrite},
+ {"notion", "NOTION_DELETE_BLOCK", nil, ClassDelete},
+ {"googledrive", "GOOGLEDRIVE_ADD_FILE_SHARING_PREFERENCE", nil, ClassShare},
+ {"googledrive", "GOOGLEDRIVE_LIST_PERMISSIONS", nil, ClassRead},
+ {"googledrive", "GOOGLEDRIVE_SHARE_FILE", nil, ClassShare},
+ {"googlecalendar", "GOOGLECALENDAR_CREATE_EVENT", nil, ClassSend},
+ {"googlecalendar", "GOOGLECALENDAR_FIND_FREE_SLOTS", nil, ClassRead},
+ {"linear", "LINEAR_CREATE_LINEAR_ISSUE", nil, ClassWrite},
+ {"someapp", "SOMEAPP_FROBNICATE", nil, ClassSend},
+ {"someapp", "SOMEAPP_FROBNICATE", []string{"readOnlyHint"}, ClassRead},
+ {"someapp", "SOMEAPP_FROBNICATE", []string{"destructiveHint"}, ClassDelete},
+ }
+ for _, c := range cases {
+ if got := Classify(c.toolkit, c.tool, c.tags); got != c.want {
+ t.Errorf("Classify(%s, %s) = %s, want %s", c.toolkit, c.tool, got, c.want)
+ }
+ }
+}
+
+func TestDecide(t *testing.T) {
+ cases := []struct {
+ toolkit, level, class, rule, want string
+ }{
+ // Defaults under the most permissive level.
+ {"notion", LevelWrite, ClassRead, "", PolicyAllow},
+ {"notion", LevelWrite, ClassWrite, "", PolicyAllow},
+ {"notion", LevelWrite, ClassSend, "", PolicyConfirm},
+ {"notion", LevelWrite, ClassDelete, "", PolicyConfirm},
+ {"notion", LevelWrite, ClassShare, "", PolicyBlock},
+ // The default level confirms every write.
+ {"notion", LevelConfirmWrites, ClassWrite, "", PolicyConfirm},
+ {"notion", LevelConfirmWrites, ClassRead, "", PolicyAllow},
+ // Read-only agents never write, whatever the rule says.
+ {"notion", LevelRead, ClassWrite, PolicyAllow, PolicyBlock},
+ {"notion", LevelRead, ClassRead, "", PolicyAllow},
+ // A rule loosens or tightens the account; the level still caps it.
+ {"gmail", LevelWrite, ClassSend, PolicyAllow, PolicyAllow},
+ {"gmail", LevelConfirmWrites, ClassSend, PolicyAllow, PolicyConfirm},
+ {"gmail", LevelWrite, ClassRead, PolicyBlock, PolicyBlock},
+ // Curated defaults: Stripe is read-only unless a rule opens it.
+ {"stripe", LevelWrite, ClassWrite, "", PolicyBlock},
+ {"stripe", LevelWrite, ClassWrite, PolicyConfirm, PolicyConfirm},
+ // An unknown rule value falls back to the default.
+ {"notion", LevelWrite, ClassShare, "bogus", PolicyBlock},
+ }
+ for _, c := range cases {
+ if got := Decide(c.toolkit, c.level, c.class, c.rule); got != c.want {
+ t.Errorf("Decide(%s, %s, %s, %q) = %s, want %s", c.toolkit, c.level, c.class, c.rule, got, c.want)
+ }
+ }
+}
+
+func TestTaskToken(t *testing.T) {
+ secret := DeriveTokenSecret([]byte("service-secret"))
+ now := time.Unix(1_800_000_000, 0)
+ token, err := SignTaskToken(secret, "task-1", now.Add(time.Hour))
+ if err != nil {
+ t.Fatal(err)
+ }
+ got, err := VerifyTaskToken(secret, token, now)
+ if err != nil || got != "task-1" {
+ t.Fatalf("verify = %q, %v", got, err)
+ }
+ if _, err := VerifyTaskToken(secret, token, now.Add(2*time.Hour)); err != ErrTokenExpired {
+ t.Fatalf("expired token: %v", err)
+ }
+ if _, err := VerifyTaskToken(DeriveTokenSecret([]byte("other")), token, now); err != ErrTokenSignature {
+ t.Fatalf("foreign secret: %v", err)
+ }
+ if _, err := VerifyTaskToken(secret, token[:len(token)-2]+"xx", now); err != ErrTokenSignature {
+ t.Fatalf("tampered token: %v", err)
+ }
+ if _, err := VerifyTaskToken(secret, "Bearer "+token, now); err != ErrTokenMalformed {
+ t.Fatalf("unprefixed token: %v", err)
+ }
+}
+
+func TestDefaultLevel(t *testing.T) {
+ if got := DefaultLevel("private"); got != LevelWrite {
+ t.Fatalf("private agent default = %q, want %q", got, LevelWrite)
+ }
+ for _, mode := range []string{"public_to", ""} {
+ if got := DefaultLevel(mode); got != LevelConfirmWrites {
+ t.Fatalf("%q agent default = %q, want %q", mode, got, LevelConfirmWrites)
+ }
+ }
+}
+
+func TestClassifyOutwardWrites(t *testing.T) {
+ for _, tc := range []struct{ app, tool, want string }{
+ {"slack", "SLACK_SCHEDULE_MESSAGE", ClassSend},
+ {"slack", "SLACK_UPDATE_MESSAGE", ClassSend},
+ {"slack", "SLACK_SET_ADMIN_USER", ClassShare},
+ {"slack", "SLACK_SET_USER_ROLE", ClassShare},
+ {"outlook", "OUTLOOK_CALENDAR_CREATE_EVENT", ClassSend},
+ {"outlook", "OUTLOOK_CREATE_A_NEW_EVENT", ClassSend},
+ {"gmail", "GMAIL_CREATE_EMAIL_DRAFT", ClassWrite},
+ {"gmail", "GMAIL_ADD_LABEL_TO_EMAIL", ClassWrite},
+ {"notion", "NOTION_CREATE_PAGE", ClassWrite},
+ } {
+ if got := Classify(tc.app, tc.tool, nil); got != tc.want {
+ t.Errorf("Classify(%s) = %s, want %s", tc.tool, got, tc.want)
+ }
+ }
+ if got := Decide("slack", LevelWrite, Classify("slack", "SLACK_SET_ADMIN_USER", nil), ""); got != PolicyBlock {
+ t.Errorf("SLACK_SET_ADMIN_USER at write level = %s, want block", got)
+ }
+}
+
+func TestClassifyCallArguments(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ class string
+ tool string
+ args map[string]any
+ want string
+ }{
+ {"attendees make an event a send", ClassWrite, "ZOOM_UPDATE_SCHEDULE", map[string]any{"attendees": []any{"[email protected]"}}, ClassSend},
+ {"empty recipients stay a write", ClassWrite, "TODOIST_UPDATE_TASK", map[string]any{"to": "", "attendees": []any{}}, ClassWrite},
+ {"notify flag", ClassWrite, "ASANA_UPDATE_TASK", map[string]any{"send_notifications": true}, ClassSend},
+ {"notify none", ClassWrite, "GOOGLECALENDAR_UPDATE_EVENT", map[string]any{"send_updates": "none"}, ClassWrite},
+ {"drafts reach nobody", ClassWrite, "GMAIL_CREATE_EMAIL_DRAFT", map[string]any{"to": "[email protected]"}, ClassWrite},
+ {"reads stay reads", ClassRead, "GMAIL_FETCH_EMAILS", map[string]any{"to": "[email protected]"}, ClassRead},
+ {"a delete is not softened", ClassDelete, "GMAIL_DELETE_MESSAGE", map[string]any{"to": "[email protected]"}, ClassDelete},
+ {"archiving a page is a delete", ClassWrite, "NOTION_UPDATE_PAGE", map[string]any{"page_id": "p", "archived": true}, ClassDelete},
+ {"moving a page to trash", ClassWrite, "NOTION_UPDATE_PAGE", map[string]any{"in_trash": "true"}, ClassDelete},
+ {"trashing a file", ClassWrite, "GOOGLEDRIVE_EDIT_FILE", map[string]any{"trashed": 1.0}, ClassDelete},
+ {"restoring a page stays a write", ClassWrite, "NOTION_UPDATE_PAGE", map[string]any{"archived": false}, ClassWrite},
+ {"editing a page stays a write", ClassWrite, "NOTION_UPDATE_PAGE", map[string]any{"properties": map[string]any{"archived": true}}, ClassWrite},
+ {"trashing a draft is a delete", ClassWrite, "GMAIL_UPDATE_DRAFT", map[string]any{"trashed": true}, ClassDelete},
+ } {
+ if got := ClassifyCall(tc.class, tc.tool, tc.args); got != tc.want {
+ t.Errorf("%s: ClassifyCall = %s, want %s", tc.name, got, tc.want)
+ }
+ }
+}
diff --git a/server/internal/connectedapps/requests.go b/server/internal/connectedapps/requests.go
new file mode 100644
index 0000000000..e82bbfc3aa
--- /dev/null
+++ b/server/internal/connectedapps/requests.go
@@ -0,0 +1,523 @@
+package connectedapps
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "log/slog"
+ "strings"
+ "time"
+
+ "github.com/jackc/pgx/v5/pgtype"
+ "github.com/multica-ai/multica/server/internal/events"
+ "github.com/multica-ai/multica/server/internal/inbox"
+ "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"
+ "github.com/multica-ai/multica/server/pkg/dbid"
+)
+
+// EventRequestChanged tells clients to refetch the requests of an issue or
+// chat. The payload carries ids and status only; the request body is read
+// through the authorized API.
+const EventRequestChanged = "app_request:changed"
+
+// EventCallCreated tells clients an issue's runs made another app call, so
+// its call chips and sidebar refetch.
+const EventCallCreated = "app_call:created"
+
+// Inbox notification types.
+const (
+ NotifActionRequested = "app_action_requested"
+ NotifActionReminder = "app_action_reminder"
+ NotifConnectRequested = "app_connect_requested"
+ NotifActionResult = "app_action_result"
+)
+
+// Request kinds.
+const (
+ KindAction = "action"
+ KindConnect = "connect"
+)
+
+func (s *Service) submit(ctx context.Context, rn *run, app db.AgentApp, tool *sdk.Tool, class string, args map[string]any, summary string) (db.AppActionRequest, error) {
+ return s.createRequest(ctx, rn, KindAction, app, tool.Slug, class, args, summary)
+}
+
+func (s *Service) createRequest(ctx context.Context, rn *run, kind string, app db.AgentApp, toolSlug, class string, args map[string]any, summary string) (db.AppActionRequest, error) {
+ raw, err := json.Marshal(args)
+ if err != nil {
+ return db.AppActionRequest{}, err
+ }
+ slug := NormalizeSlug(app.ToolkitSlug)
+ if existing, err := s.q.FindPendingAppActionRequest(ctx, db.FindPendingAppActionRequestParams{
+ TaskID: rn.task.ID, Kind: kind, ToolkitSlug: slug, ToolSlug: toolSlug, Arguments: raw,
+ }); err == nil {
+ return existing, nil
+ } else if !isNoRows(err) {
+ return db.AppActionRequest{}, err
+ }
+ if class == "" {
+ class = ClassSend
+ }
+ req, err := s.q.CreateAppActionRequest(ctx, db.CreateAppActionRequestParams{
+ WorkspaceID: rn.workspaceID,
+ Kind: kind,
+ TaskID: rn.task.ID,
+ AgentID: rn.agent.ID,
+ IssueID: rn.task.IssueID,
+ ChatSessionID: rn.task.ChatSessionID,
+ ApproverUserID: rn.triggeredBy,
+ AccountScope: app.AccountScope,
+ ToolkitSlug: slug,
+ ToolSlug: toolSlug,
+ ActionClass: class,
+ Arguments: raw,
+ Summary: truncate(summary, 500),
+ ExpiresAt: pgtype.Timestamptz{Time: s.now().Add(requestTTL(kind)), Valid: true},
+ })
+ if err != nil {
+ return db.AppActionRequest{}, err
+ }
+ notif := NotifActionRequested
+ if kind == KindConnect {
+ notif = NotifConnectRequested
+ }
+ s.notify(ctx, req, notif)
+ s.publishChange(req)
+ return req, nil
+}
+
+// Approve executes an approved request with args (nil keeps the agent's) and
+// resumes the agent with the outcome. Only the approver may approve.
+func (s *Service) Approve(ctx context.Context, workspaceID, actorID, requestID pgtype.UUID, args map[string]any) (db.AppActionRequest, error) {
+ req, err := s.pendingForApprover(ctx, workspaceID, actorID, requestID)
+ if err != nil {
+ return db.AppActionRequest{}, err
+ }
+ if !s.mayAct(ctx, req) {
+ s.withdraw(ctx, req)
+ return db.AppActionRequest{}, ErrNoLongerAllowed
+ }
+ if req.Kind == KindConnect {
+ if _, err := s.resolveAccount(ctx, workspaceID, actorID, req.ToolkitSlug, req.AccountScope); err != nil {
+ return db.AppActionRequest{}, ErrAccountMissing
+ }
+ } else if acct, err := s.resolveAccount(ctx, workspaceID, actorID, req.ToolkitSlug, req.AccountScope); err == nil &&
+ s.overLimit(ctx, workspaceID, req.ToolkitSlug, acct) {
+ // Checked before deciding, so the request stays pending and retryable.
+ return db.AppActionRequest{}, ErrRateLimited
+ }
+ approvedArgs := req.Arguments
+ if args != nil && req.Kind == KindAction {
+ if approvedArgs, err = json.Marshal(args); err != nil {
+ return db.AppActionRequest{}, err
+ }
+ }
+ decided, err := s.q.DecideAppActionRequest(ctx, db.DecideAppActionRequestParams{
+ ID: requestID, WorkspaceID: workspaceID, Status: "approved", DecidedBy: actorID,
+ ApprovedArguments: approvedArgs,
+ })
+ if isNoRows(err) {
+ return db.AppActionRequest{}, ErrNotPending
+ }
+ if err != nil {
+ return db.AppActionRequest{}, err
+ }
+ if decided.Kind == KindConnect {
+ s.publishChange(decided)
+ s.resume(ctx, decided, actorID, fmt.Sprintf(
+ "The %s account you asked for (request %s) is now connected. Continue the task and use the app.",
+ appLabel(decided.ToolkitSlug), util.UUIDToString(decided.ID)))
+ return decided, nil
+ }
+
+ final, note := s.executeApproved(ctx, decided)
+ s.publishChange(final)
+ s.resume(ctx, final, actorID, note)
+ return final, nil
+}
+
+// ResolveConnectRequests completes the connection requests a member was
+// asked to answer for slug, once they connected it, and resumes each agent.
+// It runs from the OAuth callback, so nobody has to come back and confirm.
+func (s *Service) ResolveConnectRequests(ctx context.Context, userID pgtype.UUID, slug string) {
+ rows, err := s.q.ListPendingConnectRequestsForUser(ctx, db.ListPendingConnectRequestsForUserParams{
+ ApproverUserID: userID, ToolkitSlug: NormalizeSlug(slug),
+ })
+ if err != nil {
+ slog.Warn("connectedapps: list connect requests failed", "toolkit", slug, "error", err)
+ return
+ }
+ for _, r := range rows {
+ if _, err := s.Approve(ctx, r.WorkspaceID, userID, r.ID, nil); err != nil &&
+ !errors.Is(err, ErrNotPending) && !errors.Is(err, ErrNoLongerAllowed) {
+ slog.Warn("connectedapps: resolve connect request failed", "request_id", util.UUIDToString(r.ID), "error", err)
+ }
+ }
+}
+
+// Reject declines a request and resumes the agent so it can adapt.
+func (s *Service) Reject(ctx context.Context, workspaceID, actorID, requestID pgtype.UUID, reason string) (db.AppActionRequest, error) {
+ if _, err := s.pendingForApprover(ctx, workspaceID, actorID, requestID); err != nil {
+ return db.AppActionRequest{}, err
+ }
+ reason = truncate(strings.TrimSpace(reason), 1000)
+ decided, err := s.q.DecideAppActionRequest(ctx, db.DecideAppActionRequestParams{
+ ID: requestID, WorkspaceID: workspaceID, Status: "rejected", DecidedBy: actorID,
+ Reason: pgtype.Text{String: reason, Valid: reason != ""},
+ })
+ if isNoRows(err) {
+ return db.AppActionRequest{}, ErrNotPending
+ }
+ if err != nil {
+ return db.AppActionRequest{}, err
+ }
+ if decided.Kind == KindAction {
+ s.recordCall(ctx, toolCall{
+ workspaceID: decided.WorkspaceID, taskID: decided.TaskID, agentID: decided.AgentID,
+ issueID: decided.IssueID, chatSessionID: decided.ChatSessionID, triggeredBy: decided.ApproverUserID,
+ acct: account{scope: decided.AccountScope, owner: personalOwner(decided)},
+ toolkit: decided.ToolkitSlug, tool: decided.ToolSlug, class: decided.ActionClass,
+ outcome: "rejected", requestID: decided.ID,
+ })
+ }
+ s.publishChange(decided)
+ note := fmt.Sprintf("The person declined your %s request %s (%s).", appLabel(decided.ToolkitSlug), util.UUIDToString(decided.ID), decided.ToolSlug)
+ if decided.Kind == KindConnect {
+ note = fmt.Sprintf("The person declined to connect %s (request %s).", appLabel(decided.ToolkitSlug), util.UUIDToString(decided.ID))
+ }
+ if reason != "" {
+ note += " Their reason: " + reason
+ }
+ note += " Do not retry the same call. Continue without it, or adjust your plan and explain in your reply."
+ s.resume(ctx, decided, actorID, note)
+ return decided, nil
+}
+
+func (s *Service) pendingForApprover(ctx context.Context, workspaceID, actorID, requestID pgtype.UUID) (db.AppActionRequest, error) {
+ req, err := s.q.GetAppActionRequest(ctx, db.GetAppActionRequestParams{ID: requestID, WorkspaceID: workspaceID})
+ if err != nil {
+ return db.AppActionRequest{}, ErrRequestNotFound
+ }
+ if req.ApproverUserID != actorID {
+ return db.AppActionRequest{}, ErrNotApprover
+ }
+ if req.Status != "pending" {
+ return db.AppActionRequest{}, ErrNotPending
+ }
+ return req, nil
+}
+
+func personalOwner(req db.AppActionRequest) pgtype.UUID {
+ if req.AccountScope == ScopePersonal {
+ return req.ApproverUserID
+ }
+ return pgtype.UUID{}
+}
+
+// executeApproved runs an approved request. The agent's app, the account and
+// the rules are checked again: anything that changed while the request waited
+// and now forbids the call fails the request instead of running it.
+func (s *Service) executeApproved(ctx context.Context, req db.AppActionRequest) (db.AppActionRequest, string) {
+ label := fmt.Sprintf("%s request %s (%s)", appLabel(req.ToolkitSlug), util.UUIDToString(req.ID), req.ToolSlug)
+ call := toolCall{
+ workspaceID: req.WorkspaceID, taskID: req.TaskID, agentID: req.AgentID,
+ issueID: req.IssueID, chatSessionID: req.ChatSessionID, triggeredBy: req.ApproverUserID,
+ acct: account{scope: req.AccountScope, owner: personalOwner(req)},
+ toolkit: req.ToolkitSlug, tool: req.ToolSlug, class: req.ActionClass, requestID: req.ID,
+ }
+ fail := func(msg string) (db.AppActionRequest, string) {
+ call.outcome, call.err = "error", truncate(msg, 500)
+ s.recordCall(ctx, call)
+ row, err := s.q.SetAppActionRequestOutcome(ctx, db.SetAppActionRequestOutcomeParams{
+ ID: req.ID, WorkspaceID: req.WorkspaceID, Status: "failed",
+ Error: pgtype.Text{String: truncate(msg, 2000), Valid: true},
+ })
+ if err != nil {
+ row = req
+ }
+ return row, fmt.Sprintf("Your %s was approved, but running it failed: %s. Decide how to continue; do not resubmit the same call unless the failure was transient.", label, msg)
+ }
+
+ app, ok := s.agentApp(ctx, req.AgentID, req.ToolkitSlug)
+ if !ok {
+ return fail("the app is no longer attached to the agent")
+ }
+ if !s.Catalog(ctx, req.WorkspaceID).Allows(req.ToolkitSlug) {
+ return fail("the workspace no longer allows this app")
+ }
+ acct, err := s.resolveAccount(ctx, req.WorkspaceID, req.ApproverUserID, req.ToolkitSlug, req.AccountScope)
+ if err != nil {
+ return fail("the account is no longer connected")
+ }
+ call.acct = acct
+ tool, err := s.composio.GetTool(ctx, req.ToolkitSlug, req.ToolSlug)
+ if err != nil {
+ return fail("the tool could not be loaded")
+ }
+ var args map[string]any
+ if err := json.Unmarshal(req.ApprovedArguments, &args); err != nil {
+ return fail("the approved arguments are invalid")
+ }
+ class := ClassifyCall(s.classify(ctx, req.WorkspaceID, req.ToolkitSlug, tool), tool.Slug, args)
+ rule, err := s.accountRule(ctx, req.WorkspaceID, req.ToolkitSlug, acct, class)
+ if err != nil {
+ return fail("the rules could not be read")
+ }
+ if Decide(req.ToolkitSlug, app.Level, class, rule) == PolicyBlock {
+ return fail("a rule now blocks this call")
+ }
+ resp, err := s.composio.ExecuteTool(ctx, acct.connectedAccountID, *tool, args)
+ s.touch(ctx, req.WorkspaceID, acct)
+ if err != nil {
+ return fail(truncate(err.Error(), 500))
+ }
+ if !resp.Successful {
+ return fail(truncate(resp.Error, 500))
+ }
+ result, err := json.Marshal(resp.Data)
+ if err != nil || len(result) > maxResultBytes {
+ result = []byte(`{"truncated":true}`)
+ }
+ call.outcome = "approved"
+ s.recordCall(ctx, call)
+ row, err := s.q.SetAppActionRequestOutcome(ctx, db.SetAppActionRequestOutcomeParams{
+ ID: req.ID, WorkspaceID: req.WorkspaceID, Status: "approved", Result: result,
+ })
+ if err != nil {
+ row = req
+ }
+ edited := ""
+ if string(req.ApprovedArguments) != string(req.Arguments) {
+ edited = " The person edited the arguments before approving; the result reflects their version."
+ }
+ return row, fmt.Sprintf("Your %s was approved and Multica ran it.%s Result:\n```json\n%s\n```\nContinue the task from here. Do not call the tool again for this request.", label, edited, string(result))
+}
+
+func (s *Service) agentApp(ctx context.Context, agentID pgtype.UUID, slug string) (db.AgentApp, bool) {
+ apps, err := s.q.ListAgentApps(ctx, agentID)
+ if err != nil {
+ return db.AgentApp{}, false
+ }
+ for _, app := range apps {
+ if NormalizeSlug(app.ToolkitSlug) == NormalizeSlug(slug) {
+ return app, true
+ }
+ }
+ return db.AgentApp{}, false
+}
+
+// mayAct reports whether the approver is still a member who may run the
+// agent. Membership and agent access can change while a request waits.
+func (s *Service) mayAct(ctx context.Context, req db.AppActionRequest) bool {
+ if _, err := s.q.GetMemberByUserAndWorkspace(ctx, db.GetMemberByUserAndWorkspaceParams{
+ UserID: req.ApproverUserID, WorkspaceID: req.WorkspaceID,
+ }); err != nil {
+ return false
+ }
+ return s.resumer == nil || s.resumer.CanActFor(ctx, req.WorkspaceID, req.AgentID, req.ApproverUserID)
+}
+
+func (s *Service) withdraw(ctx context.Context, req db.AppActionRequest) {
+ row, err := s.q.CancelAppActionRequest(ctx, db.CancelAppActionRequestParams{ID: req.ID, WorkspaceID: req.WorkspaceID})
+ if err != nil {
+ return
+ }
+ s.publishChange(row)
+}
+
+func (s *Service) resume(ctx context.Context, req db.AppActionRequest, actorID pgtype.UUID, note string) {
+ if s.resumer == nil {
+ return
+ }
+ if !s.mayAct(ctx, req) {
+ slog.Info("connectedapps: approver can no longer run the agent; not resuming", "request_id", util.UUIDToString(req.ID))
+ return
+ }
+ if err := s.resumer.ResumeAfterDecision(ctx, req, actorID, note); err != nil {
+ slog.Warn("connectedapps: resume agent failed", "request_id", util.UUIDToString(req.ID), "error", err)
+ }
+}
+
+// CancelTeamRequests cancels what was waiting on a team account that was
+// just disconnected. The agents are not resumed.
+func (s *Service) CancelTeamRequests(ctx context.Context, workspaceID pgtype.UUID, slug string) {
+ rows, err := s.q.CancelPendingTeamAppActionRequests(ctx, db.CancelPendingTeamAppActionRequestsParams{WorkspaceID: workspaceID, ToolkitSlug: slug})
+ if err != nil {
+ slog.Warn("connectedapps: cancel team requests failed", "toolkit", slug, "error", err)
+ return
+ }
+ for _, r := range rows {
+ s.publishChange(r)
+ }
+}
+
+// Sweep expires requests past their deadline and reminds approvers two hours
+// before. Expiry does not resume the agent: the run already ended, and
+// nothing happened. The approver gets a result notification instead.
+func (s *Service) Sweep(ctx context.Context) {
+ expired, err := s.q.ExpireDueAppActionRequests(ctx)
+ if err != nil {
+ slog.Warn("connectedapps: expire requests failed", "error", err)
+ }
+ for _, r := range expired {
+ s.publishChange(r)
+ s.notify(ctx, r, NotifActionResult)
+ }
+ due, err := s.q.ClaimAppActionRequestReminders(ctx)
+ if err != nil {
+ slog.Warn("connectedapps: claim reminders failed", "error", err)
+ }
+ for _, r := range due {
+ s.notify(ctx, r, NotifActionReminder)
+ }
+}
+
+func (s *Service) publishChange(req db.AppActionRequest) {
+ if s.bus == nil {
+ return
+ }
+ e := events.Event{
+ Type: EventRequestChanged,
+ WorkspaceID: util.UUIDToString(req.WorkspaceID),
+ ActorType: "system",
+ Payload: map[string]any{
+ "request_id": util.UUIDToString(req.ID),
+ "issue_id": util.UUIDToPtr(req.IssueID),
+ "chat_session_id": util.UUIDToPtr(req.ChatSessionID),
+ "status": req.Status,
+ },
+ }
+ if !req.IssueID.Valid {
+ e.MemberPrivateUserID = util.UUIDToString(req.ApproverUserID)
+ }
+ s.bus.Publish(e)
+}
+
+func appLabel(slug string) string {
+ if name := runtimeapps.DisplayNameForToolkitSlug(slug); name != "" {
+ return name
+ }
+ return slug
+}
+
+// notify writes the approver's inbox item. Confirmation and connection
+// requests are always delivered: the agent is stopped until the person
+// answers. Results follow the recipient's agent-activity preference.
+func (s *Service) notify(ctx context.Context, req db.AppActionRequest, notifType string) {
+ if notifType == NotifActionResult && s.mutedAgentActivity(ctx, req) {
+ return
+ }
+ actorType := pgtype.Text{String: "agent", Valid: true}
+ agentName := "Agent"
+ if agent, err := s.q.GetAgent(ctx, req.AgentID); err == nil {
+ agentName = agent.Name
+ }
+ title, issueStatus := agentName, ""
+ if req.IssueID.Valid {
+ if issue, err := s.q.GetIssue(ctx, req.IssueID); err == nil {
+ title, issueStatus = issue.Title, issue.Status
+ }
+ } else if req.ChatSessionID.Valid {
+ if chat, err := s.q.GetChatSession(ctx, req.ChatSessionID); err == nil && chat.Title != "" {
+ title = chat.Title
+ }
+ }
+ var body string
+ severity := "action_required"
+ switch notifType {
+ case NotifActionResult:
+ severity = "info"
+ switch {
+ case req.Status == "blocked":
+ body = fmt.Sprintf("A rule blocked %s from running %s · %s", agentName, appLabel(req.ToolkitSlug), req.ToolSlug)
+ case req.Kind == KindConnect:
+ body = fmt.Sprintf("%s's request to connect %s expired without an answer", agentName, appLabel(req.ToolkitSlug))
+ default:
+ body = fmt.Sprintf("%s's request to run %s · %s expired without an answer", agentName, appLabel(req.ToolkitSlug), req.ToolSlug)
+ }
+ case NotifConnectRequested:
+ body = fmt.Sprintf("%s asks you to connect %s", agentName, appLabel(req.ToolkitSlug))
+ case NotifActionReminder:
+ body = fmt.Sprintf("%s is still waiting for your confirmation on %s · %s; it expires in 2 hours", agentName, appLabel(req.ToolkitSlug), req.ToolSlug)
+ default:
+ body = fmt.Sprintf("%s wants to run %s · %s", agentName, appLabel(req.ToolkitSlug), req.ToolSlug)
+ }
+ details, _ := json.Marshal(map[string]any{
+ "request_id": util.UUIDToPtr(req.ID),
+ "task_id": util.UUIDToPtr(req.TaskID),
+ "status": req.Status,
+ "kind": req.Kind,
+ "toolkit_slug": req.ToolkitSlug,
+ "tool_slug": req.ToolSlug,
+ "action_class": req.ActionClass,
+ "agent_id": util.UUIDToString(req.AgentID),
+ "chat_session_id": util.UUIDToPtr(req.ChatSessionID),
+ "summary": req.Summary,
+ "expires_at": util.TimestampToString(req.ExpiresAt),
+ })
+ item, inserted, err := inbox.CreateIfEligible(ctx, s.q, db.CreateInboxItemParams{
+ ID: dbid.NewV7(),
+ WorkspaceID: req.WorkspaceID,
+ RecipientType: "member",
+ RecipientID: req.ApproverUserID,
+ Type: notifType,
+ Severity: severity,
+ IssueID: req.IssueID,
+ Title: title,
+ Body: pgtype.Text{String: body, Valid: true},
+ ActorType: actorType,
+ ActorID: req.AgentID,
+ Details: details,
+ })
+ if err != nil {
+ slog.Warn("connectedapps: create inbox item failed", "request_id", util.UUIDToString(req.ID), "error", err)
+ return
+ }
+ if !inserted || s.bus == nil {
+ return
+ }
+ s.bus.Publish(events.Event{
+ Type: "inbox:new", WorkspaceID: util.UUIDToString(item.WorkspaceID), ActorType: "agent", ActorID: util.UUIDToString(req.AgentID),
+ Payload: map[string]any{"item": map[string]any{
+ "id": util.UUIDToString(item.ID), "workspace_id": util.UUIDToString(item.WorkspaceID),
+ "recipient_type": item.RecipientType, "recipient_id": util.UUIDToString(item.RecipientID),
+ "type": item.Type, "severity": item.Severity, "issue_id": util.UUIDToPtr(item.IssueID),
+ "title": item.Title, "body": util.TextToPtr(item.Body), "read": item.Read, "archived": item.Archived,
+ "created_at": util.TimestampToString(item.CreatedAt), "actor_type": util.TextToPtr(item.ActorType),
+ "actor_id": util.UUIDToPtr(item.ActorID), "details": json.RawMessage(item.Details), "issue_status": issueStatus,
+ }},
+ })
+}
+
+// mutedAgentActivity reports whether the recipient muted the agent-activity
+// group, which app results belong to.
+func (s *Service) mutedAgentActivity(ctx context.Context, req db.AppActionRequest) bool {
+ pref, err := s.q.GetNotificationPreference(ctx, db.GetNotificationPreferenceParams{
+ WorkspaceID: req.WorkspaceID, UserID: req.ApproverUserID,
+ })
+ if err != nil {
+ return false
+ }
+ prefs := map[string]string{}
+ _ = json.Unmarshal(pref.Preferences, &prefs)
+ return prefs["agent_activity"] == "muted"
+}
+
+// RunSweeper runs Sweep every minute until ctx ends. Safe on every replica:
+// both statements claim rows with SKIP LOCKED.
+func (s *Service) RunSweeper(ctx context.Context) {
+ t := time.NewTicker(time.Minute)
+ defer t.Stop()
+ for {
+ select {
+ case <-ctx.Done():
+ return
+ case <-t.C:
+ s.Sweep(ctx)
+ }
+ }
+}
diff --git a/server/internal/connectedapps/service.go b/server/internal/connectedapps/service.go
new file mode 100644
index 0000000000..995d6805b1
--- /dev/null
+++ b/server/internal/connectedapps/service.go
@@ -0,0 +1,464 @@
+package connectedapps
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "strings"
+ "time"
+
+ "github.com/jackc/pgx/v5"
+ "github.com/jackc/pgx/v5/pgtype"
+ "github.com/multica-ai/multica/server/internal/events"
+ composiointeg "github.com/multica-ai/multica/server/internal/integrations/composio"
+ "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"
+)
+
+// GatewayServerName is the MCP server name every run sees its apps under.
+const GatewayServerName = "multica_apps"
+
+// GatewayPath is the API route of the MCP gateway.
+const GatewayPath = "/api/apps/mcp"
+
+// Provider tags gateway-served apps in a run's connected-app metadata.
+const Provider = "multica"
+
+// RequestTTL is how long a confirmation waits before it expires.
+const RequestTTL = 24 * time.Hour
+
+// ConnectRequestTTL is how long a connection request waits. Connecting an
+// account can need someone else (an IT admin approving the OAuth app), so it
+// waits longer than a confirmation.
+const ConnectRequestTTL = 7 * 24 * time.Hour
+
+// DefaultCallsPerMinute caps the calls one account runs per minute.
+const DefaultCallsPerMinute = 30
+
+func requestTTL(kind string) time.Duration {
+ if kind == KindConnect {
+ return ConnectRequestTTL
+ }
+ return RequestTTL
+}
+
+// tokenTTL bounds a gateway token. The task status check is the real bound;
+// this only caps a token that leaks from a run that never finishes.
+const tokenTTL = 26 * time.Hour
+
+// Errors surfaced to the HTTP layer.
+var (
+ ErrRequestNotFound = errors.New("connectedapps: request not found")
+ ErrNotApprover = errors.New("connectedapps: only the approver can decide")
+ ErrNotPending = errors.New("connectedapps: request is no longer pending")
+ ErrAccountMissing = errors.New("connectedapps: account not connected")
+ // ErrNoLongerAllowed: the approver left the workspace or lost access to
+ // the agent while the request waited. The request is withdrawn.
+ ErrNoLongerAllowed = errors.New("connectedapps: the approver can no longer use this agent")
+ // ErrRateLimited: the account used its per-minute budget. The request
+ // stays pending, so approving again a minute later runs it.
+ ErrRateLimited = errors.New("connectedapps: the account is over its per-minute call budget")
+)
+
+// Resumer continues the agent's work after a person decides on a request: a
+// new run on the issue, or a message in the chat.
+type Resumer interface {
+ ResumeAfterDecision(ctx context.Context, req db.AppActionRequest, actorID pgtype.UUID, note string) error
+ // CanActFor reports whether userID may still run agentID in the
+ // workspace, by the same rule that admits a new run.
+ CanActFor(ctx context.Context, workspaceID, agentID, userID pgtype.UUID) bool
+}
+
+// Config wires a Service.
+type Config struct {
+ Queries *db.Queries
+ Composio *composiointeg.Service
+ // TokenSecret signs gateway tokens. Derive it with DeriveTokenSecret.
+ TokenSecret []byte
+ // PublicBaseURL is the API's public origin, e.g. "https://api.multica.ai".
+ PublicBaseURL string
+ Bus *events.Bus
+ Now func() time.Time
+ // CallsPerMinute caps the calls one account runs per minute;
+ // DefaultCallsPerMinute when zero.
+ CallsPerMinute int
+}
+
+// Service is the connected-apps runtime: overlay, gateway, and confirmations.
+type Service struct {
+ q *db.Queries
+ composio *composiointeg.Service
+ secret []byte
+ gatewayURL string
+ bus *events.Bus
+ now func() time.Time
+ resumer Resumer
+ perMinute int
+}
+
+// New returns a Service, or an error when a required dependency is missing.
+func New(cfg Config) (*Service, error) {
+ if cfg.Queries == nil || cfg.Composio == nil {
+ return nil, errors.New("connectedapps: queries and composio are required")
+ }
+ if len(cfg.TokenSecret) == 0 {
+ return nil, errors.New("connectedapps: token secret is required")
+ }
+ base := strings.TrimRight(strings.TrimSpace(cfg.PublicBaseURL), "/")
+ if base == "" {
+ return nil, errors.New("connectedapps: public base url is required")
+ }
+ now := cfg.Now
+ if now == nil {
+ now = time.Now
+ }
+ perMinute := cfg.CallsPerMinute
+ if perMinute <= 0 {
+ perMinute = DefaultCallsPerMinute
+ }
+ return &Service{
+ q: cfg.Queries,
+ composio: cfg.Composio,
+ secret: cfg.TokenSecret,
+ gatewayURL: base + GatewayPath,
+ bus: cfg.Bus,
+ now: now,
+ perMinute: perMinute,
+ }, nil
+}
+
+// SetResumer installs how agents are resumed after a decision.
+func (s *Service) SetResumer(r Resumer) { s.resumer = r }
+
+// Catalog is which apps a workspace lets its members use.
+type Catalog struct {
+ Mode string
+ // Allowed lists the apps of a custom catalog.
+ Allowed []string
+}
+
+// Allows reports whether the catalog permits slug.
+func (c Catalog) Allows(slug string) bool {
+ switch c.Mode {
+ case CatalogCurated:
+ _, ok := Curated(slug)
+ return ok
+ case CatalogCustom:
+ slug = NormalizeSlug(slug)
+ for _, allowed := range c.Allowed {
+ if NormalizeSlug(allowed) == slug {
+ return true
+ }
+ }
+ return false
+ }
+ return true
+}
+
+// Catalog returns the workspace's catalog, every app by default.
+func (s *Service) Catalog(ctx context.Context, workspaceID pgtype.UUID) Catalog {
+ row, err := s.q.GetWorkspaceAppSetting(ctx, workspaceID)
+ if err != nil {
+ return Catalog{Mode: CatalogAll}
+ }
+ switch row.CatalogMode {
+ case CatalogCurated:
+ return Catalog{Mode: CatalogCurated}
+ case CatalogCustom:
+ return Catalog{Mode: CatalogCustom, Allowed: row.AllowedToolkits}
+ }
+ return Catalog{Mode: CatalogAll}
+}
+
+// ClassOverrides returns the workspace's class corrections for one app, keyed
+// by upper-case tool slug.
+func (s *Service) ClassOverrides(ctx context.Context, workspaceID pgtype.UUID, slug string) map[string]string {
+ rows, err := s.q.ListAppToolClassOverrides(ctx, db.ListAppToolClassOverridesParams{
+ WorkspaceID: workspaceID, ToolkitSlug: NormalizeSlug(slug),
+ })
+ out := make(map[string]string, len(rows))
+ if err != nil {
+ return out
+ }
+ for _, row := range rows {
+ out[strings.ToUpper(row.ToolSlug)] = row.ActionClass
+ }
+ return out
+}
+
+// classify is Classify with the workspace's corrections applied first.
+func (s *Service) classify(ctx context.Context, workspaceID pgtype.UUID, slug string, tool *sdk.Tool) string {
+ class, err := s.q.GetAppToolClassOverride(ctx, db.GetAppToolClassOverrideParams{
+ WorkspaceID: workspaceID, ToolkitSlug: NormalizeSlug(slug), ToolSlug: strings.ToUpper(tool.Slug),
+ })
+ if err == nil {
+ return class
+ }
+ return Classify(slug, tool.Slug, tool.Tags)
+}
+
+type gatewayServer struct {
+ Type string `json:"type"`
+ URL string `json:"url"`
+ Headers map[string]string `json:"headers,omitempty"`
+}
+
+type gatewayOverlay struct {
+ MCPServers map[string]gatewayServer `json:"mcpServers"`
+}
+
+// BuildTaskOverlay is the enqueue-time overlay for a run of agent. It carries
+// no credential: only the gateway address and which apps the agent has. The
+// claim handler adds the run's token (AuthorizeOverlay) once the task id is
+// final. A zero result means the agent has no apps.
+func (s *Service) BuildTaskOverlay(ctx context.Context, originatorUserID pgtype.UUID, agent db.Agent) (runtimeapps.MCPOverlayResult, error) {
+ apps, err := s.q.ListAgentApps(ctx, agent.ID)
+ if err != nil {
+ return runtimeapps.MCPOverlayResult{}, fmt.Errorf("connectedapps: list agent apps: %w", err)
+ }
+ if len(apps) == 0 {
+ return runtimeapps.MCPOverlayResult{}, nil
+ }
+ catalog := s.Catalog(ctx, agent.WorkspaceID)
+ team, err := s.activeTeamAccounts(ctx, agent.WorkspaceID)
+ if err != nil {
+ return runtimeapps.MCPOverlayResult{}, err
+ }
+ personal := map[string]db.UserComposioConnection{}
+ if originatorUserID.Valid {
+ if personal, err = s.activePersonalAccounts(ctx, originatorUserID); err != nil {
+ return runtimeapps.MCPOverlayResult{}, err
+ }
+ }
+ meta := make([]runtimeapps.ConnectedApp, 0, len(apps))
+ for _, app := range apps {
+ if !catalog.Allows(app.ToolkitSlug) {
+ continue
+ }
+ status := "not_connected"
+ if app.AccountScope == ScopeTeam {
+ if _, ok := team[app.ToolkitSlug]; ok {
+ status = "connected"
+ }
+ } else if _, ok := personal[app.ToolkitSlug]; ok {
+ status = "connected"
+ }
+ meta = append(meta, runtimeapps.ConnectedApp{
+ Provider: Provider,
+ ServerName: GatewayServerName,
+ ToolkitSlug: app.ToolkitSlug,
+ ToolkitName: runtimeapps.DisplayNameForToolkitSlug(app.ToolkitSlug),
+ AccountScope: app.AccountScope,
+ Level: app.Level,
+ AccountStatus: status,
+ })
+ }
+ if len(meta) == 0 {
+ return runtimeapps.MCPOverlayResult{}, nil
+ }
+ raw, err := json.Marshal(gatewayOverlay{MCPServers: map[string]gatewayServer{
+ GatewayServerName: {Type: "http", URL: s.gatewayURL},
+ }})
+ if err != nil {
+ return runtimeapps.MCPOverlayResult{}, err
+ }
+ return runtimeapps.MCPOverlayResult{MCPOverlay: raw, ConnectedApps: meta}, nil
+}
+
+// AuthorizeOverlay adds a token for taskID to the gateway entry of a stored
+// overlay. Overlays without a gateway entry are returned unchanged.
+func (s *Service) AuthorizeOverlay(overlay []byte, taskID pgtype.UUID) ([]byte, error) {
+ var parsed struct {
+ MCPServers map[string]json.RawMessage `json:"mcpServers"`
+ }
+ if err := json.Unmarshal(overlay, &parsed); err != nil {
+ return nil, err
+ }
+ entry, ok := parsed.MCPServers[GatewayServerName]
+ if !ok {
+ return overlay, nil
+ }
+ var server gatewayServer
+ if err := json.Unmarshal(entry, &server); err != nil {
+ return nil, err
+ }
+ token, err := SignTaskToken(s.secret, util.UUIDToString(taskID), s.now().Add(tokenTTL))
+ if err != nil {
+ return nil, err
+ }
+ server.Type = "http"
+ server.URL = s.gatewayURL
+ server.Headers = map[string]string{"Authorization": "Bearer " + token}
+ raw, err := json.Marshal(server)
+ if err != nil {
+ return nil, err
+ }
+ parsed.MCPServers[GatewayServerName] = raw
+ return json.Marshal(map[string]any{"mcpServers": parsed.MCPServers})
+}
+
+func (s *Service) activeTeamAccounts(ctx context.Context, workspaceID pgtype.UUID) (map[string]db.WorkspaceComposioConnection, error) {
+ rows, err := s.q.ListWorkspaceComposioConnections(ctx, workspaceID)
+ if err != nil {
+ return nil, fmt.Errorf("connectedapps: list team accounts: %w", err)
+ }
+ out := map[string]db.WorkspaceComposioConnection{}
+ for _, row := range rows {
+ slug := NormalizeSlug(row.ToolkitSlug)
+ if row.Status != "active" {
+ continue
+ }
+ if _, dup := out[slug]; !dup {
+ out[slug] = row
+ }
+ }
+ return out, nil
+}
+
+func (s *Service) activePersonalAccounts(ctx context.Context, userID pgtype.UUID) (map[string]db.UserComposioConnection, error) {
+ rows, err := s.q.ListActiveUserComposioConnections(ctx, userID)
+ if err != nil {
+ return nil, fmt.Errorf("connectedapps: list personal accounts: %w", err)
+ }
+ out := map[string]db.UserComposioConnection{}
+ for _, row := range rows {
+ slug := NormalizeSlug(row.ToolkitSlug)
+ if _, dup := out[slug]; !dup {
+ out[slug] = row
+ }
+ }
+ return out, nil
+}
+
+// account is the connected account one call acts through.
+type account struct {
+ scope string
+ connectedAccountID string
+ connectionID pgtype.UUID
+ // owner is the member whose personal account it is; invalid for team.
+ owner pgtype.UUID
+}
+
+// resolveAccount finds the account an app acts as for a run: the workspace's
+// team account, or the personal account of the member who triggered the run.
+func (s *Service) resolveAccount(ctx context.Context, workspaceID, triggeredBy pgtype.UUID, slug, scope string) (account, error) {
+ if scope == ScopeTeam {
+ team, err := s.activeTeamAccounts(ctx, workspaceID)
+ if err != nil {
+ return account{}, err
+ }
+ row, ok := team[slug]
+ if !ok {
+ return account{}, ErrAccountMissing
+ }
+ return account{scope: ScopeTeam, connectedAccountID: row.ConnectedAccountID, connectionID: row.ID}, nil
+ }
+ if !triggeredBy.Valid {
+ return account{}, ErrAccountMissing
+ }
+ personal, err := s.activePersonalAccounts(ctx, triggeredBy)
+ if err != nil {
+ return account{}, err
+ }
+ row, ok := personal[slug]
+ if !ok {
+ return account{}, ErrAccountMissing
+ }
+ return account{scope: ScopePersonal, connectedAccountID: row.ConnectedAccountID, connectionID: row.ID, owner: triggeredBy}, nil
+}
+
+// accountRule returns the account owner's rule for one class, or "".
+func (s *Service) accountRule(ctx context.Context, workspaceID pgtype.UUID, slug string, acct account, class string) (string, error) {
+ rules, err := s.q.ListAppActionRules(ctx, db.ListAppActionRulesParams{
+ WorkspaceID: workspaceID,
+ ToolkitSlug: slug,
+ OwnerUserID: acct.owner,
+ })
+ if err != nil {
+ return "", fmt.Errorf("connectedapps: list rules: %w", err)
+ }
+ for _, r := range rules {
+ if r.ActionClass == class {
+ return r.Policy, nil
+ }
+ }
+ return "", nil
+}
+
+func (s *Service) touch(ctx context.Context, workspaceID pgtype.UUID, acct account) {
+ if acct.scope == ScopeTeam {
+ _ = s.q.TouchWorkspaceComposioConnection(ctx, db.TouchWorkspaceComposioConnectionParams{ID: acct.connectionID, WorkspaceID: workspaceID})
+ return
+ }
+ _ = s.q.TouchUserComposioConnection(ctx, db.TouchUserComposioConnectionParams{ID: acct.connectionID, UserID: acct.owner})
+}
+
+type toolCall struct {
+ workspaceID, taskID, agentID, issueID, chatSessionID, triggeredBy pgtype.UUID
+ acct account
+ toolkit, tool, class, outcome string
+ requestID pgtype.UUID
+ err string
+}
+
+func (s *Service) recordCall(ctx context.Context, c toolCall) {
+ scope := c.acct.scope
+ if scope == "" {
+ scope = ScopePersonal
+ }
+ _ = s.q.InsertAppToolCall(ctx, db.InsertAppToolCallParams{
+ WorkspaceID: c.workspaceID,
+ TaskID: c.taskID,
+ AgentID: c.agentID,
+ IssueID: c.issueID,
+ ChatSessionID: c.chatSessionID,
+ TriggeredBy: c.triggeredBy,
+ AccountScope: scope,
+ AccountOwnerUserID: c.acct.owner,
+ ToolkitSlug: c.toolkit,
+ ToolSlug: c.tool,
+ ActionClass: c.class,
+ Outcome: c.outcome,
+ RequestID: c.requestID,
+ Error: pgtype.Text{String: c.err, Valid: c.err != ""},
+ })
+ if s.bus != nil && c.issueID.Valid {
+ s.bus.Publish(events.Event{
+ Type: EventCallCreated,
+ WorkspaceID: util.UUIDToString(c.workspaceID),
+ ActorType: "agent",
+ ActorID: util.UUIDToString(c.agentID),
+ Payload: map[string]any{"issue_id": util.UUIDToString(c.issueID)},
+ })
+ }
+}
+
+// overLimit reports whether acct already ran its per-minute share of calls.
+func (s *Service) overLimit(ctx context.Context, workspaceID pgtype.UUID, slug string, acct account) bool {
+ n, err := s.q.CountRecentAppAccountCalls(ctx, db.CountRecentAppAccountCallsParams{
+ WorkspaceID: workspaceID,
+ ToolkitSlug: slug,
+ AccountScope: acct.scope,
+ Owner: acct.owner,
+ Since: pgtype.Timestamptz{Time: s.now().Add(-time.Minute), Valid: true},
+ })
+ return err == nil && n >= int64(s.perMinute)
+}
+
+// firstBlock reports whether this is the run's first blocked call of a tool,
+// so the person who triggered it is told once, not on every retry.
+func (s *Service) firstBlock(ctx context.Context, c toolCall) bool {
+ if !c.taskID.Valid {
+ return true
+ }
+ seen, err := s.q.HasBlockedAppToolCall(ctx, db.HasBlockedAppToolCallParams{
+ WorkspaceID: c.workspaceID, ToolkitSlug: c.toolkit, TaskID: c.taskID, ToolSlug: c.tool,
+ Since: pgtype.Timestamptz{Time: s.now().Add(-tokenTTL), Valid: true},
+ })
+ return err == nil && !seen
+}
+
+func isNoRows(err error) bool { return errors.Is(err, pgx.ErrNoRows) }
diff --git a/server/internal/connectedapps/token.go b/server/internal/connectedapps/token.go
new file mode 100644
index 0000000000..84d3ea74c7
--- /dev/null
+++ b/server/internal/connectedapps/token.go
@@ -0,0 +1,78 @@
+package connectedapps
+
+import (
+ "crypto/hmac"
+ "crypto/sha256"
+ "encoding/base64"
+ "encoding/json"
+ "errors"
+ "strings"
+ "time"
+)
+
+// Gateway token errors. The gateway answers all of them with the same 401.
+var (
+ ErrTokenMalformed = errors.New("connectedapps: token malformed")
+ ErrTokenSignature = errors.New("connectedapps: token signature mismatch")
+ ErrTokenExpired = errors.New("connectedapps: token expired")
+)
+
+const tokenPrefix = "mca_"
+
+type tokenClaims struct {
+ TaskID string `json:"t"`
+ Exp int64 `json:"e"`
+}
+
+// DeriveTokenSecret derives the gateway signing key from a service secret, so
+// a gateway token can never verify as a connect state or the other way round.
+func DeriveTokenSecret(secret []byte) []byte {
+ mac := hmac.New(sha256.New, secret)
+ mac.Write([]byte("multica-connected-apps-gateway-v1"))
+ return mac.Sum(nil)
+}
+
+// SignTaskToken mints the bearer token a run presents to the gateway. It names
+// only the task; everything else (agent, workspace, who triggered it) is read
+// from the task row on each call, so the token is useless once the run ends.
+func SignTaskToken(secret []byte, taskID string, exp time.Time) (string, error) {
+ raw, err := json.Marshal(tokenClaims{TaskID: taskID, Exp: exp.Unix()})
+ if err != nil {
+ return "", err
+ }
+ payload := base64.RawURLEncoding.EncodeToString(raw)
+ return tokenPrefix + payload + "." + signTokenPayload(secret, payload), nil
+}
+
+// VerifyTaskToken checks a gateway token and returns its task id.
+func VerifyTaskToken(secret []byte, token string, now time.Time) (string, error) {
+ body, ok := strings.CutPrefix(strings.TrimSpace(token), tokenPrefix)
+ if !ok {
+ return "", ErrTokenMalformed
+ }
+ payload, sig, found := strings.Cut(body, ".")
+ if !found || payload == "" || sig == "" {
+ return "", ErrTokenMalformed
+ }
+ if !hmac.Equal([]byte(sig), []byte(signTokenPayload(secret, payload))) {
+ return "", ErrTokenSignature
+ }
+ raw, err := base64.RawURLEncoding.DecodeString(payload)
+ if err != nil {
+ return "", ErrTokenMalformed
+ }
+ var claims tokenClaims
+ if err := json.Unmarshal(raw, &claims); err != nil || claims.TaskID == "" {
+ return "", ErrTokenMalformed
+ }
+ if now.Unix() > claims.Exp {
+ return "", ErrTokenExpired
+ }
+ return claims.TaskID, nil
+}
+
+func signTokenPayload(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/daemon/execenv/runtime_config_sections.go b/server/internal/daemon/execenv/runtime_config_sections.go
index 8c9addbdec..e1bca8d872 100644
--- a/server/internal/daemon/execenv/runtime_config_sections.go
+++ b/server/internal/daemon/execenv/runtime_config_sections.go
@@ -166,6 +166,7 @@ func BuildConnectedAppsBlock(apps []runtimeapps.ConnectedApp) string {
}
var b strings.Builder
var lines strings.Builder
+ gateway := ""
for _, app := range apps {
serverName := sanitizeBriefCodeToken(app.ServerName)
toolkitSlug := sanitizeBriefCodeToken(app.ToolkitSlug)
@@ -179,6 +180,11 @@ func BuildConnectedAppsBlock(apps []runtimeapps.ConnectedApp) string {
if name == "" {
name = toolkitSlug
}
+ if app.Provider == "multica" {
+ gateway = serverName
+ fmt.Fprintf(&lines, "- %s (`%s`) via MCP server `%s`%s\n", name, toolkitSlug, serverName, gatewayAppDetail(app))
+ continue
+ }
fmt.Fprintf(&lines, "- %s (`%s`) via MCP server `%s`\n", name, toolkitSlug, serverName)
}
if lines.Len() == 0 {
@@ -186,10 +192,43 @@ func BuildConnectedAppsBlock(apps []runtimeapps.ConnectedApp) string {
}
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")
+ b.WriteString("\nUse the listed MCP server when the task asks to read or act in one of these apps.\n")
+ if gateway != "" {
+ fmt.Fprintf(&b, "On `%s`, find tools with `apps_search_tools`, read the schema with `apps_get_tool`, then call `apps_run_tool`. "+
+ "When `apps_run_tool` answers `submitted`, the call waits for a person's confirmation: end your turn — you are resumed with the outcome. "+
+ "Never retry a submitted call or work around a blocked one. For a `not connected` account, call `apps_request_connection` and end your turn.\n", gateway)
+ }
+ b.WriteString("\n")
return b.String()
}
+// gatewayAppDetail is the account, level and connection note for one
+// gateway app line.
+func gatewayAppDetail(app runtimeapps.ConnectedApp) string {
+ var parts []string
+ switch app.AccountScope {
+ case "team":
+ parts = append(parts, "team account")
+ case "personal":
+ parts = append(parts, "account of the person who triggered this run")
+ }
+ switch app.Level {
+ case "read":
+ parts = append(parts, "read only")
+ case "confirm_writes":
+ parts = append(parts, "writes need confirmation")
+ case "write":
+ parts = append(parts, "can write")
+ }
+ if app.AccountStatus == "not_connected" {
+ parts = append(parts, "not connected")
+ }
+ if len(parts) == 0 {
+ return ""
+ }
+ return " — " + strings.Join(parts, ", ")
+}
+
func sanitizeBriefCodeToken(s string) string {
s = strings.TrimSpace(s)
if s == "" {
diff --git a/server/internal/handler/agent.go b/server/internal/handler/agent.go
index be78a9baf0..b65479bfd5 100644
--- a/server/internal/handler/agent.go
+++ b/server/internal/handler/agent.go
@@ -1722,6 +1722,12 @@ func (h *Handler) CreateAgent(w http.ResponseWriter, r *http.Request) {
writeError(w, http.StatusInternalServerError, "failed to save agent access")
return
}
+ if len(allowlist) > 0 {
+ if err := syncAgentAppsFromAllowlist(r.Context(), qtx, created, allowlist, parseUUID(ownerID)); err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to save agent apps")
+ return
+ }
+ }
for _, skillID := range skillUUIDs {
if err := qtx.AddAgentSkill(r.Context(), db.AddAgentSkillParams{
AgentID: created.ID,
@@ -2560,6 +2566,13 @@ func (h *Handler) UpdateAgent(w http.ResponseWriter, r *http.Request) {
return
}
}
+ if shouldClearComposioAllowlist || params.ComposioToolkitAllowlist != nil {
+ if err := syncAgentAppsFromAllowlist(r.Context(), h.Queries, updated, params.ComposioToolkitAllowlist, parseUUID(requestUserID(r))); err != nil {
+ slog.Warn("update agent: sync agent apps failed", append(logger.RequestAttrs(r), "error", err, "agent_id", id)...)
+ writeError(w, http.StatusInternalServerError, "failed to update agent apps")
+ return
+ }
+ }
// Invocation targets (MUL-3963): replace wholesale when the owner touched
// permission. Done after the row update so a permission_mode flip and its
diff --git a/server/internal/handler/connected_apps.go b/server/internal/handler/connected_apps.go
new file mode 100644
index 0000000000..96318721b4
--- /dev/null
+++ b/server/internal/handler/connected_apps.go
@@ -0,0 +1,1192 @@
+package handler
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "log/slog"
+ "net/http"
+ "sort"
+ "strconv"
+ "strings"
+ "time"
+
+ "github.com/go-chi/chi/v5"
+ "github.com/jackc/pgx/v5/pgtype"
+ "github.com/multica-ai/multica/server/internal/connectedapps"
+ "github.com/multica-ai/multica/server/internal/integrations/composio"
+ "github.com/multica-ai/multica/server/internal/logger"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+ "github.com/multica-ai/multica/server/pkg/protocol"
+)
+
+// Connected Apps v2 (MUL-8516). Team accounts belong to the workspace and are
+// managed by admins; personal accounts belong to a member. Agents get apps
+// with an account scope and a level; every call goes through the gateway in
+// internal/connectedapps.
+
+// AppConnectionResponse is one team or personal account.
+type AppConnectionResponse struct {
+ ID string `json:"id"`
+ ToolkitSlug string `json:"toolkit_slug"`
+ Status string `json:"status"`
+ ConnectedBy *string `json:"connected_by,omitempty"`
+ ConnectedAt string `json:"connected_at"`
+ LastUsedAt *string `json:"last_used_at"`
+}
+
+// AgentAppResponse is one app attached to an agent.
+type AgentAppResponse struct {
+ AgentID string `json:"agent_id"`
+ ToolkitSlug string `json:"toolkit_slug"`
+ AccountScope string `json:"account_scope"`
+ Level string `json:"level"`
+}
+
+// AppsOverviewResponse backs Settings › Apps.
+type AppsOverviewResponse struct {
+ CatalogMode string `json:"catalog_mode"`
+ AllowedToolkits []string `json:"allowed_toolkits"`
+ CanManage bool `json:"can_manage"`
+ Team []AppConnectionResponse `json:"team"`
+ Personal []AppConnectionResponse `json:"personal"`
+ AgentApps []AgentAppResponse `json:"agent_apps"`
+}
+
+// AppCatalogEntry is one app in the add-app dialog.
+type AppCatalogEntry struct {
+ Slug string `json:"slug"`
+ Name string `json:"name"`
+ Logo string `json:"logo,omitempty"`
+ Category string `json:"category,omitempty"`
+ Curated bool `json:"curated"`
+ RecommendedScope string `json:"recommended_scope,omitempty"`
+ // Allowed is false only in the admin's full view (?view=all) for apps
+ // the workspace catalog leaves out.
+ Allowed bool `json:"allowed"`
+}
+
+// AppToolResponse is one tool of an app with how it is classified.
+type AppToolResponse struct {
+ Slug string `json:"slug"`
+ Name string `json:"name"`
+ Description string `json:"description"`
+ AutoClass string `json:"auto_class"`
+ Class string `json:"class"`
+ Overridden bool `json:"overridden"`
+}
+
+// IssueAppCallResponse is one call an issue's runs made. Errors stay with
+// the account owner, like an account's activity.
+type IssueAppCallResponse struct {
+ ID string `json:"id"`
+ TaskID *string `json:"task_id"`
+ AgentID string `json:"agent_id"`
+ AccountScope string `json:"account_scope"`
+ AccountOwnerUserID *string `json:"account_owner_user_id"`
+ ToolkitSlug string `json:"toolkit_slug"`
+ ToolSlug string `json:"tool_slug"`
+ ActionClass string `json:"action_class"`
+ Outcome string `json:"outcome"`
+ RequestID *string `json:"request_id"`
+ Error *string `json:"error"`
+ CreatedAt string `json:"created_at"`
+}
+
+// AppRuleResponse is the policy of one action class for one account.
+type AppRuleResponse struct {
+ ActionClass string `json:"action_class"`
+ Policy string `json:"policy"`
+ DefaultPolicy string `json:"default_policy"`
+ Custom bool `json:"custom"`
+}
+
+// AppToolCallResponse is one row of an app's activity.
+type AppToolCallResponse struct {
+ ID string `json:"id"`
+ AgentID string `json:"agent_id"`
+ IssueID *string `json:"issue_id"`
+ ChatSessionID *string `json:"chat_session_id"`
+ TriggeredBy *string `json:"triggered_by"`
+ ToolSlug string `json:"tool_slug"`
+ ActionClass string `json:"action_class"`
+ Outcome string `json:"outcome"`
+ Error *string `json:"error"`
+ CreatedAt string `json:"created_at"`
+}
+
+// AppRequestResponse is one confirmation or connection request. Arguments and
+// results are shown only to the approver: a personal account's draft email is
+// not for everyone who can open the issue.
+type AppRequestResponse struct {
+ ID string `json:"id"`
+ Kind string `json:"kind"`
+ Status string `json:"status"`
+ AgentID string `json:"agent_id"`
+ IssueID *string `json:"issue_id"`
+ ChatSessionID *string `json:"chat_session_id"`
+ ApproverUserID string `json:"approver_user_id"`
+ AccountScope string `json:"account_scope"`
+ ToolkitSlug string `json:"toolkit_slug"`
+ ToolSlug string `json:"tool_slug"`
+ ActionClass string `json:"action_class"`
+ Summary string `json:"summary"`
+ Arguments json.RawMessage `json:"arguments,omitempty"`
+ ApprovedArguments json.RawMessage `json:"approved_arguments,omitempty"`
+ Result json.RawMessage `json:"result,omitempty"`
+ Error *string `json:"error"`
+ Reason *string `json:"reason"`
+ Redacted bool `json:"redacted"`
+ ExpiresAt string `json:"expires_at"`
+ DecidedBy *string `json:"decided_by"`
+ DecidedAt *string `json:"decided_at"`
+ CreatedAt string `json:"created_at"`
+}
+
+func (h *Handler) appsReady(w http.ResponseWriter, r *http.Request) bool {
+ if h.Composio == nil || h.ConnectedApps == nil || !h.composioMCPAppsEnabled(r.Context()) {
+ writeFeatureDisabled(w, "apps_not_configured", "connected apps are not configured")
+ return false
+ }
+ return true
+}
+
+// appsMember returns the caller's membership and whether they administer the
+// workspace. Every Connected Apps endpoint behind it is for people: a run's
+// credential acts as its owner, and must not approve its own calls, change
+// the owner's rules, or read the owner's requests and accounts. Runs reach
+// apps only through the gateway.
+func (h *Handler) appsMember(w http.ResponseWriter, r *http.Request) (db.Member, pgtype.UUID, bool, bool) {
+ if isMachineCredentialActor(r) {
+ writeError(w, http.StatusForbidden, "this endpoint is only available to human actors")
+ return db.Member{}, pgtype.UUID{}, false, false
+ }
+ workspaceID := ctxWorkspaceID(r.Context())
+ member, ok := h.workspaceMember(w, r, workspaceID)
+ if !ok {
+ return db.Member{}, pgtype.UUID{}, false, false
+ }
+ return member, parseUUID(workspaceID), roleAllowed(member.Role, "owner", "admin"), true
+}
+
+func connectionFromTeam(row db.WorkspaceComposioConnection) AppConnectionResponse {
+ return AppConnectionResponse{
+ ID: uuidToString(row.ID),
+ ToolkitSlug: row.ToolkitSlug,
+ Status: row.Status,
+ ConnectedBy: uuidToPtr(row.ConnectedBy),
+ ConnectedAt: timestampToString(row.ConnectedAt),
+ LastUsedAt: timestampToPtr(row.LastUsedAt),
+ }
+}
+
+func connectionFromPersonal(row db.UserComposioConnection) AppConnectionResponse {
+ return AppConnectionResponse{
+ ID: uuidToString(row.ID),
+ ToolkitSlug: row.ToolkitSlug,
+ Status: row.Status,
+ ConnectedAt: timestampToString(row.ConnectedAt),
+ LastUsedAt: timestampToPtr(row.LastUsedAt),
+ }
+}
+
+func agentAppResponse(row db.AgentApp) AgentAppResponse {
+ return AgentAppResponse{
+ AgentID: uuidToString(row.AgentID),
+ ToolkitSlug: row.ToolkitSlug,
+ AccountScope: row.AccountScope,
+ Level: row.Level,
+ }
+}
+
+// GetAppsOverview (GET /api/apps) returns the workspace's team accounts, the
+// caller's personal accounts, and which agents use which apps.
+func (h *Handler) GetAppsOverview(w http.ResponseWriter, r *http.Request) {
+ if !h.appsReady(w, r) {
+ return
+ }
+ member, workspaceID, isAdmin, ok := h.appsMember(w, r)
+ if !ok {
+ return
+ }
+ ctx := r.Context()
+ team, err := h.Queries.ListWorkspaceComposioConnections(ctx, workspaceID)
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to list team accounts")
+ return
+ }
+ personal, err := h.Queries.ListUserComposioConnectionsAnyStatus(ctx, member.UserID)
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to list personal accounts")
+ return
+ }
+ agentApps, err := h.Queries.ListAgentAppsInWorkspace(ctx, workspaceID)
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to list agent apps")
+ return
+ }
+ catalog := h.ConnectedApps.Catalog(ctx, workspaceID)
+ resp := AppsOverviewResponse{
+ CatalogMode: catalog.Mode,
+ AllowedToolkits: append([]string{}, catalog.Allowed...),
+ CanManage: isAdmin,
+ Team: make([]AppConnectionResponse, 0, len(team)),
+ Personal: make([]AppConnectionResponse, 0, len(personal)),
+ AgentApps: make([]AgentAppResponse, 0, len(agentApps)),
+ }
+ for _, row := range team {
+ resp.Team = append(resp.Team, connectionFromTeam(row))
+ }
+ for _, row := range personal {
+ resp.Personal = append(resp.Personal, connectionFromPersonal(row))
+ }
+ for _, row := range agentApps {
+ resp.AgentApps = append(resp.AgentApps, agentAppResponse(row))
+ }
+ writeJSON(w, http.StatusOK, resp)
+}
+
+// ListAppCatalog (GET /api/apps/catalog) is every app the workspace may add.
+// An admin passing ?view=all gets every connectable app, each marked with
+// whether the catalog allows it, to edit a custom list.
+func (h *Handler) ListAppCatalog(w http.ResponseWriter, r *http.Request) {
+ if !h.appsReady(w, r) {
+ return
+ }
+ _, workspaceID, isAdmin, ok := h.appsMember(w, r)
+ if !ok {
+ return
+ }
+ viewAll := isAdmin && r.URL.Query().Get("view") == "all"
+ toolkits, err := h.Composio.ListToolkits(r.Context())
+ if err != nil {
+ slog.Warn("apps catalog failed", append(logger.RequestAttrs(r), "error", err)...)
+ writeError(w, http.StatusBadGateway, "failed to load apps")
+ return
+ }
+ catalog := h.ConnectedApps.Catalog(r.Context(), workspaceID)
+ out := make([]AppCatalogEntry, 0, len(toolkits))
+ for _, tk := range toolkits {
+ slug := connectedapps.NormalizeSlug(tk.Slug)
+ allowed := catalog.Allows(slug)
+ if !allowed && !viewAll {
+ continue
+ }
+ entry := AppCatalogEntry{Slug: slug, Name: tk.Name, Logo: tk.LogoURL, Category: tk.Category, Allowed: allowed}
+ if app, ok := connectedapps.Curated(slug); ok {
+ entry.Curated, entry.RecommendedScope = true, app.Scope
+ }
+ out = append(out, entry)
+ }
+ // Curated apps first, each group keeping Composio's usage order.
+ sort.SliceStable(out, func(i, j int) bool { return out[i].Curated && !out[j].Curated })
+ writeJSON(w, http.StatusOK, map[string]any{"catalog_mode": catalog.Mode, "apps": out})
+}
+
+type appSlugRequest struct {
+ ToolkitSlug string `json:"toolkit_slug"`
+ // ReturnTo is the app path to come back to after the hosted flow.
+ ReturnTo string `json:"return_to"`
+}
+
+func (h *Handler) decodeAppSlug(w http.ResponseWriter, r *http.Request, workspaceID pgtype.UUID) (appSlugRequest, bool) {
+ var req appSlugRequest
+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
+ writeError(w, http.StatusBadRequest, "invalid request body")
+ return req, false
+ }
+ slug := connectedapps.NormalizeSlug(req.ToolkitSlug)
+ if slug == "" {
+ writeError(w, http.StatusBadRequest, "toolkit_slug is required")
+ return req, false
+ }
+ if !h.ConnectedApps.Catalog(r.Context(), workspaceID).Allows(slug) {
+ writeError(w, http.StatusForbidden, "this workspace does not allow this app")
+ return req, false
+ }
+ req.ToolkitSlug = slug
+ return req, true
+}
+
+func writeConnectError(w http.ResponseWriter, r *http.Request, err error) {
+ if errors.Is(err, composio.ErrToolkitNotSupported) {
+ writeError(w, http.StatusBadRequest, "app not supported")
+ return
+ }
+ slog.Warn("apps connect failed", append(logger.RequestAttrs(r), "error", err)...)
+ writeError(w, http.StatusBadGateway, "failed to start connect")
+}
+
+// ConnectTeamApp (POST /api/apps/team/connect) starts connecting the
+// workspace's team account for an app. Admins only.
+func (h *Handler) ConnectTeamApp(w http.ResponseWriter, r *http.Request) {
+ if !h.appsReady(w, r) {
+ return
+ }
+ member, workspaceID, isAdmin, ok := h.appsMember(w, r)
+ if !ok {
+ return
+ }
+ if !isAdmin {
+ writeError(w, http.StatusForbidden, "only workspace admins can connect team accounts")
+ return
+ }
+ req, ok := h.decodeAppSlug(w, r, workspaceID)
+ if !ok {
+ return
+ }
+ url, err := h.Composio.BeginTeamConnect(r.Context(), workspaceID, member.UserID, req.ToolkitSlug, req.ReturnTo)
+ if err != nil {
+ writeConnectError(w, r, err)
+ return
+ }
+ writeJSON(w, http.StatusOK, ComposioConnectInitResponse{RedirectURL: url})
+}
+
+// ConnectPersonalApp (POST /api/apps/personal/connect) starts connecting the
+// caller's own account, within the workspace's catalog.
+func (h *Handler) ConnectPersonalApp(w http.ResponseWriter, r *http.Request) {
+ if !h.appsReady(w, r) {
+ return
+ }
+ member, workspaceID, _, ok := h.appsMember(w, r)
+ if !ok {
+ return
+ }
+ req, ok := h.decodeAppSlug(w, r, workspaceID)
+ if !ok {
+ return
+ }
+ url, err := h.Composio.BeginConnectReturning(r.Context(), member.UserID, req.ToolkitSlug, req.ReturnTo)
+ if err != nil {
+ writeConnectError(w, r, err)
+ return
+ }
+ writeJSON(w, http.StatusOK, ComposioConnectInitResponse{RedirectURL: url})
+}
+
+// DisconnectTeamApp (DELETE /api/apps/team/connections/{id}) revokes a team
+// account and cancels the requests waiting on it. Admins only.
+func (h *Handler) DisconnectTeamApp(w http.ResponseWriter, r *http.Request) {
+ if !h.appsReady(w, r) {
+ return
+ }
+ _, workspaceID, isAdmin, ok := h.appsMember(w, r)
+ if !ok {
+ return
+ }
+ if !isAdmin {
+ writeError(w, http.StatusForbidden, "only workspace admins can disconnect team accounts")
+ return
+ }
+ id, ok := parseUUIDOrBadRequest(w, chi.URLParam(r, "id"), "connection id")
+ if !ok {
+ return
+ }
+ row, err := h.Composio.DisconnectTeam(r.Context(), workspaceID, id)
+ if errors.Is(err, composio.ErrConnectionNotFound) {
+ writeError(w, http.StatusNotFound, "connection not found")
+ return
+ }
+ if err != nil {
+ slog.Warn("apps team disconnect failed", append(logger.RequestAttrs(r), "error", err)...)
+ writeError(w, http.StatusBadGateway, "failed to disconnect")
+ return
+ }
+ h.ConnectedApps.CancelTeamRequests(r.Context(), workspaceID, row.ToolkitSlug)
+ w.WriteHeader(http.StatusNoContent)
+}
+
+// GetTeamAppImpact (GET /api/apps/team/impact?toolkit_slug=) is what
+// disconnecting a team account would stop. Admins only.
+func (h *Handler) GetTeamAppImpact(w http.ResponseWriter, r *http.Request) {
+ if !h.appsReady(w, r) {
+ return
+ }
+ _, workspaceID, isAdmin, ok := h.appsMember(w, r)
+ if !ok {
+ return
+ }
+ if !isAdmin {
+ writeError(w, http.StatusForbidden, "insufficient permissions")
+ return
+ }
+ slug := connectedapps.NormalizeSlug(r.URL.Query().Get("toolkit_slug"))
+ ctx := r.Context()
+ apps, err := h.Queries.ListAgentAppsInWorkspace(ctx, workspaceID)
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to list agent apps")
+ return
+ }
+ agentIDs := []pgtype.UUID{}
+ agents := []map[string]string{}
+ for _, app := range apps {
+ if app.ToolkitSlug != slug || app.AccountScope != connectedapps.ScopeTeam {
+ continue
+ }
+ agentIDs = append(agentIDs, app.AgentID)
+ name := ""
+ if agent, err := h.Queries.GetAgent(ctx, app.AgentID); err == nil {
+ name = agent.Name
+ }
+ agents = append(agents, map[string]string{"id": uuidToString(app.AgentID), "name": name})
+ }
+ var tasks, autopilots int64
+ if len(agentIDs) > 0 {
+ tasks, _ = h.Queries.CountActiveTasksForAgents(ctx, agentIDs)
+ autopilots, _ = h.Queries.CountActiveAutopilotsForAgents(ctx, db.CountActiveAutopilotsForAgentsParams{WorkspaceID: workspaceID, AgentIds: agentIDs})
+ }
+ pending, _ := h.Queries.CountPendingTeamAppActionRequests(ctx, db.CountPendingTeamAppActionRequestsParams{WorkspaceID: workspaceID, ToolkitSlug: slug})
+ writeJSON(w, http.StatusOK, map[string]any{
+ "agents": agents,
+ "active_tasks": tasks,
+ "active_autopilots": autopilots,
+ "pending_requests": pending,
+ })
+}
+
+// maxAllowedToolkits bounds a custom catalog.
+const maxAllowedToolkits = 500
+
+// UpdateAppSettings (PUT /api/apps/settings) sets the catalog: all apps,
+// curated ones, or a custom list. Admins only.
+func (h *Handler) UpdateAppSettings(w http.ResponseWriter, r *http.Request) {
+ if !h.appsReady(w, r) {
+ return
+ }
+ member, workspaceID, isAdmin, ok := h.appsMember(w, r)
+ if !ok {
+ return
+ }
+ if !isAdmin {
+ writeError(w, http.StatusForbidden, "insufficient permissions")
+ return
+ }
+ var req struct {
+ CatalogMode string `json:"catalog_mode"`
+ AllowedToolkits []string `json:"allowed_toolkits"`
+ }
+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
+ writeError(w, http.StatusBadRequest, "invalid request body")
+ return
+ }
+ switch req.CatalogMode {
+ case connectedapps.CatalogAll, connectedapps.CatalogCurated, connectedapps.CatalogCustom:
+ default:
+ writeError(w, http.StatusBadRequest, "catalog_mode must be all, curated or custom")
+ return
+ }
+ allowed := []string{}
+ seen := map[string]bool{}
+ for _, raw := range req.AllowedToolkits {
+ slug := connectedapps.NormalizeSlug(raw)
+ if slug == "" || seen[slug] {
+ continue
+ }
+ seen[slug] = true
+ allowed = append(allowed, slug)
+ }
+ if len(allowed) > maxAllowedToolkits {
+ writeError(w, http.StatusBadRequest, "too many apps in the list")
+ return
+ }
+ row, err := h.Queries.UpsertWorkspaceAppSetting(r.Context(), db.UpsertWorkspaceAppSettingParams{
+ WorkspaceID: workspaceID, CatalogMode: req.CatalogMode, AllowedToolkits: allowed, UpdatedBy: member.UserID,
+ })
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to save settings")
+ return
+ }
+ writeJSON(w, http.StatusOK, map[string]any{"catalog_mode": row.CatalogMode, "allowed_toolkits": row.AllowedToolkits})
+}
+
+// ruleScope resolves whose rules a request reads or writes: the team account
+// (owner NULL) or the caller's personal account.
+func ruleScope(r *http.Request, member db.Member) (string, pgtype.UUID, bool) {
+ switch r.URL.Query().Get("scope") {
+ case connectedapps.ScopeTeam:
+ return connectedapps.ScopeTeam, pgtype.UUID{}, true
+ case connectedapps.ScopePersonal:
+ return connectedapps.ScopePersonal, member.UserID, true
+ }
+ return "", pgtype.UUID{}, false
+}
+
+func (h *Handler) rulesResponse(ctx context.Context, workspaceID pgtype.UUID, slug string, owner pgtype.UUID) ([]AppRuleResponse, error) {
+ rows, err := h.Queries.ListAppActionRules(ctx, db.ListAppActionRulesParams{WorkspaceID: workspaceID, ToolkitSlug: slug, OwnerUserID: owner})
+ if err != nil {
+ return nil, err
+ }
+ set := map[string]string{}
+ for _, row := range rows {
+ set[row.ActionClass] = row.Policy
+ }
+ out := make([]AppRuleResponse, 0, len(connectedapps.Classes))
+ for _, class := range connectedapps.Classes {
+ def := connectedapps.DefaultPolicy(slug, class)
+ policy, custom := set[class]
+ if !custom {
+ policy = def
+ }
+ out = append(out, AppRuleResponse{ActionClass: class, Policy: policy, DefaultPolicy: def, Custom: custom})
+ }
+ return out, nil
+}
+
+// GetAppRules (GET /api/apps/rules?toolkit_slug=&scope=team|personal).
+func (h *Handler) GetAppRules(w http.ResponseWriter, r *http.Request) {
+ if !h.appsReady(w, r) {
+ return
+ }
+ member, workspaceID, _, ok := h.appsMember(w, r)
+ if !ok {
+ return
+ }
+ _, owner, ok := ruleScope(r, member)
+ if !ok {
+ writeError(w, http.StatusBadRequest, "scope must be team or personal")
+ return
+ }
+ slug := connectedapps.NormalizeSlug(r.URL.Query().Get("toolkit_slug"))
+ rules, err := h.rulesResponse(r.Context(), workspaceID, slug, owner)
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to list rules")
+ return
+ }
+ writeJSON(w, http.StatusOK, map[string]any{"rules": rules})
+}
+
+// UpdateAppRules (PUT /api/apps/rules?toolkit_slug=&scope=) replaces the
+// rules of one account. Team rules need an admin; personal rules are the
+// caller's own.
+func (h *Handler) UpdateAppRules(w http.ResponseWriter, r *http.Request) {
+ if !h.appsReady(w, r) {
+ return
+ }
+ member, workspaceID, isAdmin, ok := h.appsMember(w, r)
+ if !ok {
+ return
+ }
+ scope, owner, ok := ruleScope(r, member)
+ if !ok {
+ writeError(w, http.StatusBadRequest, "scope must be team or personal")
+ return
+ }
+ if scope == connectedapps.ScopeTeam && !isAdmin {
+ writeError(w, http.StatusForbidden, "only workspace admins can change team account rules")
+ return
+ }
+ slug := connectedapps.NormalizeSlug(r.URL.Query().Get("toolkit_slug"))
+ if slug == "" {
+ writeError(w, http.StatusBadRequest, "toolkit_slug is required")
+ return
+ }
+ var req struct {
+ Rules []struct {
+ ActionClass string `json:"action_class"`
+ Policy string `json:"policy"`
+ } `json:"rules"`
+ }
+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
+ writeError(w, http.StatusBadRequest, "invalid request body")
+ return
+ }
+ for _, rule := range req.Rules {
+ if !connectedapps.ValidClass(rule.ActionClass) || !connectedapps.ValidPolicy(rule.Policy) {
+ writeError(w, http.StatusBadRequest, "invalid rule")
+ return
+ }
+ }
+ for _, rule := range req.Rules {
+ if _, err := h.Queries.UpsertAppActionRule(r.Context(), db.UpsertAppActionRuleParams{
+ WorkspaceID: workspaceID, OwnerUserID: owner, ToolkitSlug: slug,
+ ActionClass: rule.ActionClass, Policy: rule.Policy, UpdatedBy: member.UserID,
+ }); err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to save rules")
+ return
+ }
+ }
+ rules, err := h.rulesResponse(r.Context(), workspaceID, slug, owner)
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to list rules")
+ return
+ }
+ writeJSON(w, http.StatusOK, map[string]any{"rules": rules})
+}
+
+// ListAppActivity (GET /api/apps/activity?toolkit_slug=&scope=) lists recent
+// calls through one account. Team activity is for admins; personal activity
+// for its owner.
+func (h *Handler) ListAppActivity(w http.ResponseWriter, r *http.Request) {
+ if !h.appsReady(w, r) {
+ return
+ }
+ member, workspaceID, isAdmin, ok := h.appsMember(w, r)
+ if !ok {
+ return
+ }
+ scope, owner, ok := ruleScope(r, member)
+ if !ok {
+ writeError(w, http.StatusBadRequest, "scope must be team or personal")
+ return
+ }
+ slug := connectedapps.NormalizeSlug(r.URL.Query().Get("toolkit_slug"))
+ limit := int32(50)
+ if v, err := strconv.Atoi(r.URL.Query().Get("limit")); err == nil && v > 0 && v <= 200 {
+ limit = int32(v)
+ }
+ var rows []db.AppToolCall
+ var err error
+ if scope == connectedapps.ScopeTeam {
+ if !isAdmin {
+ writeError(w, http.StatusForbidden, "insufficient permissions")
+ return
+ }
+ rows, err = h.Queries.ListTeamAppToolCalls(r.Context(), db.ListTeamAppToolCallsParams{WorkspaceID: workspaceID, ToolkitSlug: slug, Limit: limit})
+ } else {
+ rows, err = h.Queries.ListPersonalAppToolCalls(r.Context(), db.ListPersonalAppToolCallsParams{WorkspaceID: workspaceID, ToolkitSlug: slug, AccountOwnerUserID: owner, Limit: limit})
+ }
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to list activity")
+ return
+ }
+ out := make([]AppToolCallResponse, 0, len(rows))
+ for _, row := range rows {
+ out = append(out, AppToolCallResponse{
+ ID: uuidToString(row.ID), AgentID: uuidToString(row.AgentID),
+ IssueID: uuidToPtr(row.IssueID), ChatSessionID: uuidToPtr(row.ChatSessionID), TriggeredBy: uuidToPtr(row.TriggeredBy),
+ ToolSlug: row.ToolSlug, ActionClass: row.ActionClass, Outcome: row.Outcome,
+ Error: textToPtr(row.Error), CreatedAt: timestampToString(row.CreatedAt),
+ })
+ }
+ writeJSON(w, http.StatusOK, map[string]any{"calls": out})
+}
+
+// ListAppTools (GET /api/apps/tools?toolkit_slug=) lists an app's tools and
+// how each is classified in this workspace.
+func (h *Handler) ListAppTools(w http.ResponseWriter, r *http.Request) {
+ if !h.appsReady(w, r) {
+ return
+ }
+ _, workspaceID, _, ok := h.appsMember(w, r)
+ if !ok {
+ return
+ }
+ slug := connectedapps.NormalizeSlug(r.URL.Query().Get("toolkit_slug"))
+ if slug == "" {
+ writeError(w, http.StatusBadRequest, "toolkit_slug is required")
+ return
+ }
+ tools, err := h.Composio.ListToolkitTools(r.Context(), slug)
+ if err != nil {
+ slog.Warn("apps tools failed", append(logger.RequestAttrs(r), "error", err)...)
+ writeError(w, http.StatusBadGateway, "failed to load tools")
+ return
+ }
+ overrides := h.ConnectedApps.ClassOverrides(r.Context(), workspaceID, slug)
+ out := make([]AppToolResponse, 0, len(tools))
+ for _, t := range tools {
+ auto := connectedapps.Classify(slug, t.Slug, t.Tags)
+ class, overridden := overrides[strings.ToUpper(t.Slug)]
+ if !overridden {
+ class = auto
+ }
+ out = append(out, AppToolResponse{
+ Slug: t.Slug, Name: t.Name, Description: t.Description,
+ AutoClass: auto, Class: class, Overridden: overridden,
+ })
+ }
+ writeJSON(w, http.StatusOK, map[string]any{"tools": out})
+}
+
+// UpdateAppToolClass (PUT /api/apps/tools/class) corrects how one tool is
+// classified in this workspace; an empty class restores the automatic one.
+// Admins only, since the class decides what every account's rules apply.
+func (h *Handler) UpdateAppToolClass(w http.ResponseWriter, r *http.Request) {
+ if !h.appsReady(w, r) {
+ return
+ }
+ member, workspaceID, isAdmin, ok := h.appsMember(w, r)
+ if !ok {
+ return
+ }
+ if !isAdmin {
+ writeError(w, http.StatusForbidden, "only workspace admins can change how tools are classified")
+ return
+ }
+ var req struct {
+ ToolkitSlug string `json:"toolkit_slug"`
+ ToolSlug string `json:"tool_slug"`
+ ActionClass string `json:"action_class"`
+ }
+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
+ writeError(w, http.StatusBadRequest, "invalid request body")
+ return
+ }
+ slug := connectedapps.NormalizeSlug(req.ToolkitSlug)
+ tool := strings.ToUpper(strings.TrimSpace(req.ToolSlug))
+ if slug == "" || tool == "" {
+ writeError(w, http.StatusBadRequest, "toolkit_slug and tool_slug are required")
+ return
+ }
+ var err error
+ if req.ActionClass == "" {
+ err = h.Queries.DeleteAppToolClassOverride(r.Context(), db.DeleteAppToolClassOverrideParams{
+ WorkspaceID: workspaceID, ToolkitSlug: slug, ToolSlug: tool,
+ })
+ } else {
+ if !connectedapps.ValidClass(req.ActionClass) {
+ writeError(w, http.StatusBadRequest, "invalid action_class")
+ return
+ }
+ err = h.Queries.UpsertAppToolClassOverride(r.Context(), db.UpsertAppToolClassOverrideParams{
+ WorkspaceID: workspaceID, ToolkitSlug: slug, ToolSlug: tool,
+ ActionClass: req.ActionClass, UpdatedBy: member.UserID,
+ })
+ }
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to save")
+ return
+ }
+ w.WriteHeader(http.StatusNoContent)
+}
+
+// ListIssueAppCalls (GET /api/app-calls?issue_id=) lists the app calls an
+// issue's runs made, for the call chips and the issue sidebar.
+func (h *Handler) ListIssueAppCalls(w http.ResponseWriter, r *http.Request) {
+ if !h.appsReady(w, r) {
+ return
+ }
+ member, workspaceID, _, ok := h.appsMember(w, r)
+ if !ok {
+ return
+ }
+ issue, ok := h.loadIssueForUser(w, r, r.URL.Query().Get("issue_id"))
+ if !ok {
+ return
+ }
+ rows, err := h.Queries.ListIssueAppToolCalls(r.Context(), db.ListIssueAppToolCallsParams{WorkspaceID: workspaceID, IssueID: issue.ID})
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to list calls")
+ return
+ }
+ out := make([]IssueAppCallResponse, 0, len(rows))
+ for _, row := range rows {
+ call := IssueAppCallResponse{
+ ID: uuidToString(row.ID), TaskID: uuidToPtr(row.TaskID), AgentID: uuidToString(row.AgentID),
+ AccountScope: row.AccountScope, AccountOwnerUserID: uuidToPtr(row.AccountOwnerUserID),
+ ToolkitSlug: row.ToolkitSlug, ToolSlug: row.ToolSlug, ActionClass: row.ActionClass,
+ Outcome: row.Outcome, RequestID: uuidToPtr(row.RequestID), CreatedAt: timestampToString(row.CreatedAt),
+ }
+ if row.AccountOwnerUserID == member.UserID {
+ call.Error = textToPtr(row.Error)
+ }
+ out = append(out, call)
+ }
+ writeJSON(w, http.StatusOK, map[string]any{"calls": out})
+}
+
+// ListAgentApps (GET /api/agents/{id}/apps).
+func (h *Handler) ListAgentApps(w http.ResponseWriter, r *http.Request) {
+ if !h.appsReady(w, r) {
+ return
+ }
+ agent, ok := h.loadAgentForUser(w, r, chi.URLParam(r, "id"))
+ if !ok {
+ return
+ }
+ rows, err := h.Queries.ListAgentApps(r.Context(), agent.ID)
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to list agent apps")
+ return
+ }
+ out := make([]AgentAppResponse, 0, len(rows))
+ for _, row := range rows {
+ out = append(out, agentAppResponse(row))
+ }
+ writeJSON(w, http.StatusOK, map[string]any{"apps": out})
+}
+
+// UpdateAgentApps (PUT /api/agents/{id}/apps) replaces an agent's apps. The
+// agent's manager may attach personal-account apps; team-account apps act as
+// the whole workspace, so adding or changing one needs an admin.
+func (h *Handler) UpdateAgentApps(w http.ResponseWriter, r *http.Request) {
+ if !h.appsReady(w, r) {
+ return
+ }
+ agent, ok := h.loadAgentForUser(w, r, chi.URLParam(r, "id"))
+ if !ok {
+ return
+ }
+ if !h.canManageAgent(w, r, agent) {
+ return
+ }
+ member, workspaceID, isAdmin, ok := h.appsMember(w, r)
+ if !ok {
+ return
+ }
+ var req struct {
+ Apps []struct {
+ ToolkitSlug string `json:"toolkit_slug"`
+ AccountScope string `json:"account_scope"`
+ Level string `json:"level"`
+ } `json:"apps"`
+ }
+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
+ writeError(w, http.StatusBadRequest, "invalid request body")
+ return
+ }
+ ctx := r.Context()
+ existing, err := h.Queries.ListAgentApps(ctx, agent.ID)
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to list agent apps")
+ return
+ }
+ current := map[string]db.AgentApp{}
+ for _, row := range existing {
+ current[row.ToolkitSlug] = row
+ }
+ catalog := h.ConnectedApps.Catalog(ctx, workspaceID)
+ keep := []string{}
+ seen := map[string]bool{}
+ type want struct{ slug, scope, level string }
+ var wants []want
+ for _, app := range req.Apps {
+ slug := connectedapps.NormalizeSlug(app.ToolkitSlug)
+ if slug == "" || seen[slug] || !connectedapps.ValidScope(app.AccountScope) || !connectedapps.ValidLevel(app.Level) {
+ writeError(w, http.StatusBadRequest, "invalid app")
+ return
+ }
+ seen[slug] = true
+ prev, had := current[slug]
+ changed := !had || prev.AccountScope != app.AccountScope || prev.Level != app.Level
+ if changed && !catalog.Allows(slug) {
+ writeError(w, http.StatusForbidden, "this workspace does not allow this app")
+ return
+ }
+ touchesTeam := app.AccountScope == connectedapps.ScopeTeam || (had && prev.AccountScope == connectedapps.ScopeTeam)
+ if changed && touchesTeam && !isAdmin {
+ writeError(w, http.StatusForbidden, "only workspace admins can give agents a team account")
+ return
+ }
+ keep = append(keep, slug)
+ wants = append(wants, want{slug, app.AccountScope, app.Level})
+ }
+ if !isAdmin {
+ for slug, row := range current {
+ if row.AccountScope == connectedapps.ScopeTeam && !seen[slug] {
+ writeError(w, http.StatusForbidden, "only workspace admins can remove a team account from an agent")
+ return
+ }
+ }
+ }
+ tx, err := h.TxStarter.Begin(ctx)
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to save agent apps")
+ return
+ }
+ defer tx.Rollback(ctx)
+ qtx := h.Queries.WithTx(tx)
+ if err := qtx.DeleteAgentAppsExcept(ctx, db.DeleteAgentAppsExceptParams{AgentID: agent.ID, Keep: keep}); err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to save agent apps")
+ return
+ }
+ for _, wnt := range wants {
+ if _, err := qtx.UpsertAgentApp(ctx, db.UpsertAgentAppParams{
+ WorkspaceID: agent.WorkspaceID, AgentID: agent.ID, ToolkitSlug: wnt.slug,
+ AccountScope: wnt.scope, Level: wnt.level, CreatedBy: member.UserID,
+ }); err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to save agent apps")
+ return
+ }
+ }
+ if err := qtx.SetAgentComposioToolkitAllowlist(ctx, db.SetAgentComposioToolkitAllowlistParams{ID: agent.ID, Slugs: keep}); err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to save agent apps")
+ return
+ }
+ if err := tx.Commit(ctx); err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to save agent apps")
+ return
+ }
+ h.ListAgentApps(w, r)
+}
+
+// syncAgentAppsFromAllowlist mirrors a write through the legacy
+// composio_toolkit_allowlist field into agent_app: new slugs join as personal
+// apps at the default level, missing slugs leave, existing ones keep their
+// scope and level.
+func syncAgentAppsFromAllowlist(ctx context.Context, q *db.Queries, agent db.Agent, slugs []string, actorID pgtype.UUID) error {
+ existing, err := q.ListAgentApps(ctx, agent.ID)
+ if err != nil {
+ return err
+ }
+ have := map[string]bool{}
+ for _, row := range existing {
+ have[row.ToolkitSlug] = true
+ }
+ keep := []string{}
+ for _, s := range slugs {
+ slug := connectedapps.NormalizeSlug(s)
+ if slug == "" {
+ continue
+ }
+ keep = append(keep, slug)
+ if have[slug] {
+ continue
+ }
+ if _, err := q.UpsertAgentApp(ctx, db.UpsertAgentAppParams{
+ WorkspaceID: agent.WorkspaceID, AgentID: agent.ID, ToolkitSlug: slug,
+ AccountScope: connectedapps.ScopePersonal, Level: connectedapps.DefaultLevel(agent.PermissionMode), CreatedBy: actorID,
+ }); err != nil {
+ return err
+ }
+ }
+ return q.DeleteAgentAppsExcept(ctx, db.DeleteAgentAppsExceptParams{AgentID: agent.ID, Keep: keep})
+}
+
+func (h *Handler) requestResponse(req db.AppActionRequest, viewer pgtype.UUID) AppRequestResponse {
+ out := AppRequestResponse{
+ ID: uuidToString(req.ID), Kind: req.Kind, Status: req.Status, AgentID: uuidToString(req.AgentID),
+ IssueID: uuidToPtr(req.IssueID), ChatSessionID: uuidToPtr(req.ChatSessionID),
+ ApproverUserID: uuidToString(req.ApproverUserID), AccountScope: req.AccountScope,
+ ToolkitSlug: req.ToolkitSlug, ToolSlug: req.ToolSlug, ActionClass: req.ActionClass, Summary: req.Summary,
+ Error: textToPtr(req.Error), Reason: textToPtr(req.Reason),
+ ExpiresAt: timestampToString(req.ExpiresAt), DecidedBy: uuidToPtr(req.DecidedBy),
+ DecidedAt: timestampToPtr(req.DecidedAt), CreatedAt: timestampToString(req.CreatedAt),
+ }
+ if req.ApproverUserID == viewer {
+ out.Arguments = json.RawMessage(req.Arguments)
+ if len(req.ApprovedArguments) > 0 {
+ out.ApprovedArguments = json.RawMessage(req.ApprovedArguments)
+ }
+ if len(req.Result) > 0 {
+ out.Result = json.RawMessage(req.Result)
+ }
+ } else {
+ out.Redacted = true
+ out.Error = nil
+ }
+ return out
+}
+
+// ListAppRequests (GET /api/app-requests?issue_id= | chat_session_id= |
+// pending=mine). Issue requests follow issue visibility; chat requests are
+// the chat creator's.
+func (h *Handler) ListAppRequests(w http.ResponseWriter, r *http.Request) {
+ if !h.appsReady(w, r) {
+ return
+ }
+ member, workspaceID, _, ok := h.appsMember(w, r)
+ if !ok {
+ return
+ }
+ ctx := r.Context()
+ q := r.URL.Query()
+ var before pgtype.Timestamptz
+ if raw := q.Get("before"); raw != "" {
+ t, err := time.Parse(time.RFC3339Nano, raw)
+ if err != nil {
+ writeError(w, http.StatusBadRequest, "invalid before")
+ return
+ }
+ before = pgtype.Timestamptz{Time: t, Valid: true}
+ }
+ // The first page carries every pending request plus the newest decided
+ // ones; `before` pages back through decided history only, so a long
+ // history never pushes a pending request out of the list.
+ var pending, decided []db.AppActionRequest
+ var err error
+ switch {
+ case q.Get("issue_id") != "":
+ issue, ok := h.loadIssueForUser(w, r, q.Get("issue_id"))
+ if !ok {
+ return
+ }
+ if !before.Valid {
+ pending, err = h.Queries.ListPendingAppActionRequestsForIssue(ctx, db.ListPendingAppActionRequestsForIssueParams{WorkspaceID: workspaceID, IssueID: issue.ID})
+ }
+ if err == nil {
+ decided, err = h.Queries.ListDecidedAppActionRequestsForIssue(ctx, db.ListDecidedAppActionRequestsForIssueParams{
+ WorkspaceID: workspaceID, IssueID: issue.ID, Before: before, PageSize: appRequestPageSize,
+ })
+ }
+ case q.Get("chat_session_id") != "":
+ sessionID, ok := parseUUIDOrBadRequest(w, q.Get("chat_session_id"), "chat_session_id")
+ if !ok {
+ return
+ }
+ session, serr := h.Queries.GetChatSession(ctx, sessionID)
+ if serr != nil || session.WorkspaceID != workspaceID || session.CreatorID != member.UserID {
+ writeError(w, http.StatusNotFound, "chat session not found")
+ return
+ }
+ if !before.Valid {
+ pending, err = h.Queries.ListPendingAppActionRequestsForChatSession(ctx, db.ListPendingAppActionRequestsForChatSessionParams{WorkspaceID: workspaceID, ChatSessionID: sessionID})
+ }
+ if err == nil {
+ decided, err = h.Queries.ListDecidedAppActionRequestsForChatSession(ctx, db.ListDecidedAppActionRequestsForChatSessionParams{
+ WorkspaceID: workspaceID, ChatSessionID: sessionID, Before: before, PageSize: appRequestPageSize,
+ })
+ }
+ default:
+ pending, err = h.Queries.ListPendingAppActionRequestsForApprover(ctx, db.ListPendingAppActionRequestsForApproverParams{WorkspaceID: workspaceID, ApproverUserID: member.UserID})
+ }
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to list requests")
+ return
+ }
+ var nextBefore *string
+ if len(decided) == appRequestPageSize {
+ cursor := decided[len(decided)-1].CreatedAt.Time.UTC().Format(time.RFC3339Nano)
+ nextBefore = &cursor
+ }
+ out := make([]AppRequestResponse, 0, len(pending)+len(decided))
+ // Decided rows arrive newest first; the list reads oldest first.
+ for i := len(decided) - 1; i >= 0; i-- {
+ out = append(out, h.requestResponse(decided[i], member.UserID))
+ }
+ for _, row := range pending {
+ out = append(out, h.requestResponse(row, member.UserID))
+ }
+ writeJSON(w, http.StatusOK, map[string]any{"requests": out, "next_before": nextBefore})
+}
+
+// appRequestPageSize is how many decided requests one list page carries.
+const appRequestPageSize = 50
+
+func writeDecisionError(w http.ResponseWriter, err error) {
+ switch {
+ case errors.Is(err, connectedapps.ErrRequestNotFound):
+ writeError(w, http.StatusNotFound, "request not found")
+ case errors.Is(err, connectedapps.ErrNotApprover):
+ writeError(w, http.StatusForbidden, "only the person asked can decide")
+ case errors.Is(err, connectedapps.ErrNotPending):
+ writeError(w, http.StatusConflict, "request is no longer pending")
+ case errors.Is(err, connectedapps.ErrAccountMissing):
+ writeError(w, http.StatusConflict, "connect the account first")
+ case errors.Is(err, connectedapps.ErrNoLongerAllowed):
+ writeError(w, http.StatusForbidden, "you can no longer use this agent; the request was withdrawn")
+ case errors.Is(err, connectedapps.ErrRateLimited):
+ writeError(w, http.StatusTooManyRequests, "this account reached its per-minute call limit; approve again in a minute")
+ default:
+ writeError(w, http.StatusInternalServerError, "failed to decide")
+ }
+}
+
+// ApproveAppRequest (POST /api/app-requests/{id}/approve). The approver may
+// send edited arguments; Multica runs the call and resumes the agent.
+func (h *Handler) ApproveAppRequest(w http.ResponseWriter, r *http.Request) {
+ if !h.appsReady(w, r) {
+ return
+ }
+ member, workspaceID, _, ok := h.appsMember(w, r)
+ if !ok {
+ return
+ }
+ id, ok := parseUUIDOrBadRequest(w, chi.URLParam(r, "id"), "request id")
+ if !ok {
+ return
+ }
+ var req struct {
+ Arguments map[string]any `json:"arguments"`
+ }
+ if r.ContentLength != 0 {
+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
+ writeError(w, http.StatusBadRequest, "invalid request body")
+ return
+ }
+ }
+ row, err := h.ConnectedApps.Approve(r.Context(), workspaceID, member.UserID, id, req.Arguments)
+ if err != nil {
+ writeDecisionError(w, err)
+ return
+ }
+ writeJSON(w, http.StatusOK, h.requestResponse(row, member.UserID))
+}
+
+// RejectAppRequest (POST /api/app-requests/{id}/reject).
+func (h *Handler) RejectAppRequest(w http.ResponseWriter, r *http.Request) {
+ if !h.appsReady(w, r) {
+ return
+ }
+ member, workspaceID, _, ok := h.appsMember(w, r)
+ if !ok {
+ return
+ }
+ id, ok := parseUUIDOrBadRequest(w, chi.URLParam(r, "id"), "request id")
+ if !ok {
+ return
+ }
+ var req struct {
+ Reason string `json:"reason"`
+ }
+ if r.ContentLength != 0 {
+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
+ writeError(w, http.StatusBadRequest, "invalid request body")
+ return
+ }
+ }
+ row, err := h.ConnectedApps.Reject(r.Context(), workspaceID, member.UserID, id, req.Reason)
+ if err != nil {
+ writeDecisionError(w, err)
+ return
+ }
+ writeJSON(w, http.StatusOK, h.requestResponse(row, member.UserID))
+}
+
+// AppsGateway (POST /api/apps/mcp) is the MCP endpoint runs reach their apps
+// through. It authenticates with the run's bearer token, not a session.
+func (h *Handler) AppsGateway(w http.ResponseWriter, r *http.Request) {
+ if h.ConnectedApps == nil || !h.composioMCPAppsEnabled(r.Context()) {
+ http.Error(w, "connected apps are not configured", http.StatusServiceUnavailable)
+ return
+ }
+ h.ConnectedApps.ServeHTTP(w, r)
+}
+
+// ResumeAfterDecision implements connectedapps.Resumer: a run on the issue,
+// or a message in the chat from the person who decided.
+// CanActFor applies the rule that admits a new run of the agent to the
+// person a request waits on, so a decision never runs or resumes an agent
+// they could not start themselves.
+func (h *Handler) CanActFor(ctx context.Context, workspaceID, agentID, userID pgtype.UUID) bool {
+ agent, err := h.Queries.GetAgent(ctx, agentID)
+ if err != nil || agent.WorkspaceID != workspaceID || agent.ArchivedAt.Valid {
+ return false
+ }
+ uid := uuidToString(userID)
+ return h.canInvokeAgent(ctx, agent, "member", uid, uid, uuidToString(workspaceID))
+}
+
+func (h *Handler) ResumeAfterDecision(ctx context.Context, req db.AppActionRequest, actorID pgtype.UUID, note string) error {
+ if req.IssueID.Valid {
+ return h.TaskService.EnqueueAppDecisionRun(ctx, req.IssueID, req.AgentID, actorID, req.ID, note)
+ }
+ if !req.ChatSessionID.Valid {
+ return nil
+ }
+ session, err := h.Queries.GetChatSession(ctx, req.ChatSessionID)
+ if err != nil {
+ return err
+ }
+ agent, err := h.Queries.GetAgent(ctx, session.AgentID)
+ if err != nil {
+ return err
+ }
+ content := "[Multica] " + strings.TrimSpace(note)
+ sent, err := h.TaskService.SendDirectChatMessage(ctx, session, agent, actorID, content, nil, "member", actorID)
+ if err != nil {
+ return err
+ }
+ workspaceID := uuidToString(session.WorkspaceID)
+ sessionID := uuidToString(session.ID)
+ h.publishChat(protocol.EventChatMessage, workspaceID, "member", uuidToString(actorID), sessionID, protocol.ChatMessagePayload{
+ ChatSessionID: sessionID,
+ MessageID: uuidToString(sent.Message.ID),
+ Role: "user",
+ Content: content,
+ TaskID: uuidToString(sent.Task.ID),
+ CreatedAt: timestampToString(sent.Message.CreatedAt),
+ })
+ return nil
+}
diff --git a/server/internal/handler/connected_apps_boundary_test.go b/server/internal/handler/connected_apps_boundary_test.go
new file mode 100644
index 0000000000..3c8e0989ec
--- /dev/null
+++ b/server/internal/handler/connected_apps_boundary_test.go
@@ -0,0 +1,334 @@
+package handler
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/go-chi/chi/v5"
+ "github.com/jackc/pgx/v5/pgtype"
+ "github.com/multica-ai/multica/server/internal/auth"
+ "github.com/multica-ai/multica/server/internal/middleware"
+ sdk "github.com/multica-ai/multica/server/pkg/composio"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+)
+
+func (f *appsFixture) submitSend(t *testing.T) AppRequestResponse {
+ t.Helper()
+ f.putAgentApps(t, testUserID, []map[string]string{{"toolkit_slug": "gmail", "account_scope": "personal", "level": "confirm_writes"}})
+ _, response, isErr := f.gateway(t, f.token(t), "apps_run_tool", map[string]any{"tool": "GMAIL_SEND_EMAIL", "arguments": map[string]any{"to": "[email protected]"}})
+ if isErr || !strings.HasPrefix(response, "submitted") {
+ t.Fatalf("submit: %s", response)
+ }
+ requests := f.listRequests(t, testUserID)
+ if len(requests) != 1 {
+ t.Fatalf("requests: %d", len(requests))
+ }
+ return requests[0]
+}
+
+func (f *appsFixture) requestStatus(t *testing.T, id string) string {
+ t.Helper()
+ var status string
+ if err := testPool.QueryRow(context.Background(), `SELECT status FROM app_action_request WHERE id = $1`, id).Scan(&status); err != nil {
+ t.Fatal(err)
+ }
+ return status
+}
+
+// A run's credential acts as its owner, but must not approve its own calls,
+// rewrite the owner's rules, or read the owner's requests.
+func TestConnectedApps_RunCredentialIsNotAPerson(t *testing.T) {
+ f := newAppsFixture(t)
+ req := f.submitSend(t)
+ token := "mat_apps_boundary_" + f.taskID
+ if _, err := f.h.Queries.CreateTaskToken(context.Background(), db.CreateTaskTokenParams{
+ TokenHash: auth.HashToken(token), TaskID: parseUUID(f.taskID), AgentID: parseUUID(f.agentID),
+ WorkspaceID: parseUUID(testWorkspaceID), UserID: parseUUID(testUserID),
+ ExpiresAt: pgtype.Timestamptz{Time: time.Now().Add(time.Hour), Valid: true},
+ }); err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { f.h.Queries.DeleteTaskTokensByTask(context.Background(), parseUUID(f.taskID)) })
+
+ router := chi.NewRouter()
+ router.Use(middleware.Auth(f.h.Queries, nil, nil, nil))
+ router.Use(middleware.RequireWorkspaceMember(f.h.Queries))
+ router.Post("/api/app-requests/{id}/approve", f.h.ApproveAppRequest)
+ router.Get("/api/app-requests", f.h.ListAppRequests)
+ router.Put("/api/apps/rules", f.h.UpdateAppRules)
+ send := func(method, path, body string) int {
+ r := httptest.NewRequest(method, path, strings.NewReader(body))
+ r.Header.Set("Authorization", "Bearer "+token)
+ w := httptest.NewRecorder()
+ router.ServeHTTP(w, r)
+ return w.Code
+ }
+
+ if code := send(http.MethodPost, "/api/app-requests/"+req.ID+"/approve", ""); code != http.StatusForbidden {
+ t.Errorf("run credential approved its own call: HTTP %d, executions=%d", code, len(f.sdk.executions()))
+ }
+ if n := len(f.sdk.executions()); n != 0 {
+ t.Errorf("executions = %d, want 0", n)
+ }
+ if code := send(http.MethodPut, "/api/apps/rules?toolkit_slug=gmail&scope=personal", `{"rules":[{"action_class":"send","policy":"allow"}]}`); code != http.StatusForbidden {
+ t.Errorf("run credential changed the owner's send rule: HTTP %d", code)
+ }
+ if code := send(http.MethodGet, "/api/app-requests?issue_id="+f.issueID, ""); code != http.StatusForbidden {
+ t.Errorf("run credential read the owner's requests: HTTP %d", code)
+ }
+ if got := f.requestStatus(t, req.ID); got != "pending" {
+ t.Errorf("request status = %s, want pending", got)
+ }
+}
+
+// Leaving the workspace withdraws what waited on the member; connecting the
+// app afterwards resumes nothing there.
+func TestConnectedApps_DepartedMemberCannotResumeOnConnect(t *testing.T) {
+ f := newAppsFixture(t)
+ ctx := context.Background()
+ f.putAgentApps(t, testUserID, []map[string]string{{"toolkit_slug": "gmail", "account_scope": "personal", "level": "write"}})
+ if _, err := testPool.Exec(ctx, `UPDATE agent_task_queue SET originator_user_id=$1, accountable_user_id=$1 WHERE id=$2`, f.member, f.taskID); err != nil {
+ t.Fatal(err)
+ }
+ _, response, isErr := f.gateway(t, f.token(t), "apps_request_connection", map[string]any{"app": "gmail"})
+ if isErr || !strings.HasPrefix(response, "requested") {
+ t.Fatalf("request: %s", response)
+ }
+ var requestID string
+ if err := testPool.QueryRow(ctx, `SELECT id FROM app_action_request WHERE task_id=$1 AND kind='connect'`, f.taskID).Scan(&requestID); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := testPool.Exec(ctx, `UPDATE agent_task_queue SET status='completed', completed_at=now() WHERE id=$1`, f.taskID); err != nil {
+ t.Fatal(err)
+ }
+ member, err := f.h.Queries.GetMemberByUserAndWorkspace(ctx, db.GetMemberByUserAndWorkspaceParams{UserID: parseUUID(f.member), WorkspaceID: parseUUID(testWorkspaceID)})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err := f.h.revokeAndRemoveMember(ctx, member.WorkspaceID, member.UserID, member.ID, parseUUID(testUserID)); err != nil {
+ t.Fatal(err)
+ }
+ if got := f.requestStatus(t, requestID); got != "cancelled" {
+ t.Errorf("request after the member left = %s, want cancelled", got)
+ }
+ accountID := fmt.Sprintf("ca_departed_%s", f.member)
+ if _, err := f.h.Queries.UpsertUserComposioConnection(ctx, db.UpsertUserComposioConnectionParams{UserID: member.UserID, ToolkitSlug: "gmail", AuthConfigID: "ac_gmail", ConnectedAccountID: accountID, ComposioUserID: f.member}); err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() {
+ testPool.Exec(ctx, `DELETE FROM user_composio_connection WHERE connected_account_id=$1`, accountID)
+ })
+ f.h.ConnectedApps.ResolveConnectRequests(ctx, member.UserID, "gmail")
+ var queued int
+ if err := testPool.QueryRow(ctx, `SELECT count(*) FROM agent_task_queue WHERE issue_id=$1 AND status='queued' AND originator_user_id=$2`, f.issueID, f.member).Scan(&queued); err != nil {
+ t.Fatal(err)
+ }
+ if queued != 0 {
+ t.Errorf("OAuth completion queued %d runs in a workspace the member already left", queued)
+ }
+}
+
+// Access to the agent is checked again when deciding: a request whose
+// approver lost it is withdrawn instead of run.
+func TestConnectedApps_ApprovalRechecksAgentAccess(t *testing.T) {
+ f := newAppsFixture(t)
+ ctx := context.Background()
+ req := f.submitSend(t)
+ if !f.h.CanActFor(ctx, parseUUID(testWorkspaceID), parseUUID(f.agentID), parseUUID(testUserID)) {
+ t.Fatal("the agent's owner should be able to act for it")
+ }
+ if _, err := testPool.Exec(ctx, `UPDATE agent SET archived_at = now() WHERE id = $1`, f.agentID); err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { testPool.Exec(ctx, `UPDATE agent SET archived_at = NULL WHERE id = $1`, f.agentID) })
+ w := httptest.NewRecorder()
+ f.h.ApproveAppRequest(w, withURLParam(appsReqAs(t, testUserID, http.MethodPost, "/api/app-requests/"+req.ID+"/approve", nil), "id", req.ID))
+ if w.Code != http.StatusForbidden {
+ t.Fatalf("approve for an archived agent: %d %s", w.Code, w.Body.String())
+ }
+ if n := len(f.sdk.executions()); n != 0 {
+ t.Fatalf("executions = %d, want 0", n)
+ }
+ if got := f.requestStatus(t, req.ID); got != "cancelled" {
+ t.Fatalf("request = %s, want cancelled", got)
+ }
+}
+
+// Approving shares the account's per-minute budget with direct calls; an
+// approval over budget leaves the request pending to approve again.
+func TestConnectedApps_ApprovedCallsRespectRateLimit(t *testing.T) {
+ f := newAppsFixture(t)
+ req := f.submitSend(t)
+ if _, err := testPool.Exec(context.Background(), `INSERT INTO app_tool_call (workspace_id, agent_id, account_scope, account_owner_user_id, toolkit_slug, tool_slug, action_class, outcome) SELECT $1,$2,'personal',$3,'gmail','GMAIL_FETCH_EMAILS','read','ok' FROM generate_series(1,30)`, testWorkspaceID, f.agentID, testUserID); err != nil {
+ t.Fatal(err)
+ }
+ w := httptest.NewRecorder()
+ f.h.ApproveAppRequest(w, withURLParam(appsReqAs(t, testUserID, http.MethodPost, "/api/app-requests/"+req.ID+"/approve", nil), "id", req.ID))
+ if w.Code != http.StatusTooManyRequests {
+ t.Fatalf("approve over budget: %d %s", w.Code, w.Body.String())
+ }
+ if n := len(f.sdk.executions()); n != 0 {
+ t.Fatalf("approval executed %d provider calls over the account's budget", n)
+ }
+ if got := f.requestStatus(t, req.ID); got != "pending" {
+ t.Fatalf("request after a rate-limited approval = %s, want pending", got)
+ }
+}
+
+const notionUpdatePage = "NOTION_UPDATE_PAGE"
+
+// withNotionDeleteBlocked attaches Notion at level with the personal account's
+// delete rule set to block. NOTION_UPDATE_PAGE also takes archived=true, which
+// moves the page to trash.
+func (f *appsFixture) withNotionDeleteBlocked(t *testing.T, level string) {
+ t.Helper()
+ ctx := context.Background()
+ old := appsFakeGmailTools
+ appsFakeGmailTools = append(append([]sdk.Tool(nil), old...), sdk.Tool{
+ Slug: notionUpdatePage, Name: "Update Page", Toolkit: sdk.Toolkit{Slug: "notion"},
+ Description: "Update page properties, icon, cover, or archive status.",
+ })
+ t.Cleanup(func() { appsFakeGmailTools = old })
+ account := "ca_notion_" + f.taskID
+ if _, err := f.h.Queries.UpsertUserComposioConnection(ctx, db.UpsertUserComposioConnectionParams{
+ UserID: parseUUID(testUserID), ToolkitSlug: "notion", AuthConfigID: "ac_notion",
+ ConnectedAccountID: account, ComposioUserID: testUserID,
+ }); err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() {
+ testPool.Exec(ctx, `DELETE FROM user_composio_connection WHERE connected_account_id=$1`, account)
+ })
+ if w := f.putAgentApps(t, testUserID, []map[string]string{{"toolkit_slug": "notion", "account_scope": "personal", "level": level}}); w.Code != http.StatusOK {
+ t.Fatalf("attach: %d %s", w.Code, w.Body.String())
+ }
+ w := httptest.NewRecorder()
+ f.h.UpdateAppRules(w, appsReqAs(t, testUserID, http.MethodPut, "/api/apps/rules?toolkit_slug=notion&scope=personal", map[string]any{
+ "rules": []map[string]string{{"action_class": "delete", "policy": "block"}},
+ }))
+ if w.Code != http.StatusOK {
+ t.Fatalf("set delete rule: %d %s", w.Code, w.Body.String())
+ }
+}
+
+// Archiving through an update tool is a delete and obeys the delete rule;
+// ordinary edits and restores through the same tool still run.
+func TestConnectedApps_ArchiveViaUpdateObeysDeleteRule(t *testing.T) {
+ f := newAppsFixture(t)
+ f.withNotionDeleteBlocked(t, "write")
+ run := func(args map[string]any) (bool, string) {
+ _, response, isErr := f.gateway(t, f.token(t), "apps_run_tool", map[string]any{"tool": notionUpdatePage, "arguments": args})
+ return isErr, response
+ }
+ if isErr, response := run(map[string]any{"page_id": "p1", "archived": true}); !isErr || len(f.sdk.executions()) != 0 {
+ t.Fatalf("archive bypassed delete=block: isError=%v executions=%d response=%s", isErr, len(f.sdk.executions()), response)
+ }
+ if isErr, response := run(map[string]any{"page_id": "p1", "in_trash": "true"}); !isErr || len(f.sdk.executions()) != 0 {
+ t.Fatalf("in_trash bypassed delete=block: isError=%v response=%s", isErr, response)
+ }
+ if isErr, response := run(map[string]any{"page_id": "p1", "properties": map[string]any{"title": "Q3"}}); isErr {
+ t.Fatalf("plain edit refused: %s", response)
+ }
+ if isErr, response := run(map[string]any{"page_id": "p1", "archived": false}); isErr {
+ t.Fatalf("restore refused: %s", response)
+ }
+ if n := len(f.sdk.executions()); n != 2 {
+ t.Fatalf("executions = %d, want the edit and the restore", n)
+ }
+}
+
+// An approver who edits a confirmed update into an archive gets the delete
+// rule, not the class the request was submitted under.
+func TestConnectedApps_ApprovalWithEditedArchiveObeysDeleteRule(t *testing.T) {
+ f := newAppsFixture(t)
+ f.withNotionDeleteBlocked(t, "confirm_writes")
+ _, response, isErr := f.gateway(t, f.token(t), "apps_run_tool", map[string]any{
+ "tool": notionUpdatePage, "arguments": map[string]any{"page_id": "p1", "properties": map[string]any{"title": "Q3"}},
+ })
+ if isErr || !strings.HasPrefix(response, "submitted") {
+ t.Fatalf("submit: %s", response)
+ }
+ requests := f.listRequests(t, testUserID)
+ if len(requests) != 1 {
+ t.Fatalf("requests: %d", len(requests))
+ }
+ id := requests[0].ID
+ w := httptest.NewRecorder()
+ f.h.ApproveAppRequest(w, withURLParam(appsReqAs(t, testUserID, http.MethodPost, "/api/app-requests/"+id+"/approve", map[string]any{
+ "arguments": map[string]any{"page_id": "p1", "archived": true},
+ }), "id", id))
+ if n := len(f.sdk.executions()); n != 0 {
+ t.Fatalf("edited archive ran despite delete=block: HTTP %d executions=%d %s", w.Code, n, w.Body.String())
+ }
+ if got := f.requestStatus(t, id); got != "failed" {
+ t.Fatalf("request = %s, want failed", got)
+ }
+}
+
+// A long decided history never pushes a pending request out of the list;
+// the history pages back through `before`.
+func TestConnectedApps_PendingVisibleAfterHistoricalRequests(t *testing.T) {
+ f := newAppsFixture(t)
+ f.putAgentApps(t, testUserID, []map[string]string{{"toolkit_slug": "gmail", "account_scope": "personal", "level": "confirm_writes"}})
+ if _, err := testPool.Exec(context.Background(), `
+ INSERT INTO app_action_request (workspace_id, task_id, agent_id, issue_id, approver_user_id, account_scope, toolkit_slug, status, expires_at, created_at)
+ SELECT $1, $2, $3, $4, $5, 'personal', 'gmail', 'rejected', now()+interval '1 day', now()-interval '1 day'+(g * interval '1 second') FROM generate_series(1,200) g
+ `, testWorkspaceID, f.taskID, f.agentID, f.issueID, testUserID); err != nil {
+ t.Fatal(err)
+ }
+ _, response, isErr := f.gateway(t, f.token(t), "apps_run_tool", map[string]any{"tool": "GMAIL_SEND_EMAIL", "arguments": map[string]any{"to": "[email protected]"}})
+ if isErr || !strings.HasPrefix(response, "submitted") {
+ t.Fatalf("submit: %s", response)
+ }
+
+ type page struct {
+ Requests []AppRequestResponse `json:"requests"`
+ NextBefore *string `json:"next_before"`
+ }
+ list := func(query string) page {
+ w := httptest.NewRecorder()
+ f.h.ListAppRequests(w, appsReqAs(t, testUserID, http.MethodGet, "/api/app-requests?issue_id="+f.issueID+query, nil))
+ if w.Code != http.StatusOK {
+ t.Fatalf("list: %d %s", w.Code, w.Body.String())
+ }
+ var p page
+ json.Unmarshal(w.Body.Bytes(), &p)
+ return p
+ }
+ first := list("")
+ pending, decided := 0, 0
+ for _, r := range first.Requests {
+ if r.Status == "pending" {
+ pending++
+ } else {
+ decided++
+ }
+ }
+ if pending != 1 || decided != appRequestPageSize || first.NextBefore == nil {
+ t.Fatalf("first page: pending=%d decided=%d next=%v", pending, decided, first.NextBefore)
+ }
+ seen := decided
+ cursor := *first.NextBefore
+ for cursor != "" {
+ p := list("&before=" + cursor)
+ for _, r := range p.Requests {
+ if r.Status == "pending" {
+ t.Fatal("a history page repeated a pending request")
+ }
+ }
+ seen += len(p.Requests)
+ cursor = ""
+ if p.NextBefore != nil {
+ cursor = *p.NextBefore
+ }
+ }
+ if seen != 200 {
+ t.Fatalf("history pages carried %d decided requests, want 200", seen)
+ }
+}
diff --git a/server/internal/handler/connected_apps_test.go b/server/internal/handler/connected_apps_test.go
new file mode 100644
index 0000000000..5622878de1
--- /dev/null
+++ b/server/internal/handler/connected_apps_test.go
@@ -0,0 +1,596 @@
+package handler
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "fmt"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/multica-ai/multica/server/internal/connectedapps"
+ composio "github.com/multica-ai/multica/server/internal/integrations/composio"
+ "github.com/multica-ai/multica/server/internal/middleware"
+ "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"
+)
+
+// appsFakeSDK serves a small Gmail toolkit and records executions.
+type appsFakeSDK struct {
+ composioFakeSDK
+ mu sync.Mutex
+ executed []sdk.ExecuteToolRequest
+}
+
+var appsFakeGmailTools = []sdk.Tool{
+ {Slug: "GMAIL_FETCH_EMAILS", Name: "Fetch emails", Description: "List recent emails", Toolkit: sdk.Toolkit{Slug: "gmail"}},
+ {Slug: "GMAIL_SEND_EMAIL", Name: "Send email", Description: "Send an email", Toolkit: sdk.Toolkit{Slug: "gmail"}},
+ {Slug: "GMAIL_DELETE_MESSAGE", Name: "Delete message", Description: "Delete an email", Toolkit: sdk.Toolkit{Slug: "gmail"}},
+}
+
+func (f *appsFakeSDK) GetToolkit(_ context.Context, slug string) (*sdk.Toolkit, error) {
+ return &sdk.Toolkit{Slug: slug, Name: slug}, nil
+}
+
+func (f *appsFakeSDK) ListTools(_ context.Context, req sdk.ListToolsRequest) (*sdk.ListToolsResponse, error) {
+ if req.ToolkitSlug != "gmail" {
+ return &sdk.ListToolsResponse{}, nil
+ }
+ return &sdk.ListToolsResponse{Items: appsFakeGmailTools}, nil
+}
+
+func (f *appsFakeSDK) GetTool(_ context.Context, slug string) (*sdk.Tool, error) {
+ for i := range appsFakeGmailTools {
+ if appsFakeGmailTools[i].Slug == slug {
+ return &appsFakeGmailTools[i], nil
+ }
+ }
+ return nil, fmt.Errorf("tool %s not found", slug)
+}
+
+func (f *appsFakeSDK) ExecuteTool(_ context.Context, slug string, req sdk.ExecuteToolRequest) (*sdk.ExecuteToolResponse, error) {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ f.executed = append(f.executed, req)
+ return &sdk.ExecuteToolResponse{Successful: true, Data: map[string]any{"tool": slug}}, nil
+}
+
+func (f *appsFakeSDK) CreateManagedAuthConfig(_ context.Context, slug string) (string, error) {
+ return "ac_" + slug, nil
+}
+
+func (f *appsFakeSDK) executions() []sdk.ExecuteToolRequest {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ return append([]sdk.ExecuteToolRequest(nil), f.executed...)
+}
+
+type appsFixture struct {
+ h *Handler
+ sdk *appsFakeSDK
+ agentID string
+ issueID string
+ taskID string
+ member string
+}
+
+func newAppsFixture(t *testing.T) *appsFixture {
+ t.Helper()
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ fake := &appsFakeSDK{}
+ svc, err := composio.NewService(fake, testHandler.Queries, composio.Config{
+ StateSecret: []byte("apps-test-secret"),
+ CallbackBaseURL: "https://multica.ai",
+ FrontendBaseURL: "https://multica.ai",
+ })
+ if err != nil {
+ t.Fatalf("composio.NewService: %v", err)
+ }
+ h := *testHandler
+ h.Composio = svc
+ apps, err := connectedapps.New(connectedapps.Config{
+ Queries: h.Queries,
+ Composio: svc,
+ TokenSecret: connectedapps.DeriveTokenSecret([]byte("apps-test-secret")),
+ PublicBaseURL: "https://api.multica.test",
+ })
+ if err != nil {
+ t.Fatalf("connectedapps.New: %v", err)
+ }
+ apps.SetResumer(&h)
+ h.ConnectedApps = apps
+ withComposioMCPAppsFlag(t, &h, true)
+
+ agentID := createHandlerTestAgent(t, fmt.Sprintf("apps-agent-%d", testSeq.Add(1)), nil)
+ issueID := createTestIssue(t, "apps confirmation test", "todo", "medium")
+ t.Cleanup(func() { deleteTestIssue(t, issueID) })
+ taskID := createHandlerTestTaskForAgentOnIssue(t, agentID, issueID)
+ if _, err := testPool.Exec(context.Background(), `UPDATE agent_task_queue SET originator_user_id = $1, accountable_user_id = $1, originator_source = 'direct_human' WHERE id = $2`, testUserID, taskID); err != nil {
+ t.Fatalf("set originator: %v", err)
+ }
+
+ account := fmt.Sprintf("ca_apps_test_%d", testSeq.Add(1))
+ if _, err := testHandler.Queries.UpsertUserComposioConnection(context.Background(), db.UpsertUserComposioConnectionParams{
+ UserID: parseUUID(testUserID),
+ ToolkitSlug: "gmail",
+ AuthConfigID: "ac_gmail",
+ ConnectedAccountID: account,
+ ComposioUserID: testUserID,
+ }); err != nil {
+ t.Fatalf("seed personal account: %v", err)
+ }
+ t.Cleanup(func() {
+ ctx := context.Background()
+ testPool.Exec(ctx, `DELETE FROM user_composio_connection WHERE connected_account_id = $1`, account)
+ for _, table := range []string{"app_tool_call", "app_action_request", "app_action_rule", "agent_app", "workspace_app_setting", "app_tool_class_override"} {
+ testPool.Exec(ctx, `DELETE FROM `+table+` WHERE workspace_id = $1`, testWorkspaceID)
+ }
+ testPool.Exec(ctx, `DELETE FROM inbox_item WHERE workspace_id = $1 AND type LIKE 'app\_%'`, testWorkspaceID)
+ testPool.Exec(ctx, `DELETE FROM agent_task_queue WHERE agent_id = $1`, agentID)
+ })
+
+ return &appsFixture{
+ h: &h, sdk: fake, agentID: agentID, issueID: issueID, taskID: taskID,
+ member: createTestUserAndMember(t, "member"),
+ }
+}
+
+func appsReqAs(t *testing.T, userID, method, path string, body any) *http.Request {
+ t.Helper()
+ req := newRequestAs(userID, method, path, body)
+ member, err := testHandler.Queries.GetMemberByUserAndWorkspace(context.Background(), db.GetMemberByUserAndWorkspaceParams{
+ UserID: util.MustParseUUID(userID), WorkspaceID: util.MustParseUUID(testWorkspaceID),
+ })
+ if err != nil {
+ t.Fatalf("load member %s: %v", userID, err)
+ }
+ return req.WithContext(middleware.SetMemberContext(req.Context(), testWorkspaceID, member))
+}
+
+func (f *appsFixture) putAgentApps(t *testing.T, userID string, apps []map[string]string) *httptest.ResponseRecorder {
+ t.Helper()
+ w := httptest.NewRecorder()
+ req := appsReqAs(t, userID, http.MethodPut, "/api/agents/"+f.agentID+"/apps", map[string]any{"apps": apps})
+ f.h.UpdateAgentApps(w, withURLParam(req, "id", f.agentID))
+ return w
+}
+
+// gateway sends one tools/call to the MCP gateway with the run's token.
+func (f *appsFixture) gateway(t *testing.T, token, tool string, args map[string]any) (int, string, bool) {
+ t.Helper()
+ body, _ := json.Marshal(map[string]any{
+ "jsonrpc": "2.0", "id": 1, "method": "tools/call",
+ "params": map[string]any{"name": tool, "arguments": args},
+ })
+ req := httptest.NewRequest(http.MethodPost, connectedapps.GatewayPath, bytes.NewReader(body))
+ if token != "" {
+ req.Header.Set("Authorization", "Bearer "+token)
+ }
+ w := httptest.NewRecorder()
+ f.h.AppsGateway(w, req)
+ if w.Code != http.StatusOK {
+ return w.Code, w.Body.String(), false
+ }
+ var resp struct {
+ Result struct {
+ Content []struct {
+ Text string `json:"text"`
+ } `json:"content"`
+ IsError bool `json:"isError"`
+ } `json:"result"`
+ }
+ if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil || len(resp.Result.Content) == 0 {
+ t.Fatalf("decode gateway response %s: %v", w.Body.String(), err)
+ }
+ return w.Code, resp.Result.Content[0].Text, resp.Result.IsError
+}
+
+func (f *appsFixture) token(t *testing.T) string {
+ t.Helper()
+ token, err := connectedapps.SignTaskToken(connectedapps.DeriveTokenSecret([]byte("apps-test-secret")), f.taskID, time.Now().Add(time.Hour))
+ if err != nil {
+ t.Fatalf("sign token: %v", err)
+ }
+ return token
+}
+
+func (f *appsFixture) listRequests(t *testing.T, userID string) []AppRequestResponse {
+ t.Helper()
+ w := httptest.NewRecorder()
+ f.h.ListAppRequests(w, appsReqAs(t, userID, http.MethodGet, "/api/app-requests?issue_id="+f.issueID, nil))
+ if w.Code != http.StatusOK {
+ t.Fatalf("ListAppRequests: %d %s", w.Code, w.Body.String())
+ }
+ var resp struct {
+ Requests []AppRequestResponse `json:"requests"`
+ }
+ json.Unmarshal(w.Body.Bytes(), &resp)
+ return resp.Requests
+}
+
+func TestConnectedApps_ConfirmApproveResumes(t *testing.T) {
+ f := newAppsFixture(t)
+
+ if w := f.putAgentApps(t, testUserID, []map[string]string{{"toolkit_slug": "gmail", "account_scope": "personal", "level": "confirm_writes"}}); w.Code != http.StatusOK {
+ t.Fatalf("UpdateAgentApps: %d %s", w.Code, w.Body.String())
+ }
+ var allowlist []string
+ testPool.QueryRow(context.Background(), `SELECT composio_toolkit_allowlist FROM agent WHERE id = $1`, f.agentID).Scan(&allowlist)
+ if len(allowlist) != 1 || allowlist[0] != "gmail" {
+ t.Fatalf("legacy allowlist = %v, want [gmail]", allowlist)
+ }
+
+ token := f.token(t)
+ if code, _, _ := f.gateway(t, "", "apps_list", nil); code != http.StatusUnauthorized {
+ t.Fatalf("gateway without token: %d, want 401", code)
+ }
+ if _, text, isErr := f.gateway(t, token, "apps_list", nil); isErr || !strings.Contains(text, `"status": "connected"`) {
+ t.Fatalf("apps_list = %s (error %v)", text, isErr)
+ }
+
+ // A read runs directly.
+ if _, text, isErr := f.gateway(t, token, "apps_run_tool", map[string]any{"tool": "GMAIL_FETCH_EMAILS", "arguments": map[string]any{}}); isErr {
+ t.Fatalf("read call failed: %s", text)
+ }
+ if n := len(f.sdk.executions()); n != 1 {
+ t.Fatalf("executions after read = %d, want 1", n)
+ }
+
+ // A send waits for the person who triggered the run.
+ args := map[string]any{"to": "[email protected]", "body": "draft"}
+ _, text, isErr := f.gateway(t, token, "apps_run_tool", map[string]any{"tool": "GMAIL_SEND_EMAIL", "arguments": args, "summary": "Reply to the customer"})
+ if isErr || !strings.HasPrefix(text, "submitted") {
+ t.Fatalf("send call = %s (error %v), want submitted", text, isErr)
+ }
+ if n := len(f.sdk.executions()); n != 1 {
+ t.Fatalf("send executed before approval")
+ }
+ // Retrying the same call reuses the pending request.
+ f.gateway(t, token, "apps_run_tool", map[string]any{"tool": "GMAIL_SEND_EMAIL", "arguments": args})
+
+ mine := f.listRequests(t, testUserID)
+ if len(mine) != 1 || mine[0].Status != "pending" || mine[0].Redacted || mine[0].Summary != "Reply to the customer" {
+ t.Fatalf("approver view = %+v", mine)
+ }
+ other := f.listRequests(t, f.member)
+ if len(other) != 1 || !other[0].Redacted || other[0].Arguments != nil {
+ t.Fatalf("non-approver view not redacted: %+v", other)
+ }
+
+ var inboxCount int
+ testPool.QueryRow(context.Background(), `SELECT count(*) FROM inbox_item WHERE recipient_id = $1 AND type = 'app_action_requested' AND details->>'request_id' = $2`, testUserID, mine[0].ID).Scan(&inboxCount)
+ if inboxCount != 1 {
+ t.Fatalf("inbox items = %d, want 1", inboxCount)
+ }
+
+ approve := func(userID string, body any) *httptest.ResponseRecorder {
+ w := httptest.NewRecorder()
+ req := appsReqAs(t, userID, http.MethodPost, "/api/app-requests/"+mine[0].ID+"/approve", body)
+ f.h.ApproveAppRequest(w, withURLParam(req, "id", mine[0].ID))
+ return w
+ }
+ if w := approve(f.member, nil); w.Code != http.StatusForbidden {
+ t.Fatalf("approve by non-approver: %d, want 403", w.Code)
+ }
+ edited := map[string]any{"to": "[email protected]", "body": "edited"}
+ w := approve(testUserID, map[string]any{"arguments": edited})
+ if w.Code != http.StatusOK {
+ t.Fatalf("approve: %d %s", w.Code, w.Body.String())
+ }
+ execs := f.sdk.executions()
+ if len(execs) != 2 || execs[1].Arguments["body"] != "edited" {
+ t.Fatalf("approved execution = %+v", execs)
+ }
+ if w := approve(testUserID, nil); w.Code != http.StatusConflict {
+ t.Fatalf("second approve: %d, want 409", w.Code)
+ }
+
+ var note string
+ if err := testPool.QueryRow(context.Background(), `
+ SELECT handoff_note FROM agent_task_queue
+ WHERE agent_id = $1 AND issue_id = $2 AND status = 'queued' AND trigger_evidence_kind = 'app_action_request'
+ `, f.agentID, f.issueID).Scan(&note); err != nil {
+ t.Fatalf("resume run not queued: %v", err)
+ }
+ if !strings.Contains(note, "approved") || !strings.Contains(note, "edited the arguments") {
+ t.Fatalf("handoff note = %q", note)
+ }
+
+ // The token dies with the run.
+ testPool.Exec(context.Background(), `UPDATE agent_task_queue SET status = 'completed', completed_at = now() WHERE id = $1`, f.taskID)
+ if code, _, _ := f.gateway(t, token, "apps_list", nil); code != http.StatusUnauthorized {
+ t.Fatalf("gateway after run ended: %d, want 401", code)
+ }
+}
+
+func TestConnectedApps_RulesAndLevels(t *testing.T) {
+ f := newAppsFixture(t)
+ if w := f.putAgentApps(t, testUserID, []map[string]string{{"toolkit_slug": "gmail", "account_scope": "personal", "level": "read"}}); w.Code != http.StatusOK {
+ t.Fatalf("UpdateAgentApps: %d %s", w.Code, w.Body.String())
+ }
+ token := f.token(t)
+
+ // A read-only agent cannot send, whatever the rules say.
+ if _, text, isErr := f.gateway(t, token, "apps_run_tool", map[string]any{"tool": "GMAIL_SEND_EMAIL", "arguments": map[string]any{}}); !isErr || !strings.HasPrefix(text, "blocked") {
+ t.Fatalf("send at read level = %s, want blocked", text)
+ }
+
+ // With write level, the account owner's own rule lets sends through.
+ f.putAgentApps(t, testUserID, []map[string]string{{"toolkit_slug": "gmail", "account_scope": "personal", "level": "write"}})
+ w := httptest.NewRecorder()
+ f.h.UpdateAppRules(w, appsReqAs(t, testUserID, http.MethodPut, "/api/apps/rules?toolkit_slug=gmail&scope=personal",
+ map[string]any{"rules": []map[string]string{{"action_class": "send", "policy": "allow"}, {"action_class": "delete", "policy": "block"}}}))
+ if w.Code != http.StatusOK {
+ t.Fatalf("UpdateAppRules: %d %s", w.Code, w.Body.String())
+ }
+ if _, text, isErr := f.gateway(t, token, "apps_run_tool", map[string]any{"tool": "GMAIL_SEND_EMAIL", "arguments": map[string]any{}}); isErr {
+ t.Fatalf("allowed send failed: %s", text)
+ }
+ if _, text, isErr := f.gateway(t, token, "apps_run_tool", map[string]any{"tool": "GMAIL_DELETE_MESSAGE", "arguments": map[string]any{}}); !isErr || !strings.HasPrefix(text, "blocked") {
+ t.Fatalf("blocked delete = %s", text)
+ }
+
+ // Another member's rules are their own and do not touch this account.
+ w = httptest.NewRecorder()
+ f.h.GetAppRules(w, appsReqAs(t, f.member, http.MethodGet, "/api/apps/rules?toolkit_slug=gmail&scope=personal", nil))
+ var rules struct {
+ Rules []AppRuleResponse `json:"rules"`
+ }
+ json.Unmarshal(w.Body.Bytes(), &rules)
+ for _, r := range rules.Rules {
+ if r.Custom {
+ t.Fatalf("member sees another person's rule: %+v", r)
+ }
+ }
+}
+
+func TestConnectedApps_AdminOnlyTeamSurfaces(t *testing.T) {
+ f := newAppsFixture(t)
+
+ w := f.putAgentApps(t, f.member, []map[string]string{{"toolkit_slug": "gmail", "account_scope": "team", "level": "read"}})
+ if w.Code != http.StatusForbidden {
+ t.Fatalf("member gives agent a team account: %d, want 403", w.Code)
+ }
+
+ w = httptest.NewRecorder()
+ f.h.UpdateAppRules(w, appsReqAs(t, f.member, http.MethodPut, "/api/apps/rules?toolkit_slug=gmail&scope=team",
+ map[string]any{"rules": []map[string]string{{"action_class": "send", "policy": "allow"}}}))
+ if w.Code != http.StatusForbidden {
+ t.Fatalf("member edits team rules: %d, want 403", w.Code)
+ }
+
+ for name, call := range map[string]func(http.ResponseWriter, *http.Request){
+ "connect": f.h.ConnectTeamApp,
+ "settings": f.h.UpdateAppSettings,
+ "impact": f.h.GetTeamAppImpact,
+ } {
+ w := httptest.NewRecorder()
+ call(w, appsReqAs(t, f.member, http.MethodPost, "/api/apps/team", map[string]any{"toolkit_slug": "gmail", "catalog_mode": "curated"}))
+ if w.Code != http.StatusForbidden {
+ t.Fatalf("%s as member: %d, want 403", name, w.Code)
+ }
+ }
+
+ // Curated mode keeps unlisted apps out of agents.
+ w = httptest.NewRecorder()
+ f.h.UpdateAppSettings(w, appsReqAs(t, testUserID, http.MethodPut, "/api/apps/settings", map[string]any{"catalog_mode": "curated"}))
+ if w.Code != http.StatusOK {
+ t.Fatalf("UpdateAppSettings: %d %s", w.Code, w.Body.String())
+ }
+ if w := f.putAgentApps(t, testUserID, []map[string]string{{"toolkit_slug": "some_unlisted_app", "account_scope": "personal", "level": "read"}}); w.Code != http.StatusForbidden {
+ t.Fatalf("unlisted app in curated mode: %d, want 403", w.Code)
+ }
+ if w := f.putAgentApps(t, testUserID, []map[string]string{{"toolkit_slug": "gmail", "account_scope": "team", "level": "read"}}); w.Code != http.StatusOK {
+ t.Fatalf("admin gives agent a team account: %d %s", w.Code, w.Body.String())
+ }
+
+ // A team app without a connected team account reports not_connected.
+ if _, text, _ := f.gateway(t, f.token(t), "apps_list", nil); !strings.Contains(text, `"status": "not_connected"`) {
+ t.Fatalf("apps_list = %s, want not_connected", text)
+ }
+}
+
+func (f *appsFixture) inboxCount(t *testing.T, recipient, notifType string) int {
+ t.Helper()
+ var n int
+ testPool.QueryRow(context.Background(), `SELECT count(*) FROM inbox_item WHERE workspace_id = $1 AND recipient_id = $2 AND type = $3`, testWorkspaceID, recipient, notifType).Scan(&n)
+ return n
+}
+
+func TestConnectedApps_ResultNotifications(t *testing.T) {
+ f := newAppsFixture(t)
+ f.putAgentApps(t, testUserID, []map[string]string{{"toolkit_slug": "gmail", "account_scope": "personal", "level": "read"}})
+ token := f.token(t)
+
+ // A block tells the person who triggered the run once, not on every retry.
+ for i := 0; i < 2; i++ {
+ if _, text, isErr := f.gateway(t, token, "apps_run_tool", map[string]any{"tool": "GMAIL_SEND_EMAIL", "arguments": map[string]any{}}); !isErr || !strings.HasPrefix(text, "blocked") {
+ t.Fatalf("send at read level = %s", text)
+ }
+ }
+ if n := f.inboxCount(t, testUserID, connectedapps.NotifActionResult); n != 1 {
+ t.Fatalf("block notifications = %d, want 1", n)
+ }
+
+ // An unanswered confirmation expires into a result notification.
+ f.putAgentApps(t, testUserID, []map[string]string{{"toolkit_slug": "gmail", "account_scope": "personal", "level": "confirm_writes"}})
+ if _, text, _ := f.gateway(t, token, "apps_run_tool", map[string]any{"tool": "GMAIL_SEND_EMAIL", "arguments": map[string]any{"to": "x"}}); !strings.HasPrefix(text, "submitted") {
+ t.Fatalf("send = %s, want submitted", text)
+ }
+ testPool.Exec(context.Background(), `UPDATE app_action_request SET expires_at = now() - interval '1 minute' WHERE task_id = $1`, f.taskID)
+ f.h.ConnectedApps.Sweep(context.Background())
+ if reqs := f.listRequests(t, testUserID); len(reqs) != 1 || reqs[0].Status != "expired" {
+ t.Fatalf("requests after sweep = %+v", reqs)
+ }
+ if n := f.inboxCount(t, testUserID, connectedapps.NotifActionResult); n != 2 {
+ t.Fatalf("result notifications after expiry = %d, want 2", n)
+ }
+
+ // Muting agent activity mutes results, never confirmations.
+ testPool.Exec(context.Background(), `
+ INSERT INTO notification_preference (workspace_id, user_id, preferences)
+ VALUES ($1, $2, '{"agent_activity":"muted"}')
+ ON CONFLICT (workspace_id, user_id) DO UPDATE SET preferences = EXCLUDED.preferences
+ `, testWorkspaceID, testUserID)
+ t.Cleanup(func() {
+ testPool.Exec(context.Background(), `DELETE FROM notification_preference WHERE workspace_id = $1 AND user_id = $2`, testWorkspaceID, testUserID)
+ })
+ f.gateway(t, token, "apps_run_tool", map[string]any{"tool": "GMAIL_SEND_EMAIL", "arguments": map[string]any{"to": "y"}})
+ if n := f.inboxCount(t, testUserID, connectedapps.NotifActionRequested); n != 2 {
+ t.Fatalf("confirmations with agent activity muted = %d, want 2", n)
+ }
+ testPool.Exec(context.Background(), `UPDATE app_action_request SET expires_at = now() - interval '1 minute' WHERE task_id = $1 AND status = 'pending'`, f.taskID)
+ f.h.ConnectedApps.Sweep(context.Background())
+ if n := f.inboxCount(t, testUserID, connectedapps.NotifActionResult); n != 2 {
+ t.Fatalf("muted result delivered: %d, want 2", n)
+ }
+}
+
+func TestConnectedApps_RateLimit(t *testing.T) {
+ f := newAppsFixture(t)
+ f.putAgentApps(t, testUserID, []map[string]string{{"toolkit_slug": "gmail", "account_scope": "personal", "level": "write"}})
+ if _, err := testPool.Exec(context.Background(), `
+ INSERT INTO app_tool_call (workspace_id, agent_id, account_scope, account_owner_user_id, toolkit_slug, tool_slug, action_class, outcome)
+ SELECT $1, $2, 'personal', $3, 'gmail', 'GMAIL_FETCH_EMAILS', 'read', 'ok' FROM generate_series(1, $4::int)
+ `, testWorkspaceID, f.agentID, testUserID, connectedapps.DefaultCallsPerMinute); err != nil {
+ t.Fatalf("seed calls: %v", err)
+ }
+ _, text, isErr := f.gateway(t, f.token(t), "apps_run_tool", map[string]any{"tool": "GMAIL_FETCH_EMAILS", "arguments": map[string]any{}})
+ if !isErr || !strings.HasPrefix(text, "rate limited") {
+ t.Fatalf("call over the limit = %s (error %v)", text, isErr)
+ }
+ if n := len(f.sdk.executions()); n != 0 {
+ t.Fatalf("limited call executed")
+ }
+ // Older calls fall out of the window.
+ testPool.Exec(context.Background(), `UPDATE app_tool_call SET created_at = now() - interval '2 minutes' WHERE workspace_id = $1`, testWorkspaceID)
+ if _, text, isErr := f.gateway(t, f.token(t), "apps_run_tool", map[string]any{"tool": "GMAIL_FETCH_EMAILS", "arguments": map[string]any{}}); isErr {
+ t.Fatalf("call after the window = %s", text)
+ }
+}
+
+func TestConnectedApps_ConnectRequestResolvesOnConnect(t *testing.T) {
+ f := newAppsFixture(t)
+ f.putAgentApps(t, testUserID, []map[string]string{{"toolkit_slug": "notion", "account_scope": "personal", "level": "write"}})
+ _, text, isErr := f.gateway(t, f.token(t), "apps_request_connection", map[string]any{"app": "notion", "summary": "Read the spec"})
+ if isErr || !strings.HasPrefix(text, "requested") {
+ t.Fatalf("request connection = %s (error %v)", text, isErr)
+ }
+ reqs := f.listRequests(t, testUserID)
+ if len(reqs) != 1 || reqs[0].Kind != "connect" {
+ t.Fatalf("requests = %+v", reqs)
+ }
+ expires, _ := time.Parse(time.RFC3339, reqs[0].ExpiresAt)
+ if time.Until(expires) < 6*24*time.Hour {
+ t.Fatalf("connect request expires %s, want about 7 days out", reqs[0].ExpiresAt)
+ }
+
+ account := fmt.Sprintf("ca_notion_%d", testSeq.Add(1))
+ testHandler.Queries.UpsertUserComposioConnection(context.Background(), db.UpsertUserComposioConnectionParams{
+ UserID: parseUUID(testUserID), ToolkitSlug: "notion", AuthConfigID: "ac_notion",
+ ConnectedAccountID: account, ComposioUserID: testUserID,
+ })
+ t.Cleanup(func() {
+ testPool.Exec(context.Background(), `DELETE FROM user_composio_connection WHERE connected_account_id = $1`, account)
+ })
+ f.h.ConnectedApps.ResolveConnectRequests(context.Background(), parseUUID(testUserID), "notion")
+
+ if reqs := f.listRequests(t, testUserID); len(reqs) != 1 || reqs[0].Status != "approved" {
+ t.Fatalf("connect request after connecting = %+v", reqs)
+ }
+ var note string
+ if err := testPool.QueryRow(context.Background(), `
+ SELECT handoff_note FROM agent_task_queue
+ WHERE agent_id = $1 AND issue_id = $2 AND status = 'queued' AND trigger_evidence_kind = 'app_action_request'
+ `, f.agentID, f.issueID).Scan(&note); err != nil || !strings.Contains(note, "now connected") {
+ t.Fatalf("resume run = %q, %v", note, err)
+ }
+}
+
+func TestConnectedApps_ToolClassOverride(t *testing.T) {
+ f := newAppsFixture(t)
+ f.putAgentApps(t, testUserID, []map[string]string{{"toolkit_slug": "gmail", "account_scope": "personal", "level": "confirm_writes"}})
+
+ setClass := func(userID, class string) int {
+ w := httptest.NewRecorder()
+ f.h.UpdateAppToolClass(w, appsReqAs(t, userID, http.MethodPut, "/api/apps/tools/class",
+ map[string]string{"toolkit_slug": "gmail", "tool_slug": "GMAIL_FETCH_EMAILS", "action_class": class}))
+ return w.Code
+ }
+ if code := setClass(f.member, "send"); code != http.StatusForbidden {
+ t.Fatalf("member overrides a class: %d, want 403", code)
+ }
+ if code := setClass(testUserID, "send"); code != http.StatusNoContent {
+ t.Fatalf("admin override: %d", code)
+ }
+
+ w := httptest.NewRecorder()
+ f.h.ListAppTools(w, appsReqAs(t, f.member, http.MethodGet, "/api/apps/tools?toolkit_slug=gmail", nil))
+ var tools struct {
+ Tools []AppToolResponse `json:"tools"`
+ }
+ json.Unmarshal(w.Body.Bytes(), &tools)
+ found := false
+ for _, tool := range tools.Tools {
+ if tool.Slug == "GMAIL_FETCH_EMAILS" {
+ found = true
+ if tool.Class != "send" || tool.AutoClass != "read" || !tool.Overridden {
+ t.Fatalf("overridden tool = %+v", tool)
+ }
+ }
+ }
+ if !found {
+ t.Fatalf("tools = %s", w.Body.String())
+ }
+
+ // The corrected class drives the policy: a "read" now waits for confirmation.
+ if _, text, _ := f.gateway(t, f.token(t), "apps_run_tool", map[string]any{"tool": "GMAIL_FETCH_EMAILS", "arguments": map[string]any{}}); !strings.HasPrefix(text, "submitted") {
+ t.Fatalf("overridden read = %s, want submitted", text)
+ }
+ if code := setClass(testUserID, ""); code != http.StatusNoContent {
+ t.Fatalf("reset override: %d", code)
+ }
+ if _, text, isErr := f.gateway(t, f.token(t), "apps_run_tool", map[string]any{"tool": "GMAIL_FETCH_EMAILS", "arguments": map[string]any{}}); isErr || strings.HasPrefix(text, "submitted") {
+ t.Fatalf("read after reset = %s", text)
+ }
+}
+
+func TestConnectedApps_CustomCatalogAndIssueCalls(t *testing.T) {
+ f := newAppsFixture(t)
+ f.putAgentApps(t, testUserID, []map[string]string{{"toolkit_slug": "gmail", "account_scope": "personal", "level": "write"}})
+ f.gateway(t, f.token(t), "apps_run_tool", map[string]any{"tool": "GMAIL_FETCH_EMAILS", "arguments": map[string]any{}})
+
+ w := httptest.NewRecorder()
+ f.h.ListIssueAppCalls(w, appsReqAs(t, f.member, http.MethodGet, "/api/app-calls?issue_id="+f.issueID, nil))
+ var calls struct {
+ Calls []IssueAppCallResponse `json:"calls"`
+ }
+ json.Unmarshal(w.Body.Bytes(), &calls)
+ if w.Code != http.StatusOK || len(calls.Calls) != 1 || calls.Calls[0].ToolSlug != "GMAIL_FETCH_EMAILS" || calls.Calls[0].Outcome != "ok" {
+ t.Fatalf("issue calls = %d %s", w.Code, w.Body.String())
+ }
+
+ // A custom catalog keeps everything off the list away from agents.
+ w = httptest.NewRecorder()
+ f.h.UpdateAppSettings(w, appsReqAs(t, testUserID, http.MethodPut, "/api/apps/settings",
+ map[string]any{"catalog_mode": "custom", "allowed_toolkits": []string{"Notion", "notion", ""}}))
+ if w.Code != http.StatusOK || !strings.Contains(w.Body.String(), `"allowed_toolkits":["notion"]`) {
+ t.Fatalf("custom settings: %d %s", w.Code, w.Body.String())
+ }
+ if _, text, _ := f.gateway(t, f.token(t), "apps_list", nil); strings.Contains(text, "gmail") {
+ t.Fatalf("apps_list in custom catalog = %s", text)
+ }
+ if w := f.putAgentApps(t, testUserID, []map[string]string{{"toolkit_slug": "notion", "account_scope": "personal", "level": "read"}}); w.Code != http.StatusOK {
+ t.Fatalf("listed app: %d %s", w.Code, w.Body.String())
+ }
+ if w := f.putAgentApps(t, testUserID, []map[string]string{{"toolkit_slug": "slack", "account_scope": "personal", "level": "read"}}); w.Code != http.StatusForbidden {
+ t.Fatalf("unlisted app in custom catalog: %d, want 403", w.Code)
+ }
+}
diff --git a/server/internal/handler/daemon.go b/server/internal/handler/daemon.go
index 2e0510fca3..cf71adb014 100644
--- a/server/internal/handler/daemon.go
+++ b/server/internal/handler/daemon.go
@@ -3008,7 +3008,17 @@ func (h *Handler) buildClaimedTaskResponse(r *http.Request, task *db.AgentTaskQu
// 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 {
+ overlay := json.RawMessage(task.RuntimeMcpOverlay)
+ // The stored overlay names the apps gateway without a credential; the
+ // run's token is minted here, once the task id is final.
+ if h.ConnectedApps != nil {
+ if authorized, err := h.ConnectedApps.AuthorizeOverlay(overlay, task.ID); err != nil {
+ slog.Warn("daemon claim: authorize apps gateway overlay failed", "task_id", uuidToString(task.ID), "error", err)
+ } else {
+ overlay = authorized
+ }
+ }
+ if merged, err := mergeMCPOverlay(mcpConfig, overlay); 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
diff --git a/server/internal/handler/handler.go b/server/internal/handler/handler.go
index de551221c1..c4c85ccc91 100644
--- a/server/internal/handler/handler.go
+++ b/server/internal/handler/handler.go
@@ -21,6 +21,7 @@ import (
"github.com/multica-ai/multica/server/internal/analytics"
"github.com/multica-ai/multica/server/internal/auth"
"github.com/multica-ai/multica/server/internal/cloudruntime"
+ "github.com/multica-ai/multica/server/internal/connectedapps"
"github.com/multica-ai/multica/server/internal/daemonws"
"github.com/multica-ai/multica/server/internal/dbreader"
"github.com/multica-ai/multica/server/internal/entitlement"
@@ -309,6 +310,9 @@ type Handler struct {
// the composio HTTP handlers return 403 in that case. Wired in
// cmd/server/router.go after handler.New.
Composio *composio.Service
+ // ConnectedApps serves agents' app calls through the MCP gateway (MUL-8516).
+ // Wired together with Composio; nil when Composio is.
+ ConnectedApps *connectedapps.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-agnostic
diff --git a/server/internal/handler/integrations_composio.go b/server/internal/handler/integrations_composio.go
index dea01501b5..c7b150e978 100644
--- a/server/internal/handler/integrations_composio.go
+++ b/server/internal/handler/integrations_composio.go
@@ -105,8 +105,9 @@ func (h *Handler) ComposioConnectInit(w http.ResponseWriter, r *http.Request) {
// 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
+// doing anything. On success the row is upserted, connection requests waiting
+// on this account resume their agents, and the browser is redirected to where
+// the flow started (the settings page by default); 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()) {
@@ -118,15 +119,20 @@ func (h *Handler) ComposioCallback(w http.ResponseWriter, r *http.Request) {
status := q.Get("status")
connectedAccountID := q.Get("connected_account_id")
- slug, err := h.Composio.CompleteCallback(r.Context(), state, status, connectedAccountID)
+ result, 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)
+ http.Redirect(w, r, h.Composio.CallbackRedirect(result, false), http.StatusFound)
return
}
- http.Redirect(w, r, h.Composio.CallbackRedirect(slug, true), http.StatusFound)
+ if h.ConnectedApps != nil && !result.Team() {
+ if userID, perr := parseUUIDStrict(result.UserID); perr == nil {
+ h.ConnectedApps.ResolveConnectRequests(r.Context(), userID, result.ToolkitSlug)
+ }
+ }
+ http.Redirect(w, r, h.Composio.CallbackRedirect(result, true), http.StatusFound)
}
// ListComposioConnections (GET /api/integrations/composio/connections) returns
diff --git a/server/internal/handler/workspace_delete_manifest_test.go b/server/internal/handler/workspace_delete_manifest_test.go
index 562a8b8cd9..4751d98890 100644
--- a/server/internal/handler/workspace_delete_manifest_test.go
+++ b/server/internal/handler/workspace_delete_manifest_test.go
@@ -147,6 +147,13 @@ var workspaceDeletionManifest = map[string]workspaceDeleteAction{
"verification_code": workspaceDeleteKeep,
"webhook_delivery": workspaceDelete,
"wecom_install_session": workspaceDelete,
+ "workspace_composio_connection": workspaceDelete,
+ "agent_app": workspaceDelete,
+ "app_action_rule": workspaceDelete,
+ "app_action_request": workspaceDelete,
+ "app_tool_call": workspaceDelete,
+ "workspace_app_setting": workspaceDelete,
+ "app_tool_class_override": workspaceDelete,
"workspace": workspaceDelete,
"workspace_invitation": workspaceDelete,
"workspace_share_link": workspaceDelete,
diff --git a/server/internal/handler/workspace_revoke.go b/server/internal/handler/workspace_revoke.go
index 2d2733f94b..2593c74a98 100644
--- a/server/internal/handler/workspace_revoke.go
+++ b/server/internal/handler/workspace_revoke.go
@@ -218,6 +218,14 @@ func (h *Handler) revokeAndRemoveMember(ctx context.Context, workspaceID, userID
return empty, err
}
+ // App requests waiting on the member would otherwise let a later OAuth
+ // connect, or a stale tab, resume an agent in a workspace they left.
+ if _, err := qtx.CancelPendingAppActionRequestsForApprover(ctx, db.CancelPendingAppActionRequestsForApproverParams{
+ WorkspaceID: workspaceID, ApproverUserID: 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 leaves
diff --git a/server/internal/integrations/composio/service.go b/server/internal/integrations/composio/service.go
index ca08be5a70..e59dbe689b 100644
--- a/server/internal/integrations/composio/service.go
+++ b/server/internal/integrations/composio/service.go
@@ -136,6 +136,10 @@ type Service struct {
authCache map[string]string
authCacheExp time.Time
authCacheTTL time.Duration
+ // authCreateMu serializes creating managed auth configs so two concurrent
+ // connects for the same new app do not register two configs.
+ authCreateMu sync.Mutex
+ tools toolCache
}
// NewService validates its inputs and returns a ready Service. It errors when a
@@ -239,8 +243,17 @@ func toolkitLogoURL(slug, upstreamLogoURL string) string {
// 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) {
+ return s.BeginConnectReturning(ctx, userID, toolkitSlug, "")
+}
+
+// BeginConnectReturning is BeginConnect whose callback sends the browser back
+// to returnTo, an app path; an unsafe or empty path keeps the settings page.
+func (s *Service) BeginConnectReturning(ctx context.Context, userID pgtype.UUID, toolkitSlug, returnTo string) (string, error) {
+ if !SafeReturnPath(returnTo) {
+ returnTo = ""
+ }
slug := strings.ToLower(strings.TrimSpace(toolkitSlug))
- authConfigID, err := s.authConfigForToolkit(ctx, slug)
+ authConfigID, err := s.ensureAuthConfig(ctx, slug)
if err != nil {
return "", err
}
@@ -256,6 +269,7 @@ func (s *Service) BeginConnect(ctx context.Context, userID pgtype.UUID, toolkitS
UserID: composioUserID,
ToolkitSlug: slug,
AuthConfigID: authConfigID,
+ ReturnTo: returnTo,
Exp: s.now().Add(s.stateTTL).Unix(),
})
if err != nil {
@@ -285,23 +299,31 @@ func (s *Service) BeginConnect(ctx context.Context, userID pgtype.UUID, toolkitS
//
// 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) {
+func (s *Service) CompleteCallback(ctx context.Context, state, status, connectedAccountID string) (CallbackResult, error) {
claims, err := verifyState(s.secret, state, s.now())
if err != nil {
- return "", err
+ return CallbackResult{}, err
+ }
+ result := CallbackResult{ToolkitSlug: claims.ToolkitSlug, WorkspaceID: claims.WorkspaceID, ReturnTo: claims.ReturnTo}
+ if claims.WorkspaceID == "" {
+ result.UserID = claims.UserID
}
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
+ return result, ErrConnectNotSuccessful
}
if strings.TrimSpace(connectedAccountID) == "" {
- return claims.ToolkitSlug, errors.New("composio: callback missing connected_account_id")
+ return result, errors.New("composio: callback missing connected_account_id")
+ }
+
+ if result.Team() {
+ return result, s.completeTeamCallback(ctx, claims, connectedAccountID)
}
userID, err := util.ParseUUID(claims.UserID)
if err != nil {
- return claims.ToolkitSlug, fmt.Errorf("composio: state has invalid user id: %w", err)
+ return result, fmt.Errorf("composio: state has invalid user id: %w", err)
}
// The auth_config_id was resolved at BeginConnect and signed into the state,
@@ -321,7 +343,7 @@ func (s *Service) CompleteCallback(ctx context.Context, state, status, connected
// 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
+ return result, err
}
if _, err := s.store.UpsertUserComposioConnection(ctx, db.UpsertUserComposioConnectionParams{
@@ -332,9 +354,9 @@ func (s *Service) CompleteCallback(ctx context.Context, state, status, connected
// Invariant: composio_user_id == Multica user id.
ComposioUserID: claims.UserID,
}); err != nil {
- return claims.ToolkitSlug, fmt.Errorf("composio: upsert connection: %w", err)
+ return result, fmt.Errorf("composio: upsert connection: %w", err)
}
- return claims.ToolkitSlug, nil
+ return result, nil
}
// ListConnections returns the user's active connections.
@@ -459,14 +481,31 @@ func (s *Service) CreateMCPSession(ctx context.Context, userID pgtype.UUID) (*MC
// 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
+func (s *Service) CallbackRedirect(result CallbackResult, success bool) string {
+ if result.ReturnTo != "" && SafeReturnPath(result.ReturnTo) {
+ path, rawQuery, _ := strings.Cut(result.ReturnTo, "?")
+ q, err := url.ParseQuery(rawQuery)
+ if err != nil {
+ q = url.Values{}
+ }
+ if success {
+ q.Set("app_connected", result.ToolkitSlug)
+ } else {
+ q.Set("app_connect_error", result.ToolkitSlug)
+ }
+ return s.frontendURL + path + "?" + q.Encode()
+ }
+ q := url.Values{}
+ q.Set("tab", "apps")
if success {
- path = "/settings?tab=integrations&connected=" + url.QueryEscape(slug)
+ q.Set("connected", result.ToolkitSlug)
} else {
- path = "/settings?tab=integrations&error=composio_connect_failed"
+ q.Set("error", "composio_connect_failed")
+ }
+ if result.Team() {
+ q.Set("scope", "team")
}
- return s.frontendURL + path
+ return s.frontendURL + "/settings?" + q.Encode()
}
// rowToConnection maps a DB row to the API-facing Connection view.
@@ -530,7 +569,7 @@ func (s *Service) ListToolkits(ctx context.Context) ([]ToolkitView, error) {
seen[slug] = struct{}{}
// Filter out toolkits with no enabled auth config: the user has no
// working action for them, so they are omitted from the catalog.
- if _, canConnect := connectable[slug]; !canConnect {
+ if _, canConnect := connectable[slug]; !canConnect && len(tk.ComposioManagedAuthSchemes) == 0 {
continue
}
category := ""
diff --git a/server/internal/integrations/composio/service_test.go b/server/internal/integrations/composio/service_test.go
index bd01b0935d..50966bf2d9 100644
--- a/server/internal/integrations/composio/service_test.go
+++ b/server/internal/integrations/composio/service_test.go
@@ -397,12 +397,12 @@ func TestCompleteCallback_SuccessAndIdempotent(t *testing.T) {
Exp: time.Unix(1_700_000_000, 0).Add(time.Minute).Unix(),
})
- slug, err := svc.CompleteCallback(context.Background(), state, "success", "ca_123")
+ res, 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)
+ if res.ToolkitSlug != "notion" || res.Team() {
+ t.Errorf("result = %+v", res)
}
// Duplicate callback (same connected account) must not create a 2nd row.
if _, err := svc.CompleteCallback(context.Background(), state, "success", "ca_123"); err != nil {
@@ -452,12 +452,12 @@ func TestCompleteCallback_NonSuccessNoRow(t *testing.T) {
ToolkitSlug: "notion",
Exp: time.Unix(1_700_000_000, 0).Add(time.Minute).Unix(),
})
- slug, err := svc.CompleteCallback(context.Background(), state, "failed", "ca_x")
+ res, 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 res.ToolkitSlug != "notion" {
+ t.Errorf("slug = %q (should still be returned for redirect)", res.ToolkitSlug)
}
if len(store.rows) != 0 {
t.Fatalf("expected no row written on non-success, got %d", len(store.rows))
@@ -693,12 +693,21 @@ func TestCreateMCPSession_PinsConnectedAccounts(t *testing.T) {
func TestCallbackRedirect(t *testing.T) {
t.Parallel()
svc := newTestService(t, &fakeSDK{}, newFakeStore())
- if got := svc.CallbackRedirect("notion", true); got != "https://multica.ai/settings?tab=integrations&connected=notion" {
+ if got := svc.CallbackRedirect(CallbackResult{ToolkitSlug: "notion"}, true); got != "https://multica.ai/settings?connected=notion&tab=apps" {
t.Errorf("success redirect = %q", got)
}
- if got := svc.CallbackRedirect("notion", false); got != "https://multica.ai/settings?tab=integrations&error=composio_connect_failed" {
+ if got := svc.CallbackRedirect(CallbackResult{ToolkitSlug: "notion"}, false); got != "https://multica.ai/settings?error=composio_connect_failed&tab=apps" {
t.Errorf("failure redirect = %q", got)
}
+ if got := svc.CallbackRedirect(CallbackResult{ToolkitSlug: "notion", ReturnTo: "/acme/issues/MUL-1?tab=x"}, true); got != "https://multica.ai/acme/issues/MUL-1?app_connected=notion&tab=x" {
+ t.Errorf("return redirect = %q", got)
+ }
+ if got := svc.CallbackRedirect(CallbackResult{ToolkitSlug: "notion", ReturnTo: "//evil.example/x"}, false); got != "https://multica.ai/settings?error=composio_connect_failed&tab=apps" {
+ t.Errorf("unsafe return path not ignored: %q", got)
+ }
+ if got := svc.CallbackRedirect(CallbackResult{ToolkitSlug: "notion", WorkspaceID: "w"}, true); got != "https://multica.ai/settings?connected=notion&scope=team&tab=apps" {
+ t.Errorf("team redirect = %q", got)
+ }
}
// seedActive inserts an active connection through the store and returns the row.
@@ -712,3 +721,20 @@ func seedActive(store *fakeStore, userID pgtype.UUID, slug, caID string) db.User
})
return row
}
+
+func TestSafeReturnPath(t *testing.T) {
+ for path, want := range map[string]bool{
+ "/acme/issues/MUL-1": true,
+ "/acme/chat?session=1": true,
+ "": false,
+ "acme/issues": false,
+ "//evil.example": false,
+ "/\\evil.example": false,
+ "https://evil.example": false,
+ "/acme/\r\nSet-Cookie: x": false,
+ } {
+ if got := SafeReturnPath(path); got != want {
+ t.Errorf("SafeReturnPath(%q) = %v, want %v", path, got, want)
+ }
+ }
+}
diff --git a/server/internal/integrations/composio/state.go b/server/internal/integrations/composio/state.go
index 3c23b7b9af..3946b853b4 100644
--- a/server/internal/integrations/composio/state.go
+++ b/server/internal/integrations/composio/state.go
@@ -40,7 +40,31 @@ type stateClaims struct {
// 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"`
+ // WorkspaceID and ConnectedBy are set only for a team account: the
+ // workspace that owns it and the admin who started the handshake.
+ WorkspaceID string `json:"w,omitempty"`
+ ConnectedBy string `json:"c,omitempty"`
+ // ReturnTo is the app path the browser goes back to, e.g. the issue whose
+ // connect card started the flow. Validated by SafeReturnPath at sign time.
+ ReturnTo string `json:"r,omitempty"`
+ Exp int64 `json:"e"`
+}
+
+// SafeReturnPath reports whether p is a same-origin app path: absolute,
+// not protocol-relative, without control characters, and short.
+func SafeReturnPath(p string) bool {
+ if p == "" || len(p) > 512 || !strings.HasPrefix(p, "/") {
+ return false
+ }
+ if strings.HasPrefix(p, "//") || strings.HasPrefix(p, "/\\") {
+ return false
+ }
+ for _, r := range p {
+ if r < 0x20 || r == 0x7f || r == '\\' {
+ return false
+ }
+ }
+ return true
}
// signState produces a URL-safe "<payload>.<sig>" token. payload is the
diff --git a/server/internal/integrations/composio/team.go b/server/internal/integrations/composio/team.go
new file mode 100644
index 0000000000..5810416cf2
--- /dev/null
+++ b/server/internal/integrations/composio/team.go
@@ -0,0 +1,338 @@
+package composio
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "net/url"
+ "strings"
+ "sync"
+ "time"
+
+ "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"
+)
+
+// ErrTeamAccountsUnavailable is returned when the configured SDK or store
+// cannot serve team accounts or tool execution (test fakes that predate them).
+var ErrTeamAccountsUnavailable = errors.New("composio: team accounts unavailable")
+
+// ToolSDK is the part of *sdk.Client the gateway and the unified catalog use.
+// It is separate from SDK so fakes written for the connect flow keep working.
+type ToolSDK interface {
+ GetToolkit(ctx context.Context, slug string) (*sdk.Toolkit, error)
+ ListTools(ctx context.Context, req sdk.ListToolsRequest) (*sdk.ListToolsResponse, error)
+ GetTool(ctx context.Context, toolSlug string) (*sdk.Tool, error)
+ ExecuteTool(ctx context.Context, toolSlug string, req sdk.ExecuteToolRequest) (*sdk.ExecuteToolResponse, error)
+ CreateManagedAuthConfig(ctx context.Context, toolkitSlug string) (string, error)
+}
+
+// TeamStore persists workspace-level (team) accounts. *db.Queries satisfies it.
+type TeamStore interface {
+ UpsertWorkspaceComposioConnection(ctx context.Context, arg db.UpsertWorkspaceComposioConnectionParams) (db.WorkspaceComposioConnection, error)
+ RevokeOtherWorkspaceComposioConnections(ctx context.Context, arg db.RevokeOtherWorkspaceComposioConnectionsParams) ([]db.WorkspaceComposioConnection, error)
+ GetWorkspaceComposioConnection(ctx context.Context, arg db.GetWorkspaceComposioConnectionParams) (db.WorkspaceComposioConnection, error)
+ SetWorkspaceComposioConnectionStatus(ctx context.Context, arg db.SetWorkspaceComposioConnectionStatusParams) error
+}
+
+// TeamComposioUserID is the Composio user a workspace's team accounts belong
+// to. It cannot collide with a member's id, which is a bare UUID.
+func TeamComposioUserID(workspaceID pgtype.UUID) string {
+ return "ws_" + util.UUIDToString(workspaceID)
+}
+
+// CallbackResult is what a completed connect handshake produced.
+type CallbackResult struct {
+ ToolkitSlug string
+ // WorkspaceID is set for a team account.
+ WorkspaceID string
+ // UserID is the member who connected a personal account.
+ UserID string
+ // ReturnTo is the app path the flow started from, if any.
+ ReturnTo string
+}
+
+// Team reports whether the handshake connected a team account.
+func (r CallbackResult) Team() bool { return r.WorkspaceID != "" }
+
+func (s *Service) toolSDK() (ToolSDK, error) {
+ t, ok := s.sdk.(ToolSDK)
+ if !ok {
+ return nil, ErrTeamAccountsUnavailable
+ }
+ return t, nil
+}
+
+func (s *Service) teamStore() (TeamStore, error) {
+ t, ok := s.store.(TeamStore)
+ if !ok {
+ return nil, ErrTeamAccountsUnavailable
+ }
+ return t, nil
+}
+
+// BeginTeamConnect starts the connect handshake for a workspace's team
+// account. The caller has already checked that actorID administers the
+// workspace.
+func (s *Service) BeginTeamConnect(ctx context.Context, workspaceID, actorID pgtype.UUID, toolkitSlug, returnTo string) (string, error) {
+ if !SafeReturnPath(returnTo) {
+ returnTo = ""
+ }
+ if _, err := s.teamStore(); err != nil {
+ return "", err
+ }
+ if !workspaceID.Valid || !actorID.Valid {
+ return "", errors.New("composio: invalid workspace or actor id")
+ }
+ slug := strings.ToLower(strings.TrimSpace(toolkitSlug))
+ authConfigID, err := s.ensureAuthConfig(ctx, slug)
+ if err != nil {
+ return "", err
+ }
+ composioUserID := TeamComposioUserID(workspaceID)
+ state, err := signState(s.secret, stateClaims{
+ UserID: composioUserID,
+ ToolkitSlug: slug,
+ AuthConfigID: authConfigID,
+ WorkspaceID: util.UUIDToString(workspaceID),
+ ConnectedBy: util.UUIDToString(actorID),
+ ReturnTo: returnTo,
+ Exp: s.now().Add(s.stateTTL).Unix(),
+ })
+ if err != nil {
+ return "", fmt.Errorf("composio: sign state: %w", err)
+ }
+ resp, err := s.sdk.CreateLink(ctx, sdk.CreateLinkRequest{
+ AuthConfigID: authConfigID,
+ UserID: composioUserID,
+ CallbackURL: s.callbackURL + "?state=" + url.QueryEscape(state),
+ })
+ if err != nil {
+ return "", fmt.Errorf("composio: create link: %w", err)
+ }
+ return resp.RedirectURL, nil
+}
+
+// completeTeamCallback writes the team account named by a verified state. A
+// workspace keeps one team account per app, so the previous one is revoked.
+func (s *Service) completeTeamCallback(ctx context.Context, claims stateClaims, connectedAccountID string) error {
+ store, err := s.teamStore()
+ if err != nil {
+ return err
+ }
+ workspaceID, err := util.ParseUUID(claims.WorkspaceID)
+ if err != nil {
+ return fmt.Errorf("composio: state has invalid workspace id: %w", err)
+ }
+ actorID, err := util.ParseUUID(claims.ConnectedBy)
+ if err != nil {
+ return fmt.Errorf("composio: state has invalid actor id: %w", err)
+ }
+ if claims.UserID != TeamComposioUserID(workspaceID) {
+ return ErrAccountVerification
+ }
+ if err := s.verifyAccountOwnership(ctx, connectedAccountID, claims.UserID, claims.AuthConfigID); err != nil {
+ return err
+ }
+ row, err := store.UpsertWorkspaceComposioConnection(ctx, db.UpsertWorkspaceComposioConnectionParams{
+ WorkspaceID: workspaceID,
+ ToolkitSlug: claims.ToolkitSlug,
+ AuthConfigID: claims.AuthConfigID,
+ ConnectedAccountID: connectedAccountID,
+ ComposioUserID: claims.UserID,
+ ConnectedBy: actorID,
+ })
+ if err != nil {
+ return fmt.Errorf("composio: upsert team connection: %w", err)
+ }
+ replaced, err := store.RevokeOtherWorkspaceComposioConnections(ctx, db.RevokeOtherWorkspaceComposioConnectionsParams{
+ WorkspaceID: workspaceID,
+ ToolkitSlug: claims.ToolkitSlug,
+ ID: row.ID,
+ })
+ if err != nil {
+ return fmt.Errorf("composio: revoke replaced team connections: %w", err)
+ }
+ for _, old := range replaced {
+ s.revokeUpstream(ctx, old.ConnectedAccountID)
+ }
+ return nil
+}
+
+// DisconnectTeam revokes a team account upstream and marks it revoked.
+// Idempotent like Disconnect.
+func (s *Service) DisconnectTeam(ctx context.Context, workspaceID, connectionID pgtype.UUID) (db.WorkspaceComposioConnection, error) {
+ store, err := s.teamStore()
+ if err != nil {
+ return db.WorkspaceComposioConnection{}, err
+ }
+ row, err := store.GetWorkspaceComposioConnection(ctx, db.GetWorkspaceComposioConnectionParams{ID: connectionID, WorkspaceID: workspaceID})
+ if err != nil {
+ return db.WorkspaceComposioConnection{}, ErrConnectionNotFound
+ }
+ if row.Status == "revoked" {
+ return row, nil
+ }
+ if err := s.sdk.RevokeConnection(ctx, row.ConnectedAccountID); err != nil && !isNotFound(err) {
+ return row, fmt.Errorf("composio: revoke connection: %w", err)
+ }
+ if err := s.sdk.DeleteConnectedAccount(ctx, row.ConnectedAccountID); err != nil && !isNotFound(err) {
+ return row, fmt.Errorf("composio: delete connected account: %w", err)
+ }
+ if err := store.SetWorkspaceComposioConnectionStatus(ctx, db.SetWorkspaceComposioConnectionStatusParams{
+ ID: row.ID, WorkspaceID: workspaceID, Status: "revoked",
+ }); err != nil {
+ return row, fmt.Errorf("composio: mark revoked: %w", err)
+ }
+ row.Status = "revoked"
+ return row, nil
+}
+
+func (s *Service) revokeUpstream(ctx context.Context, connectedAccountID string) {
+ if err := s.sdk.RevokeConnection(ctx, connectedAccountID); err != nil && !isNotFound(err) {
+ return
+ }
+ _ = s.sdk.DeleteConnectedAccount(ctx, connectedAccountID)
+}
+
+// ensureAuthConfig returns the toolkit's auth config, creating one with
+// Composio's managed app when the project has none and the toolkit offers
+// managed auth. This is what lets every catalog app connect without a
+// dashboard step.
+func (s *Service) ensureAuthConfig(ctx context.Context, slug string) (string, error) {
+ id, err := s.authConfigForToolkit(ctx, slug)
+ if err != nil || id != "" {
+ return id, err
+ }
+ tools, err := s.toolSDK()
+ if err != nil {
+ return "", ErrToolkitNotSupported
+ }
+ tk, err := tools.GetToolkit(ctx, slug)
+ if err != nil {
+ if isNotFound(err) {
+ return "", ErrToolkitNotSupported
+ }
+ return "", fmt.Errorf("composio: get toolkit: %w", err)
+ }
+ if len(tk.ComposioManagedAuthSchemes) == 0 {
+ return "", ErrToolkitNotSupported
+ }
+ s.authCreateMu.Lock()
+ defer s.authCreateMu.Unlock()
+ // Another request may have created it while this one waited.
+ s.invalidateAuthConfigs()
+ if id, err := s.authConfigForToolkit(ctx, slug); err != nil || id != "" {
+ return id, err
+ }
+ id, err = tools.CreateManagedAuthConfig(ctx, slug)
+ if err != nil {
+ return "", fmt.Errorf("composio: create managed auth config: %w", err)
+ }
+ s.invalidateAuthConfigs()
+ return id, nil
+}
+
+func (s *Service) invalidateAuthConfigs() {
+ s.authCacheMu.Lock()
+ s.authCacheExp = time.Time{}
+ s.authCacheMu.Unlock()
+}
+
+// ---- tools ----------------------------------------------------------------
+
+const toolCacheTTL = 10 * time.Minute
+
+type toolCacheEntry struct {
+ tools []sdk.Tool
+ exp time.Time
+}
+
+type toolCache struct {
+ mu sync.Mutex
+ entries map[string]toolCacheEntry
+}
+
+// ListToolkitTools returns a toolkit's tools, cached briefly. The full list is
+// fetched once per toolkit; search filters it locally.
+func (s *Service) ListToolkitTools(ctx context.Context, toolkitSlug string) ([]sdk.Tool, error) {
+ tools, err := s.toolSDK()
+ if err != nil {
+ return nil, err
+ }
+ slug := strings.ToLower(strings.TrimSpace(toolkitSlug))
+ s.tools.mu.Lock()
+ if e, ok := s.tools.entries[slug]; ok && s.now().Before(e.exp) {
+ s.tools.mu.Unlock()
+ return e.tools, nil
+ }
+ s.tools.mu.Unlock()
+
+ var out []sdk.Tool
+ cursor := ""
+ for page := 0; page < maxToolkitPages; page++ {
+ resp, err := tools.ListTools(ctx, sdk.ListToolsRequest{ToolkitSlug: slug, Limit: listPageLimit, Cursor: cursor})
+ if err != nil {
+ return nil, fmt.Errorf("composio: list tools: %w", err)
+ }
+ for _, t := range resp.Items {
+ if !t.IsDeprecated {
+ out = append(out, t)
+ }
+ }
+ if resp.NextCursor == "" {
+ break
+ }
+ cursor = resp.NextCursor
+ }
+ s.tools.mu.Lock()
+ if s.tools.entries == nil {
+ s.tools.entries = map[string]toolCacheEntry{}
+ }
+ s.tools.entries[slug] = toolCacheEntry{tools: out, exp: s.now().Add(toolCacheTTL)}
+ s.tools.mu.Unlock()
+ return out, nil
+}
+
+// GetTool returns one tool definition, from the toolkit cache when warm.
+func (s *Service) GetTool(ctx context.Context, toolkitSlug, toolSlug string) (*sdk.Tool, error) {
+ tools, err := s.toolSDK()
+ if err != nil {
+ return nil, err
+ }
+ upper := strings.ToUpper(strings.TrimSpace(toolSlug))
+ if list, err := s.ListToolkitTools(ctx, toolkitSlug); err == nil {
+ for i := range list {
+ if strings.EqualFold(list[i].Slug, upper) {
+ return &list[i], nil
+ }
+ }
+ }
+ t, err := tools.GetTool(ctx, upper)
+ if err != nil {
+ return nil, err
+ }
+ if !strings.EqualFold(t.Toolkit.Slug, toolkitSlug) {
+ return nil, fmt.Errorf("composio: tool %s does not belong to %s", upper, toolkitSlug)
+ }
+ return t, nil
+}
+
+// ExecuteTool runs a tool against one connected account.
+func (s *Service) ExecuteTool(ctx context.Context, connectedAccountID string, tool sdk.Tool, args map[string]any) (*sdk.ExecuteToolResponse, error) {
+ tools, err := s.toolSDK()
+ if err != nil {
+ return nil, err
+ }
+ version := tool.Version
+ if version == "" {
+ version = "latest"
+ }
+ return tools.ExecuteTool(ctx, tool.Slug, sdk.ExecuteToolRequest{
+ Arguments: args,
+ ConnectedAccountID: connectedAccountID,
+ Version: version,
+ })
+}
diff --git a/server/internal/runtimeapps/connected_app.go b/server/internal/runtimeapps/connected_app.go
index ec9307e4ec..9f765fdc41 100644
--- a/server/internal/runtimeapps/connected_app.go
+++ b/server/internal/runtimeapps/connected_app.go
@@ -12,6 +12,12 @@ type ConnectedApp struct {
ServerName string `json:"server_name"`
ToolkitSlug string `json:"toolkit_slug"`
ToolkitName string `json:"toolkit_name,omitempty"`
+ // AccountScope, Level and AccountStatus describe apps served by the Multica
+ // gateway: whose account a call acts as, what the agent may do, and whether
+ // that account is connected yet ("connected" / "not_connected").
+ AccountScope string `json:"account_scope,omitempty"`
+ Level string `json:"level,omitempty"`
+ AccountStatus string `json:"account_status,omitempty"`
}
// MCPOverlayResult carries both the secret-bearing MCP config overlay and the
diff --git a/server/internal/service/app_decision.go b/server/internal/service/app_decision.go
new file mode 100644
index 0000000000..2a4f9c762f
--- /dev/null
+++ b/server/internal/service/app_decision.go
@@ -0,0 +1,73 @@
+package service
+
+import (
+ "context"
+ "errors"
+ "fmt"
+
+ "github.com/jackc/pgx/v5"
+ "github.com/jackc/pgx/v5/pgtype"
+ "github.com/multica-ai/multica/server/internal/attribution"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+ "github.com/multica-ai/multica/server/pkg/dbid"
+ "github.com/multica-ai/multica/server/pkg/protocol"
+)
+
+// EnqueueAppDecisionRun resumes an agent on an issue after a person decided
+// on one of its app requests. The decision rides in the handoff note. A run
+// of the agent that is still waiting to start for the same person takes the
+// note along instead of a second run being queued.
+func (s *TaskService) EnqueueAppDecisionRun(ctx context.Context, issueID, agentID, actorID, requestID pgtype.UUID, note string) error {
+ issue, err := s.Queries.GetIssue(ctx, issueID)
+ if err != nil {
+ return fmt.Errorf("load issue: %w", err)
+ }
+ agent, err := s.Queries.GetAgent(ctx, agentID)
+ if err != nil {
+ return fmt.Errorf("load agent: %w", err)
+ }
+ if agent.ArchivedAt.Valid {
+ return ErrChatTaskAgentArchived
+ }
+ if !agent.RuntimeID.Valid {
+ return ErrChatTaskAgentNoRuntime
+ }
+ waiting, err := s.Queries.FindWaitingIssueRun(ctx, db.FindWaitingIssueRunParams{IssueID: issueID, AgentID: agentID, OriginatorUserID: actorID})
+ if err == nil {
+ folded, err := s.Queries.AppendQueuedTaskHandoffNote(ctx, db.AppendQueuedTaskHandoffNoteParams{ID: waiting, Note: note})
+ if err != nil {
+ return fmt.Errorf("fold decision into waiting run: %w", err)
+ }
+ if folded > 0 {
+ return nil
+ }
+ } else if !errors.Is(err, pgx.ErrNoRows) {
+ return fmt.Errorf("find waiting run: %w", err)
+ }
+ if err := guardIssueNotInTriage(ctx, s.Queries, issue.ID, OriginDerived); err != nil {
+ return err
+ }
+ overlay := s.buildRuntimeMCPOverlay(ctx, actorID, agent)
+ task, err := s.Queries.CreateWakeupTask(ctx, db.CreateWakeupTaskParams{
+ ID: dbid.NewV7(),
+ AgentID: agent.ID,
+ RuntimeID: agent.RuntimeID,
+ IssueID: issue.ID,
+ Priority: priorityToInt(issue.Priority),
+ TriggerSummary: pgtype.Text{String: "App request decided", Valid: true},
+ HandoffNote: pgtype.Text{String: note, Valid: true},
+ OriginatorUserID: actorID,
+ AccountableUserID: actorID,
+ OriginatorSource: pgtype.Text{String: string(attribution.SourceDirectHuman), Valid: true},
+ TriggerEvidenceKind: pgtype.Text{String: "app_action_request", Valid: true},
+ TriggerEvidenceRefID: requestID,
+ RuntimeMcpOverlay: overlay.Overlay,
+ RuntimeConnectedApps: overlay.ConnectedApps,
+ })
+ if err != nil {
+ return fmt.Errorf("create decision run: %w", err)
+ }
+ s.broadcastTaskEvent(ctx, protocol.EventTaskQueued, task)
+ s.NotifyTaskEnqueued(ctx, task)
+ return nil
+}
diff --git a/server/migrations/617_connected_apps.down.sql b/server/migrations/617_connected_apps.down.sql
new file mode 100644
index 0000000000..c624d41f86
--- /dev/null
+++ b/server/migrations/617_connected_apps.down.sql
@@ -0,0 +1,7 @@
+DROP TABLE IF EXISTS app_tool_class_override;
+DROP TABLE IF EXISTS workspace_app_setting;
+DROP TABLE IF EXISTS app_tool_call;
+DROP TABLE IF EXISTS app_action_request;
+DROP TABLE IF EXISTS app_action_rule;
+DROP TABLE IF EXISTS agent_app;
+DROP TABLE IF EXISTS workspace_composio_connection;
diff --git a/server/migrations/617_connected_apps.up.sql b/server/migrations/617_connected_apps.up.sql
new file mode 100644
index 0000000000..f7a7473e34
--- /dev/null
+++ b/server/migrations/617_connected_apps.up.sql
@@ -0,0 +1,156 @@
+-- MUL-8516: Connected Apps v2 (workspace team accounts, personal accounts,
+-- per-agent levels, per-action rules, confirmation requests, activity).
+--
+-- A personal account stays in user_composio_connection (one row per user,
+-- usable in every workspace the user belongs to). A team account is new: one
+-- Composio connected account owned by the workspace, created by an admin, used
+-- by every agent the workspace adds it to. Its composio_user_id is
+-- "ws_<workspace_id>" so a team account never shares a Composio user with a
+-- person.
+--
+-- No foreign keys (repo rule): workspace and agent teardown delete these rows
+-- explicitly. Every index is built concurrently in 618-628, following
+-- wecom_install_session (600-604), so no migration builds an index inline on a
+-- live table. The tables start empty, so the window between this migration
+-- and its indexes carries no load.
+CREATE TABLE IF NOT EXISTS workspace_composio_connection (
+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
+ workspace_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,
+ connected_by UUID NOT NULL,
+ status TEXT NOT NULL DEFAULT 'active'
+ CHECK (status IN ('active', 'expired', 'revoked')),
+ 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()
+);
+
+-- Which apps an agent may use, through which kind of account, at which level.
+-- account_scope: team = the workspace's team account
+-- personal = the account of whoever triggered the run
+-- level: read = read tools only
+-- write = everything the action rules allow
+-- confirm_writes = every non-read call needs confirmation
+CREATE TABLE IF NOT EXISTS agent_app (
+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
+ workspace_id UUID NOT NULL,
+ agent_id UUID NOT NULL,
+ toolkit_slug TEXT NOT NULL,
+ account_scope TEXT NOT NULL CHECK (account_scope IN ('team', 'personal')),
+ level TEXT NOT NULL DEFAULT 'confirm_writes'
+ CHECK (level IN ('read', 'write', 'confirm_writes')),
+ created_by UUID,
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
+);
+
+-- Per-action rules. owner_user_id NULL is the workspace's rule for the team
+-- account; a user id is that member's own rule for their personal account in
+-- this workspace. A missing row means the built-in default for the class.
+CREATE TABLE IF NOT EXISTS app_action_rule (
+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
+ workspace_id UUID NOT NULL,
+ owner_user_id UUID,
+ toolkit_slug TEXT NOT NULL,
+ action_class TEXT NOT NULL
+ CHECK (action_class IN ('read', 'write', 'send', 'delete', 'share')),
+ policy TEXT NOT NULL CHECK (policy IN ('allow', 'confirm', 'block')),
+ updated_by UUID,
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
+);
+
+-- A call an agent made that waits on a person: an action that needs
+-- confirmation, or an app the person still has to connect. The arguments are
+-- what the agent asked for; approved_arguments is what the approver accepted
+-- (equal unless they edited it) and is exactly what Multica executes.
+CREATE TABLE IF NOT EXISTS app_action_request (
+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
+ workspace_id UUID NOT NULL,
+ kind TEXT NOT NULL DEFAULT 'action' CHECK (kind IN ('action', 'connect')),
+ status TEXT NOT NULL DEFAULT 'pending'
+ CHECK (status IN ('pending', 'approved', 'rejected', 'expired', 'failed', 'cancelled')),
+ task_id UUID NOT NULL,
+ agent_id UUID NOT NULL,
+ issue_id UUID,
+ chat_session_id UUID,
+ approver_user_id UUID NOT NULL,
+ account_scope TEXT NOT NULL CHECK (account_scope IN ('team', 'personal')),
+ toolkit_slug TEXT NOT NULL,
+ tool_slug TEXT NOT NULL DEFAULT '',
+ action_class TEXT NOT NULL DEFAULT 'send',
+ arguments JSONB NOT NULL DEFAULT '{}'::jsonb,
+ -- One sentence from the agent: why it wants to make this call.
+ summary TEXT NOT NULL DEFAULT '',
+ approved_arguments JSONB,
+ result JSONB,
+ error TEXT,
+ reason TEXT,
+ expires_at TIMESTAMPTZ NOT NULL,
+ reminded_at TIMESTAMPTZ,
+ decided_by UUID,
+ decided_at TIMESTAMPTZ,
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
+);
+
+-- One row per tool call that reached the gateway, whatever its outcome. Backs
+-- the activity list on app pages. Arguments are not stored here.
+CREATE TABLE IF NOT EXISTS app_tool_call (
+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
+ workspace_id UUID NOT NULL,
+ task_id UUID,
+ agent_id UUID NOT NULL,
+ issue_id UUID,
+ chat_session_id UUID,
+ triggered_by UUID,
+ account_scope TEXT NOT NULL,
+ account_owner_user_id UUID,
+ toolkit_slug TEXT NOT NULL,
+ tool_slug TEXT NOT NULL,
+ action_class TEXT NOT NULL,
+ outcome TEXT NOT NULL
+ CHECK (outcome IN ('ok', 'error', 'blocked', 'pending', 'approved', 'rejected', 'rate_limited')),
+ request_id UUID,
+ error TEXT,
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now()
+);
+
+-- Which apps members may connect. 'all' is every app in the catalog,
+-- 'curated' only the curated ones, 'custom' only allowed_toolkits. No row
+-- means 'all'.
+CREATE TABLE IF NOT EXISTS workspace_app_setting (
+ workspace_id UUID PRIMARY KEY,
+ catalog_mode TEXT NOT NULL DEFAULT 'all' CHECK (catalog_mode IN ('all', 'curated', 'custom')),
+ allowed_toolkits TEXT[] NOT NULL DEFAULT '{}',
+ updated_by UUID,
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
+);
+
+-- An admin's correction of how one tool is classified in this workspace. It
+-- wins over the curated table and the name heuristics.
+CREATE TABLE IF NOT EXISTS app_tool_class_override (
+ workspace_id UUID NOT NULL,
+ toolkit_slug TEXT NOT NULL,
+ tool_slug TEXT NOT NULL,
+ action_class TEXT NOT NULL
+ CHECK (action_class IN ('read', 'write', 'send', 'delete', 'share')),
+ updated_by UUID,
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ PRIMARY KEY (workspace_id, toolkit_slug, tool_slug)
+);
+
+-- Carry over agents that allowlisted toolkits under the first version. That
+-- version mounted the agent owner's own accounts; the closest equivalent is a
+-- personal app, and confirm_writes keeps every write behind a confirmation
+-- until the owner chooses otherwise. The feature flag never shipped, so this
+-- touches only internal workspaces. DISTINCT guards duplicate slugs in a row.
+INSERT INTO agent_app (workspace_id, agent_id, toolkit_slug, account_scope, level, created_by)
+SELECT DISTINCT a.workspace_id, a.id, lower(btrim(slug)), 'personal', 'confirm_writes', a.owner_id
+FROM agent a, unnest(a.composio_toolkit_allowlist) AS slug
+WHERE a.composio_toolkit_allowlist IS NOT NULL
+ AND cardinality(a.composio_toolkit_allowlist) > 0
+ AND btrim(slug) <> '';
diff --git a/server/migrations/618_workspace_composio_connection_account_idx.down.sql b/server/migrations/618_workspace_composio_connection_account_idx.down.sql
new file mode 100644
index 0000000000..bf01da295e
--- /dev/null
+++ b/server/migrations/618_workspace_composio_connection_account_idx.down.sql
@@ -0,0 +1 @@
+DROP INDEX CONCURRENTLY IF EXISTS idx_workspace_composio_connection_account;
diff --git a/server/migrations/618_workspace_composio_connection_account_idx.up.sql b/server/migrations/618_workspace_composio_connection_account_idx.up.sql
new file mode 100644
index 0000000000..419d5a3565
--- /dev/null
+++ b/server/migrations/618_workspace_composio_connection_account_idx.up.sql
@@ -0,0 +1,3 @@
+-- Upsert key for a team account callback; one row per Composio account.
+CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS idx_workspace_composio_connection_account
+ ON workspace_composio_connection (workspace_id, connected_account_id);
diff --git a/server/migrations/619_workspace_composio_connection_status_idx.down.sql b/server/migrations/619_workspace_composio_connection_status_idx.down.sql
new file mode 100644
index 0000000000..2e4f097cbf
--- /dev/null
+++ b/server/migrations/619_workspace_composio_connection_status_idx.down.sql
@@ -0,0 +1 @@
+DROP INDEX CONCURRENTLY IF EXISTS idx_workspace_composio_connection_status;
diff --git a/server/migrations/619_workspace_composio_connection_status_idx.up.sql b/server/migrations/619_workspace_composio_connection_status_idx.up.sql
new file mode 100644
index 0000000000..eacfe88ff6
--- /dev/null
+++ b/server/migrations/619_workspace_composio_connection_status_idx.up.sql
@@ -0,0 +1,3 @@
+-- Hot read: the workspace's active team accounts (app list, run setup, gateway).
+CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_workspace_composio_connection_status
+ ON workspace_composio_connection (workspace_id, status, toolkit_slug);
diff --git a/server/migrations/620_agent_app_agent_toolkit_idx.down.sql b/server/migrations/620_agent_app_agent_toolkit_idx.down.sql
new file mode 100644
index 0000000000..9736874013
--- /dev/null
+++ b/server/migrations/620_agent_app_agent_toolkit_idx.down.sql
@@ -0,0 +1 @@
+DROP INDEX CONCURRENTLY IF EXISTS idx_agent_app_agent_toolkit;
diff --git a/server/migrations/620_agent_app_agent_toolkit_idx.up.sql b/server/migrations/620_agent_app_agent_toolkit_idx.up.sql
new file mode 100644
index 0000000000..ed21259f61
--- /dev/null
+++ b/server/migrations/620_agent_app_agent_toolkit_idx.up.sql
@@ -0,0 +1,3 @@
+-- One entry per app per agent; the upsert key for the agent's app list.
+CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS idx_agent_app_agent_toolkit
+ ON agent_app (agent_id, toolkit_slug);
diff --git a/server/migrations/621_agent_app_workspace_toolkit_idx.down.sql b/server/migrations/621_agent_app_workspace_toolkit_idx.down.sql
new file mode 100644
index 0000000000..575b5105c5
--- /dev/null
+++ b/server/migrations/621_agent_app_workspace_toolkit_idx.down.sql
@@ -0,0 +1 @@
+DROP INDEX CONCURRENTLY IF EXISTS idx_agent_app_workspace_toolkit;
diff --git a/server/migrations/621_agent_app_workspace_toolkit_idx.up.sql b/server/migrations/621_agent_app_workspace_toolkit_idx.up.sql
new file mode 100644
index 0000000000..d0a38bf076
--- /dev/null
+++ b/server/migrations/621_agent_app_workspace_toolkit_idx.up.sql
@@ -0,0 +1,3 @@
+-- "Which agents use this app" on app pages and the disconnect impact check.
+CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_agent_app_workspace_toolkit
+ ON agent_app (workspace_id, toolkit_slug);
diff --git a/server/migrations/622_app_action_rule_scope_idx.down.sql b/server/migrations/622_app_action_rule_scope_idx.down.sql
new file mode 100644
index 0000000000..1d38aecff6
--- /dev/null
+++ b/server/migrations/622_app_action_rule_scope_idx.down.sql
@@ -0,0 +1 @@
+DROP INDEX CONCURRENTLY IF EXISTS idx_app_action_rule_scope;
diff --git a/server/migrations/622_app_action_rule_scope_idx.up.sql b/server/migrations/622_app_action_rule_scope_idx.up.sql
new file mode 100644
index 0000000000..fa8f498218
--- /dev/null
+++ b/server/migrations/622_app_action_rule_scope_idx.up.sql
@@ -0,0 +1,4 @@
+-- One rule per class for the team account and per member for their personal
+-- account. NULL owner (team) folds to the nil UUID so it is unique too.
+CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS idx_app_action_rule_scope
+ ON app_action_rule (workspace_id, toolkit_slug, action_class, COALESCE(owner_user_id, '00000000-0000-0000-0000-000000000000'::uuid));
diff --git a/server/migrations/623_app_action_request_issue_idx.down.sql b/server/migrations/623_app_action_request_issue_idx.down.sql
new file mode 100644
index 0000000000..389196c6c0
--- /dev/null
+++ b/server/migrations/623_app_action_request_issue_idx.down.sql
@@ -0,0 +1 @@
+DROP INDEX CONCURRENTLY IF EXISTS idx_app_action_request_issue;
diff --git a/server/migrations/623_app_action_request_issue_idx.up.sql b/server/migrations/623_app_action_request_issue_idx.up.sql
new file mode 100644
index 0000000000..f2c771fa6b
--- /dev/null
+++ b/server/migrations/623_app_action_request_issue_idx.up.sql
@@ -0,0 +1,4 @@
+-- Requests shown on an issue's timeline.
+CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_app_action_request_issue
+ ON app_action_request (issue_id, created_at)
+ WHERE issue_id IS NOT NULL;
diff --git a/server/migrations/624_app_action_request_pending_idx.down.sql b/server/migrations/624_app_action_request_pending_idx.down.sql
new file mode 100644
index 0000000000..5a1bf61fd4
--- /dev/null
+++ b/server/migrations/624_app_action_request_pending_idx.down.sql
@@ -0,0 +1 @@
+DROP INDEX CONCURRENTLY IF EXISTS idx_app_action_request_pending;
diff --git a/server/migrations/624_app_action_request_pending_idx.up.sql b/server/migrations/624_app_action_request_pending_idx.up.sql
new file mode 100644
index 0000000000..8b81200393
--- /dev/null
+++ b/server/migrations/624_app_action_request_pending_idx.up.sql
@@ -0,0 +1,4 @@
+-- The expiry sweep and a member's pending list only ever read pending rows.
+CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_app_action_request_pending
+ ON app_action_request (expires_at)
+ WHERE status = 'pending';
diff --git a/server/migrations/625_app_tool_call_workspace_idx.down.sql b/server/migrations/625_app_tool_call_workspace_idx.down.sql
new file mode 100644
index 0000000000..d5690bef09
--- /dev/null
+++ b/server/migrations/625_app_tool_call_workspace_idx.down.sql
@@ -0,0 +1 @@
+DROP INDEX CONCURRENTLY IF EXISTS idx_app_tool_call_workspace;
diff --git a/server/migrations/625_app_tool_call_workspace_idx.up.sql b/server/migrations/625_app_tool_call_workspace_idx.up.sql
new file mode 100644
index 0000000000..05290754a6
--- /dev/null
+++ b/server/migrations/625_app_tool_call_workspace_idx.up.sql
@@ -0,0 +1,3 @@
+-- Activity on an app page, newest first.
+CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_app_tool_call_workspace
+ ON app_tool_call (workspace_id, toolkit_slug, created_at DESC);
diff --git a/server/migrations/626_app_action_request_task_idx.down.sql b/server/migrations/626_app_action_request_task_idx.down.sql
new file mode 100644
index 0000000000..315866b6ff
--- /dev/null
+++ b/server/migrations/626_app_action_request_task_idx.down.sql
@@ -0,0 +1 @@
+DROP INDEX CONCURRENTLY IF EXISTS idx_app_action_request_task;
diff --git a/server/migrations/626_app_action_request_task_idx.up.sql b/server/migrations/626_app_action_request_task_idx.up.sql
new file mode 100644
index 0000000000..61c3ac16e8
--- /dev/null
+++ b/server/migrations/626_app_action_request_task_idx.up.sql
@@ -0,0 +1,3 @@
+-- Requests of one run: duplicate detection and the chat view.
+CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_app_action_request_task
+ ON app_action_request (task_id);
diff --git a/server/migrations/627_app_tool_call_issue_idx.down.sql b/server/migrations/627_app_tool_call_issue_idx.down.sql
new file mode 100644
index 0000000000..c708794fd7
--- /dev/null
+++ b/server/migrations/627_app_tool_call_issue_idx.down.sql
@@ -0,0 +1 @@
+DROP INDEX CONCURRENTLY IF EXISTS idx_app_tool_call_issue;
diff --git a/server/migrations/627_app_tool_call_issue_idx.up.sql b/server/migrations/627_app_tool_call_issue_idx.up.sql
new file mode 100644
index 0000000000..8db02a8716
--- /dev/null
+++ b/server/migrations/627_app_tool_call_issue_idx.up.sql
@@ -0,0 +1,4 @@
+-- Apps an issue's runs used: the call chips and the issue sidebar.
+CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_app_tool_call_issue
+ ON app_tool_call (issue_id, created_at)
+ WHERE issue_id IS NOT NULL;
diff --git a/server/migrations/628_app_action_request_chat_idx.down.sql b/server/migrations/628_app_action_request_chat_idx.down.sql
new file mode 100644
index 0000000000..8304a9784d
--- /dev/null
+++ b/server/migrations/628_app_action_request_chat_idx.down.sql
@@ -0,0 +1 @@
+DROP INDEX CONCURRENTLY IF EXISTS idx_app_action_request_chat;
diff --git a/server/migrations/628_app_action_request_chat_idx.up.sql b/server/migrations/628_app_action_request_chat_idx.up.sql
new file mode 100644
index 0000000000..ae4e200cab
--- /dev/null
+++ b/server/migrations/628_app_action_request_chat_idx.up.sql
@@ -0,0 +1,4 @@
+-- Requests shown in a chat session.
+CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_app_action_request_chat
+ ON app_action_request (chat_session_id, created_at)
+ WHERE chat_session_id IS NOT NULL;
diff --git a/server/pkg/composio/auth_configs.go b/server/pkg/composio/auth_configs.go
index 9d607c5705..77a8c0dee5 100644
--- a/server/pkg/composio/auth_configs.go
+++ b/server/pkg/composio/auth_configs.go
@@ -2,6 +2,7 @@ package composio
import (
"context"
+ "errors"
"net/http"
"net/url"
"strconv"
@@ -55,6 +56,46 @@ type ListAuthConfigsResponse struct {
TotalItems int `json:"total_items,omitempty"`
}
+type createAuthConfigRequest struct {
+ Toolkit createAuthConfigToolkit `json:"toolkit"`
+ AuthConfig createAuthConfigBody `json:"auth_config"`
+}
+
+type createAuthConfigToolkit struct {
+ Slug string `json:"slug"`
+}
+
+type createAuthConfigBody struct {
+ Type string `json:"type"`
+}
+
+type createAuthConfigResponse struct {
+ AuthConfig AuthConfig `json:"auth_config"`
+}
+
+// CreateManagedAuthConfig registers an auth config for a toolkit that uses
+// Composio's managed OAuth app, making the toolkit connectable in the project.
+// It returns the new auth_config_id.
+//
+// Spec: https://docs.composio.dev/reference/v3/api-reference/auth-configs/postAuthConfigs
+func (c *Client) CreateManagedAuthConfig(ctx context.Context, toolkitSlug string) (string, error) {
+ if toolkitSlug == "" {
+ return "", errors.New("composio: CreateManagedAuthConfig: toolkitSlug is required")
+ }
+ var out createAuthConfigResponse
+ body := createAuthConfigRequest{
+ Toolkit: createAuthConfigToolkit{Slug: toolkitSlug},
+ AuthConfig: createAuthConfigBody{Type: "use_composio_managed_auth"},
+ }
+ if err := c.do(c.newRequest(ctx).SetBody(body), http.MethodPost, "/auth_configs", &out); err != nil {
+ return "", err
+ }
+ if out.AuthConfig.ID == "" {
+ return "", errors.New("composio: CreateManagedAuthConfig: response has no auth config id")
+ }
+ return out.AuthConfig.ID, nil
+}
+
// 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.
diff --git a/server/pkg/composio/toolkits.go b/server/pkg/composio/toolkits.go
index 2b5b34f0cb..3e1ee1b42c 100644
--- a/server/pkg/composio/toolkits.go
+++ b/server/pkg/composio/toolkits.go
@@ -19,6 +19,12 @@ type Toolkit struct {
Categories []string `json:"categories,omitempty"`
AuthSchemes []string `json:"auth_schemes,omitempty"`
Meta map[string]any `json:"meta,omitempty"`
+ // ComposioManagedAuthSchemes lists the schemes Composio can authenticate
+ // with its own managed app — the toolkit is connectable without the project
+ // bringing an OAuth client.
+ ComposioManagedAuthSchemes []string `json:"composio_managed_auth_schemes,omitempty"`
+ // NoAuth is true for toolkits that need no credential at all.
+ NoAuth bool `json:"no_auth,omitempty"`
}
// ListToolkitsRequest carries the optional filters of GET /toolkits.
diff --git a/server/pkg/composio/tools.go b/server/pkg/composio/tools.go
index 1548482589..808f93ef1d 100644
--- a/server/pkg/composio/tools.go
+++ b/server/pkg/composio/tools.go
@@ -5,6 +5,7 @@ import (
"errors"
"net/http"
"net/url"
+ "strconv"
)
// ExecuteToolRequest is the body for POST /tools/execute/{tool_slug}.
@@ -53,6 +54,77 @@ type ExecuteToolResponse struct {
SessionInfo map[string]any `json:"session_info,omitempty"`
}
+// Tool mirrors the subset of a Composio tool definition the gateway exposes to
+// agents: what it is, what it takes, and the hints used to classify it.
+//
+// Spec: https://docs.composio.dev/reference/v3/api-reference/tools/getTools
+type Tool struct {
+ Slug string `json:"slug"`
+ Name string `json:"name,omitempty"`
+ Description string `json:"description,omitempty"`
+ InputParameters map[string]any `json:"input_parameters,omitempty"`
+ Tags []string `json:"tags,omitempty"`
+ Toolkit Toolkit `json:"toolkit"`
+ Version string `json:"version,omitempty"`
+ IsDeprecated bool `json:"is_deprecated,omitempty"`
+}
+
+// ListToolsRequest collects the filters of GET /tools.
+type ListToolsRequest struct {
+ ToolkitSlug string
+ Search string
+ // Important limits the result to the toolkit's most-used tools.
+ Important bool
+ Limit int
+ Cursor string
+}
+
+// ListToolsResponse is the typed paginated response.
+type ListToolsResponse struct {
+ Items []Tool `json:"items"`
+ NextCursor string `json:"next_cursor,omitempty"`
+ TotalItems int `json:"total_items,omitempty"`
+}
+
+// ListTools returns tool definitions, optionally filtered to one toolkit.
+func (c *Client) ListTools(ctx context.Context, req ListToolsRequest) (*ListToolsResponse, error) {
+ q := url.Values{}
+ if req.ToolkitSlug != "" {
+ q.Set("toolkit_slug", req.ToolkitSlug)
+ }
+ if req.Search != "" {
+ q.Set("search", req.Search)
+ }
+ if req.Important {
+ q.Set("important", "true")
+ }
+ if req.Limit > 0 {
+ q.Set("limit", strconv.Itoa(req.Limit))
+ }
+ if req.Cursor != "" {
+ q.Set("cursor", req.Cursor)
+ }
+ q.Set("toolkit_versions", "latest")
+ var out ListToolsResponse
+ if err := c.do(c.newRequest(ctx), http.MethodGet, "/tools?"+q.Encode(), &out); err != nil {
+ return nil, err
+ }
+ return &out, nil
+}
+
+// GetTool fetches one tool definition by slug, at its latest version.
+func (c *Client) GetTool(ctx context.Context, toolSlug string) (*Tool, error) {
+ if toolSlug == "" {
+ return nil, errors.New("composio: GetTool: toolSlug is required")
+ }
+ var out Tool
+ if err := c.do(c.newRequest(ctx),
+ http.MethodGet, "/tools/"+url.PathEscape(toolSlug)+"?toolkit_versions=latest", &out); err != nil {
+ return nil, err
+ }
+ return &out, nil
+}
+
// ExecuteTool calls a Composio tool by its slug
// (SCREAMING_SNAKE_CASE, e.g. GITHUB_CREATE_ISSUE).
//
diff --git a/server/pkg/db/generated/connected_apps.sql.go b/server/pkg/db/generated/connected_apps.sql.go
new file mode 100644
index 0000000000..b3782b0fb4
--- /dev/null
+++ b/server/pkg/db/generated/connected_apps.sql.go
@@ -0,0 +1,2011 @@
+// Code generated by sqlc. DO NOT EDIT.
+// versions:
+// sqlc v1.31.1
+// source: connected_apps.sql
+
+package db
+
+import (
+ "context"
+
+ "github.com/jackc/pgx/v5/pgtype"
+)
+
+const appendQueuedTaskHandoffNote = `-- name: AppendQueuedTaskHandoffNote :execrows
+UPDATE agent_task_queue
+SET handoff_note = CASE
+ WHEN handoff_note IS NULL OR handoff_note = '' THEN $2::text
+ ELSE handoff_note || E'\n\n' || $2::text
+ END
+WHERE id = $1 AND status = 'queued'
+`
+
+type AppendQueuedTaskHandoffNoteParams struct {
+ ID pgtype.UUID `json:"id"`
+ Note string `json:"note"`
+}
+
+// Folds a decision into a run that has not been claimed yet, so approving a
+// batch of requests starts one run instead of one per request.
+func (q *Queries) AppendQueuedTaskHandoffNote(ctx context.Context, arg AppendQueuedTaskHandoffNoteParams) (int64, error) {
+ result, err := q.db.Exec(ctx, appendQueuedTaskHandoffNote, arg.ID, arg.Note)
+ if err != nil {
+ return 0, err
+ }
+ return result.RowsAffected(), nil
+}
+
+const cancelAppActionRequest = `-- name: CancelAppActionRequest :one
+UPDATE app_action_request
+SET status = 'cancelled', updated_at = now()
+WHERE id = $1 AND workspace_id = $2 AND status = 'pending'
+RETURNING id, workspace_id, kind, status, task_id, agent_id, issue_id, chat_session_id, approver_user_id, account_scope, toolkit_slug, tool_slug, action_class, arguments, summary, approved_arguments, result, error, reason, expires_at, reminded_at, decided_by, decided_at, created_at, updated_at
+`
+
+type CancelAppActionRequestParams struct {
+ ID pgtype.UUID `json:"id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+}
+
+// Withdraws one pending request whose approver may no longer act on it.
+func (q *Queries) CancelAppActionRequest(ctx context.Context, arg CancelAppActionRequestParams) (AppActionRequest, error) {
+ row := q.db.QueryRow(ctx, cancelAppActionRequest, arg.ID, arg.WorkspaceID)
+ var i AppActionRequest
+ err := row.Scan(
+ &i.ID,
+ &i.WorkspaceID,
+ &i.Kind,
+ &i.Status,
+ &i.TaskID,
+ &i.AgentID,
+ &i.IssueID,
+ &i.ChatSessionID,
+ &i.ApproverUserID,
+ &i.AccountScope,
+ &i.ToolkitSlug,
+ &i.ToolSlug,
+ &i.ActionClass,
+ &i.Arguments,
+ &i.Summary,
+ &i.ApprovedArguments,
+ &i.Result,
+ &i.Error,
+ &i.Reason,
+ &i.ExpiresAt,
+ &i.RemindedAt,
+ &i.DecidedBy,
+ &i.DecidedAt,
+ &i.CreatedAt,
+ &i.UpdatedAt,
+ )
+ return i, err
+}
+
+const cancelPendingAppActionRequestsForApprover = `-- name: CancelPendingAppActionRequestsForApprover :many
+UPDATE app_action_request
+SET status = 'cancelled', updated_at = now()
+WHERE workspace_id = $1 AND approver_user_id = $2 AND status = 'pending'
+RETURNING id, workspace_id, kind, status, task_id, agent_id, issue_id, chat_session_id, approver_user_id, account_scope, toolkit_slug, tool_slug, action_class, arguments, summary, approved_arguments, result, error, reason, expires_at, reminded_at, decided_by, decided_at, created_at, updated_at
+`
+
+type CancelPendingAppActionRequestsForApproverParams struct {
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ ApproverUserID pgtype.UUID `json:"approver_user_id"`
+}
+
+// A member leaving the workspace withdraws everything waiting on them.
+func (q *Queries) CancelPendingAppActionRequestsForApprover(ctx context.Context, arg CancelPendingAppActionRequestsForApproverParams) ([]AppActionRequest, error) {
+ rows, err := q.db.Query(ctx, cancelPendingAppActionRequestsForApprover, arg.WorkspaceID, arg.ApproverUserID)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ items := []AppActionRequest{}
+ for rows.Next() {
+ var i AppActionRequest
+ if err := rows.Scan(
+ &i.ID,
+ &i.WorkspaceID,
+ &i.Kind,
+ &i.Status,
+ &i.TaskID,
+ &i.AgentID,
+ &i.IssueID,
+ &i.ChatSessionID,
+ &i.ApproverUserID,
+ &i.AccountScope,
+ &i.ToolkitSlug,
+ &i.ToolSlug,
+ &i.ActionClass,
+ &i.Arguments,
+ &i.Summary,
+ &i.ApprovedArguments,
+ &i.Result,
+ &i.Error,
+ &i.Reason,
+ &i.ExpiresAt,
+ &i.RemindedAt,
+ &i.DecidedBy,
+ &i.DecidedAt,
+ &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 cancelPendingTeamAppActionRequests = `-- name: CancelPendingTeamAppActionRequests :many
+UPDATE app_action_request
+SET status = 'cancelled', updated_at = now()
+WHERE workspace_id = $1 AND toolkit_slug = $2 AND account_scope = 'team' AND status = 'pending'
+RETURNING id, workspace_id, kind, status, task_id, agent_id, issue_id, chat_session_id, approver_user_id, account_scope, toolkit_slug, tool_slug, action_class, arguments, summary, approved_arguments, result, error, reason, expires_at, reminded_at, decided_by, decided_at, created_at, updated_at
+`
+
+type CancelPendingTeamAppActionRequestsParams struct {
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ ToolkitSlug string `json:"toolkit_slug"`
+}
+
+// Disconnecting a team account cancels what was waiting to use it.
+func (q *Queries) CancelPendingTeamAppActionRequests(ctx context.Context, arg CancelPendingTeamAppActionRequestsParams) ([]AppActionRequest, error) {
+ rows, err := q.db.Query(ctx, cancelPendingTeamAppActionRequests, arg.WorkspaceID, arg.ToolkitSlug)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ items := []AppActionRequest{}
+ for rows.Next() {
+ var i AppActionRequest
+ if err := rows.Scan(
+ &i.ID,
+ &i.WorkspaceID,
+ &i.Kind,
+ &i.Status,
+ &i.TaskID,
+ &i.AgentID,
+ &i.IssueID,
+ &i.ChatSessionID,
+ &i.ApproverUserID,
+ &i.AccountScope,
+ &i.ToolkitSlug,
+ &i.ToolSlug,
+ &i.ActionClass,
+ &i.Arguments,
+ &i.Summary,
+ &i.ApprovedArguments,
+ &i.Result,
+ &i.Error,
+ &i.Reason,
+ &i.ExpiresAt,
+ &i.RemindedAt,
+ &i.DecidedBy,
+ &i.DecidedAt,
+ &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 claimAppActionRequestReminders = `-- name: ClaimAppActionRequestReminders :many
+UPDATE app_action_request
+SET reminded_at = now(), updated_at = now()
+WHERE id IN (
+ SELECT r.id FROM app_action_request r
+ WHERE r.status = 'pending' AND r.reminded_at IS NULL
+ AND r.expires_at <= now() + interval '2 hours'
+ AND r.expires_at > now()
+ ORDER BY r.expires_at
+ LIMIT 200
+ FOR UPDATE SKIP LOCKED
+)
+RETURNING id, workspace_id, kind, status, task_id, agent_id, issue_id, chat_session_id, approver_user_id, account_scope, toolkit_slug, tool_slug, action_class, arguments, summary, approved_arguments, result, error, reason, expires_at, reminded_at, decided_by, decided_at, created_at, updated_at
+`
+
+// Pending requests within two hours of expiry that have not been reminded.
+func (q *Queries) ClaimAppActionRequestReminders(ctx context.Context) ([]AppActionRequest, error) {
+ rows, err := q.db.Query(ctx, claimAppActionRequestReminders)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ items := []AppActionRequest{}
+ for rows.Next() {
+ var i AppActionRequest
+ if err := rows.Scan(
+ &i.ID,
+ &i.WorkspaceID,
+ &i.Kind,
+ &i.Status,
+ &i.TaskID,
+ &i.AgentID,
+ &i.IssueID,
+ &i.ChatSessionID,
+ &i.ApproverUserID,
+ &i.AccountScope,
+ &i.ToolkitSlug,
+ &i.ToolSlug,
+ &i.ActionClass,
+ &i.Arguments,
+ &i.Summary,
+ &i.ApprovedArguments,
+ &i.Result,
+ &i.Error,
+ &i.Reason,
+ &i.ExpiresAt,
+ &i.RemindedAt,
+ &i.DecidedBy,
+ &i.DecidedAt,
+ &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 countActiveAutopilotsForAgents = `-- name: CountActiveAutopilotsForAgents :one
+SELECT count(*) FROM autopilot
+WHERE workspace_id = $1
+ AND assignee_type = 'agent'
+ AND assignee_id = ANY($2::uuid[])
+ AND status = 'active'
+`
+
+type CountActiveAutopilotsForAgentsParams struct {
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ AgentIds []pgtype.UUID `json:"agent_ids"`
+}
+
+func (q *Queries) CountActiveAutopilotsForAgents(ctx context.Context, arg CountActiveAutopilotsForAgentsParams) (int64, error) {
+ row := q.db.QueryRow(ctx, countActiveAutopilotsForAgents, arg.WorkspaceID, arg.AgentIds)
+ var count int64
+ err := row.Scan(&count)
+ return count, err
+}
+
+const countActiveTasksForAgents = `-- name: CountActiveTasksForAgents :one
+SELECT count(*) FROM agent_task_queue
+WHERE agent_id = ANY($1::uuid[])
+ AND status IN ('queued', 'dispatched', 'running')
+`
+
+func (q *Queries) CountActiveTasksForAgents(ctx context.Context, agentIds []pgtype.UUID) (int64, error) {
+ row := q.db.QueryRow(ctx, countActiveTasksForAgents, agentIds)
+ var count int64
+ err := row.Scan(&count)
+ return count, err
+}
+
+const countPendingTeamAppActionRequests = `-- name: CountPendingTeamAppActionRequests :one
+SELECT count(*) FROM app_action_request
+WHERE workspace_id = $1 AND toolkit_slug = $2 AND account_scope = 'team' AND status = 'pending'
+`
+
+type CountPendingTeamAppActionRequestsParams struct {
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ ToolkitSlug string `json:"toolkit_slug"`
+}
+
+func (q *Queries) CountPendingTeamAppActionRequests(ctx context.Context, arg CountPendingTeamAppActionRequestsParams) (int64, error) {
+ row := q.db.QueryRow(ctx, countPendingTeamAppActionRequests, arg.WorkspaceID, arg.ToolkitSlug)
+ var count int64
+ err := row.Scan(&count)
+ return count, err
+}
+
+const countRecentAppAccountCalls = `-- name: CountRecentAppAccountCalls :one
+SELECT count(*) FROM app_tool_call
+WHERE workspace_id = $1 AND toolkit_slug = $2 AND account_scope = $3
+ AND account_owner_user_id IS NOT DISTINCT FROM $4::uuid
+ AND outcome IN ('ok', 'error', 'approved')
+ AND created_at > $5::timestamptz
+`
+
+type CountRecentAppAccountCallsParams struct {
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ ToolkitSlug string `json:"toolkit_slug"`
+ AccountScope string `json:"account_scope"`
+ Owner pgtype.UUID `json:"owner"`
+ Since pgtype.Timestamptz `json:"since"`
+}
+
+// Calls that reached the app through one account within the window; backs the
+// per-account rate limit. Blocked, pending and limited calls never ran.
+func (q *Queries) CountRecentAppAccountCalls(ctx context.Context, arg CountRecentAppAccountCallsParams) (int64, error) {
+ row := q.db.QueryRow(ctx, countRecentAppAccountCalls,
+ arg.WorkspaceID,
+ arg.ToolkitSlug,
+ arg.AccountScope,
+ arg.Owner,
+ arg.Since,
+ )
+ var count int64
+ err := row.Scan(&count)
+ return count, err
+}
+
+const createAppActionRequest = `-- name: CreateAppActionRequest :one
+INSERT INTO app_action_request (
+ workspace_id, kind, task_id, agent_id, issue_id, chat_session_id, approver_user_id,
+ account_scope, toolkit_slug, tool_slug, action_class, arguments, summary, expires_at
+) VALUES (
+ $1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14
+)
+RETURNING id, workspace_id, kind, status, task_id, agent_id, issue_id, chat_session_id, approver_user_id, account_scope, toolkit_slug, tool_slug, action_class, arguments, summary, approved_arguments, result, error, reason, expires_at, reminded_at, decided_by, decided_at, created_at, updated_at
+`
+
+type CreateAppActionRequestParams struct {
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ Kind string `json:"kind"`
+ TaskID pgtype.UUID `json:"task_id"`
+ AgentID pgtype.UUID `json:"agent_id"`
+ IssueID pgtype.UUID `json:"issue_id"`
+ ChatSessionID pgtype.UUID `json:"chat_session_id"`
+ ApproverUserID pgtype.UUID `json:"approver_user_id"`
+ AccountScope string `json:"account_scope"`
+ ToolkitSlug string `json:"toolkit_slug"`
+ ToolSlug string `json:"tool_slug"`
+ ActionClass string `json:"action_class"`
+ Arguments []byte `json:"arguments"`
+ Summary string `json:"summary"`
+ ExpiresAt pgtype.Timestamptz `json:"expires_at"`
+}
+
+func (q *Queries) CreateAppActionRequest(ctx context.Context, arg CreateAppActionRequestParams) (AppActionRequest, error) {
+ row := q.db.QueryRow(ctx, createAppActionRequest,
+ arg.WorkspaceID,
+ arg.Kind,
+ arg.TaskID,
+ arg.AgentID,
+ arg.IssueID,
+ arg.ChatSessionID,
+ arg.ApproverUserID,
+ arg.AccountScope,
+ arg.ToolkitSlug,
+ arg.ToolSlug,
+ arg.ActionClass,
+ arg.Arguments,
+ arg.Summary,
+ arg.ExpiresAt,
+ )
+ var i AppActionRequest
+ err := row.Scan(
+ &i.ID,
+ &i.WorkspaceID,
+ &i.Kind,
+ &i.Status,
+ &i.TaskID,
+ &i.AgentID,
+ &i.IssueID,
+ &i.ChatSessionID,
+ &i.ApproverUserID,
+ &i.AccountScope,
+ &i.ToolkitSlug,
+ &i.ToolSlug,
+ &i.ActionClass,
+ &i.Arguments,
+ &i.Summary,
+ &i.ApprovedArguments,
+ &i.Result,
+ &i.Error,
+ &i.Reason,
+ &i.ExpiresAt,
+ &i.RemindedAt,
+ &i.DecidedBy,
+ &i.DecidedAt,
+ &i.CreatedAt,
+ &i.UpdatedAt,
+ )
+ return i, err
+}
+
+const decideAppActionRequest = `-- name: DecideAppActionRequest :one
+UPDATE app_action_request
+SET status = $3,
+ approved_arguments = $5::jsonb,
+ reason = $6::text,
+ decided_by = $4,
+ decided_at = now(),
+ updated_at = now()
+WHERE id = $1 AND workspace_id = $2 AND status = 'pending' AND approver_user_id = $4
+RETURNING id, workspace_id, kind, status, task_id, agent_id, issue_id, chat_session_id, approver_user_id, account_scope, toolkit_slug, tool_slug, action_class, arguments, summary, approved_arguments, result, error, reason, expires_at, reminded_at, decided_by, decided_at, created_at, updated_at
+`
+
+type DecideAppActionRequestParams struct {
+ ID pgtype.UUID `json:"id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ Status string `json:"status"`
+ DecidedBy pgtype.UUID `json:"decided_by"`
+ ApprovedArguments []byte `json:"approved_arguments"`
+ Reason pgtype.Text `json:"reason"`
+}
+
+// Compare-and-set from pending: a second click, another device, or the expiry
+// sweep racing the decision finds no pending row and returns no rows.
+func (q *Queries) DecideAppActionRequest(ctx context.Context, arg DecideAppActionRequestParams) (AppActionRequest, error) {
+ row := q.db.QueryRow(ctx, decideAppActionRequest,
+ arg.ID,
+ arg.WorkspaceID,
+ arg.Status,
+ arg.DecidedBy,
+ arg.ApprovedArguments,
+ arg.Reason,
+ )
+ var i AppActionRequest
+ err := row.Scan(
+ &i.ID,
+ &i.WorkspaceID,
+ &i.Kind,
+ &i.Status,
+ &i.TaskID,
+ &i.AgentID,
+ &i.IssueID,
+ &i.ChatSessionID,
+ &i.ApproverUserID,
+ &i.AccountScope,
+ &i.ToolkitSlug,
+ &i.ToolSlug,
+ &i.ActionClass,
+ &i.Arguments,
+ &i.Summary,
+ &i.ApprovedArguments,
+ &i.Result,
+ &i.Error,
+ &i.Reason,
+ &i.ExpiresAt,
+ &i.RemindedAt,
+ &i.DecidedBy,
+ &i.DecidedAt,
+ &i.CreatedAt,
+ &i.UpdatedAt,
+ )
+ return i, err
+}
+
+const deleteAgentAppsExcept = `-- name: DeleteAgentAppsExcept :exec
+DELETE FROM agent_app
+WHERE agent_id = $1 AND NOT (toolkit_slug = ANY($2::text[]))
+`
+
+type DeleteAgentAppsExceptParams struct {
+ AgentID pgtype.UUID `json:"agent_id"`
+ Keep []string `json:"keep"`
+}
+
+func (q *Queries) DeleteAgentAppsExcept(ctx context.Context, arg DeleteAgentAppsExceptParams) error {
+ _, err := q.db.Exec(ctx, deleteAgentAppsExcept, arg.AgentID, arg.Keep)
+ return err
+}
+
+const deleteAppToolClassOverride = `-- name: DeleteAppToolClassOverride :exec
+DELETE FROM app_tool_class_override
+WHERE workspace_id = $1 AND toolkit_slug = $2 AND tool_slug = $3
+`
+
+type DeleteAppToolClassOverrideParams struct {
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ ToolkitSlug string `json:"toolkit_slug"`
+ ToolSlug string `json:"tool_slug"`
+}
+
+func (q *Queries) DeleteAppToolClassOverride(ctx context.Context, arg DeleteAppToolClassOverrideParams) error {
+ _, err := q.db.Exec(ctx, deleteAppToolClassOverride, arg.WorkspaceID, arg.ToolkitSlug, arg.ToolSlug)
+ return err
+}
+
+const expireDueAppActionRequests = `-- name: ExpireDueAppActionRequests :many
+UPDATE app_action_request
+SET status = 'expired', updated_at = now()
+WHERE id IN (
+ SELECT r.id FROM app_action_request r
+ WHERE r.status = 'pending' AND r.expires_at <= now()
+ ORDER BY r.expires_at
+ LIMIT 200
+ FOR UPDATE SKIP LOCKED
+)
+RETURNING id, workspace_id, kind, status, task_id, agent_id, issue_id, chat_session_id, approver_user_id, account_scope, toolkit_slug, tool_slug, action_class, arguments, summary, approved_arguments, result, error, reason, expires_at, reminded_at, decided_by, decided_at, created_at, updated_at
+`
+
+func (q *Queries) ExpireDueAppActionRequests(ctx context.Context) ([]AppActionRequest, error) {
+ rows, err := q.db.Query(ctx, expireDueAppActionRequests)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ items := []AppActionRequest{}
+ for rows.Next() {
+ var i AppActionRequest
+ if err := rows.Scan(
+ &i.ID,
+ &i.WorkspaceID,
+ &i.Kind,
+ &i.Status,
+ &i.TaskID,
+ &i.AgentID,
+ &i.IssueID,
+ &i.ChatSessionID,
+ &i.ApproverUserID,
+ &i.AccountScope,
+ &i.ToolkitSlug,
+ &i.ToolSlug,
+ &i.ActionClass,
+ &i.Arguments,
+ &i.Summary,
+ &i.ApprovedArguments,
+ &i.Result,
+ &i.Error,
+ &i.Reason,
+ &i.ExpiresAt,
+ &i.RemindedAt,
+ &i.DecidedBy,
+ &i.DecidedAt,
+ &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 findPendingAppActionRequest = `-- name: FindPendingAppActionRequest :one
+SELECT id, workspace_id, kind, status, task_id, agent_id, issue_id, chat_session_id, approver_user_id, account_scope, toolkit_slug, tool_slug, action_class, arguments, summary, approved_arguments, result, error, reason, expires_at, reminded_at, decided_by, decided_at, created_at, updated_at FROM app_action_request
+WHERE task_id = $1 AND kind = $2 AND toolkit_slug = $3 AND tool_slug = $4
+ AND arguments = $5::jsonb AND status = 'pending'
+ORDER BY created_at DESC
+LIMIT 1
+`
+
+type FindPendingAppActionRequestParams struct {
+ TaskID pgtype.UUID `json:"task_id"`
+ Kind string `json:"kind"`
+ ToolkitSlug string `json:"toolkit_slug"`
+ ToolSlug string `json:"tool_slug"`
+ Arguments []byte `json:"arguments"`
+}
+
+// The same run asking for the same call again (an agent retrying after a
+// "submitted" answer) reuses the open request instead of stacking another.
+func (q *Queries) FindPendingAppActionRequest(ctx context.Context, arg FindPendingAppActionRequestParams) (AppActionRequest, error) {
+ row := q.db.QueryRow(ctx, findPendingAppActionRequest,
+ arg.TaskID,
+ arg.Kind,
+ arg.ToolkitSlug,
+ arg.ToolSlug,
+ arg.Arguments,
+ )
+ var i AppActionRequest
+ err := row.Scan(
+ &i.ID,
+ &i.WorkspaceID,
+ &i.Kind,
+ &i.Status,
+ &i.TaskID,
+ &i.AgentID,
+ &i.IssueID,
+ &i.ChatSessionID,
+ &i.ApproverUserID,
+ &i.AccountScope,
+ &i.ToolkitSlug,
+ &i.ToolSlug,
+ &i.ActionClass,
+ &i.Arguments,
+ &i.Summary,
+ &i.ApprovedArguments,
+ &i.Result,
+ &i.Error,
+ &i.Reason,
+ &i.ExpiresAt,
+ &i.RemindedAt,
+ &i.DecidedBy,
+ &i.DecidedAt,
+ &i.CreatedAt,
+ &i.UpdatedAt,
+ )
+ return i, err
+}
+
+const getAppActionRequest = `-- name: GetAppActionRequest :one
+SELECT id, workspace_id, kind, status, task_id, agent_id, issue_id, chat_session_id, approver_user_id, account_scope, toolkit_slug, tool_slug, action_class, arguments, summary, approved_arguments, result, error, reason, expires_at, reminded_at, decided_by, decided_at, created_at, updated_at FROM app_action_request
+WHERE id = $1 AND workspace_id = $2
+`
+
+type GetAppActionRequestParams struct {
+ ID pgtype.UUID `json:"id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+}
+
+func (q *Queries) GetAppActionRequest(ctx context.Context, arg GetAppActionRequestParams) (AppActionRequest, error) {
+ row := q.db.QueryRow(ctx, getAppActionRequest, arg.ID, arg.WorkspaceID)
+ var i AppActionRequest
+ err := row.Scan(
+ &i.ID,
+ &i.WorkspaceID,
+ &i.Kind,
+ &i.Status,
+ &i.TaskID,
+ &i.AgentID,
+ &i.IssueID,
+ &i.ChatSessionID,
+ &i.ApproverUserID,
+ &i.AccountScope,
+ &i.ToolkitSlug,
+ &i.ToolSlug,
+ &i.ActionClass,
+ &i.Arguments,
+ &i.Summary,
+ &i.ApprovedArguments,
+ &i.Result,
+ &i.Error,
+ &i.Reason,
+ &i.ExpiresAt,
+ &i.RemindedAt,
+ &i.DecidedBy,
+ &i.DecidedAt,
+ &i.CreatedAt,
+ &i.UpdatedAt,
+ )
+ return i, err
+}
+
+const getAppToolClassOverride = `-- name: GetAppToolClassOverride :one
+SELECT action_class FROM app_tool_class_override
+WHERE workspace_id = $1 AND toolkit_slug = $2 AND tool_slug = $3
+`
+
+type GetAppToolClassOverrideParams struct {
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ ToolkitSlug string `json:"toolkit_slug"`
+ ToolSlug string `json:"tool_slug"`
+}
+
+func (q *Queries) GetAppToolClassOverride(ctx context.Context, arg GetAppToolClassOverrideParams) (string, error) {
+ row := q.db.QueryRow(ctx, getAppToolClassOverride, arg.WorkspaceID, arg.ToolkitSlug, arg.ToolSlug)
+ var action_class string
+ err := row.Scan(&action_class)
+ return action_class, err
+}
+
+const getWorkspaceAppSetting = `-- name: GetWorkspaceAppSetting :one
+SELECT workspace_id, catalog_mode, allowed_toolkits, updated_by, updated_at FROM workspace_app_setting WHERE workspace_id = $1
+`
+
+func (q *Queries) GetWorkspaceAppSetting(ctx context.Context, workspaceID pgtype.UUID) (WorkspaceAppSetting, error) {
+ row := q.db.QueryRow(ctx, getWorkspaceAppSetting, workspaceID)
+ var i WorkspaceAppSetting
+ err := row.Scan(
+ &i.WorkspaceID,
+ &i.CatalogMode,
+ &i.AllowedToolkits,
+ &i.UpdatedBy,
+ &i.UpdatedAt,
+ )
+ return i, err
+}
+
+const getWorkspaceComposioConnection = `-- name: GetWorkspaceComposioConnection :one
+SELECT id, workspace_id, toolkit_slug, auth_config_id, connected_account_id, composio_user_id, connected_by, status, connected_at, last_used_at, created_at, updated_at FROM workspace_composio_connection
+WHERE id = $1 AND workspace_id = $2
+`
+
+type GetWorkspaceComposioConnectionParams struct {
+ ID pgtype.UUID `json:"id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+}
+
+func (q *Queries) GetWorkspaceComposioConnection(ctx context.Context, arg GetWorkspaceComposioConnectionParams) (WorkspaceComposioConnection, error) {
+ row := q.db.QueryRow(ctx, getWorkspaceComposioConnection, arg.ID, arg.WorkspaceID)
+ var i WorkspaceComposioConnection
+ err := row.Scan(
+ &i.ID,
+ &i.WorkspaceID,
+ &i.ToolkitSlug,
+ &i.AuthConfigID,
+ &i.ConnectedAccountID,
+ &i.ComposioUserID,
+ &i.ConnectedBy,
+ &i.Status,
+ &i.ConnectedAt,
+ &i.LastUsedAt,
+ &i.CreatedAt,
+ &i.UpdatedAt,
+ )
+ return i, err
+}
+
+const hasBlockedAppToolCall = `-- name: HasBlockedAppToolCall :one
+SELECT EXISTS (
+ SELECT 1 FROM app_tool_call
+ WHERE workspace_id = $1 AND toolkit_slug = $2 AND task_id = $3
+ AND tool_slug = $4 AND outcome = 'blocked'
+ AND created_at > $5::timestamptz
+)
+`
+
+type HasBlockedAppToolCallParams struct {
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ ToolkitSlug string `json:"toolkit_slug"`
+ TaskID pgtype.UUID `json:"task_id"`
+ ToolSlug string `json:"tool_slug"`
+ Since pgtype.Timestamptz `json:"since"`
+}
+
+// Whether a run already hit a block on this tool, so the person is told once.
+func (q *Queries) HasBlockedAppToolCall(ctx context.Context, arg HasBlockedAppToolCallParams) (bool, error) {
+ row := q.db.QueryRow(ctx, hasBlockedAppToolCall,
+ arg.WorkspaceID,
+ arg.ToolkitSlug,
+ arg.TaskID,
+ arg.ToolSlug,
+ arg.Since,
+ )
+ var exists bool
+ err := row.Scan(&exists)
+ return exists, err
+}
+
+const insertAppToolCall = `-- name: InsertAppToolCall :exec
+INSERT INTO app_tool_call (
+ workspace_id, task_id, agent_id, issue_id, chat_session_id, triggered_by,
+ account_scope, account_owner_user_id, toolkit_slug, tool_slug, action_class,
+ outcome, request_id, error
+) VALUES (
+ $1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14
+)
+`
+
+type InsertAppToolCallParams struct {
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ TaskID pgtype.UUID `json:"task_id"`
+ AgentID pgtype.UUID `json:"agent_id"`
+ IssueID pgtype.UUID `json:"issue_id"`
+ ChatSessionID pgtype.UUID `json:"chat_session_id"`
+ TriggeredBy pgtype.UUID `json:"triggered_by"`
+ AccountScope string `json:"account_scope"`
+ AccountOwnerUserID pgtype.UUID `json:"account_owner_user_id"`
+ ToolkitSlug string `json:"toolkit_slug"`
+ ToolSlug string `json:"tool_slug"`
+ ActionClass string `json:"action_class"`
+ Outcome string `json:"outcome"`
+ RequestID pgtype.UUID `json:"request_id"`
+ Error pgtype.Text `json:"error"`
+}
+
+func (q *Queries) InsertAppToolCall(ctx context.Context, arg InsertAppToolCallParams) error {
+ _, err := q.db.Exec(ctx, insertAppToolCall,
+ arg.WorkspaceID,
+ arg.TaskID,
+ arg.AgentID,
+ arg.IssueID,
+ arg.ChatSessionID,
+ arg.TriggeredBy,
+ arg.AccountScope,
+ arg.AccountOwnerUserID,
+ arg.ToolkitSlug,
+ arg.ToolSlug,
+ arg.ActionClass,
+ arg.Outcome,
+ arg.RequestID,
+ arg.Error,
+ )
+ return err
+}
+
+const listAgentApps = `-- name: ListAgentApps :many
+SELECT id, workspace_id, agent_id, toolkit_slug, account_scope, level, created_by, created_at, updated_at FROM agent_app
+WHERE agent_id = $1
+ORDER BY toolkit_slug
+`
+
+func (q *Queries) ListAgentApps(ctx context.Context, agentID pgtype.UUID) ([]AgentApp, error) {
+ rows, err := q.db.Query(ctx, listAgentApps, agentID)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ items := []AgentApp{}
+ for rows.Next() {
+ var i AgentApp
+ if err := rows.Scan(
+ &i.ID,
+ &i.WorkspaceID,
+ &i.AgentID,
+ &i.ToolkitSlug,
+ &i.AccountScope,
+ &i.Level,
+ &i.CreatedBy,
+ &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 listAgentAppsInWorkspace = `-- name: ListAgentAppsInWorkspace :many
+SELECT id, workspace_id, agent_id, toolkit_slug, account_scope, level, created_by, created_at, updated_at FROM agent_app
+WHERE workspace_id = $1
+ORDER BY toolkit_slug, agent_id
+`
+
+func (q *Queries) ListAgentAppsInWorkspace(ctx context.Context, workspaceID pgtype.UUID) ([]AgentApp, error) {
+ rows, err := q.db.Query(ctx, listAgentAppsInWorkspace, workspaceID)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ items := []AgentApp{}
+ for rows.Next() {
+ var i AgentApp
+ if err := rows.Scan(
+ &i.ID,
+ &i.WorkspaceID,
+ &i.AgentID,
+ &i.ToolkitSlug,
+ &i.AccountScope,
+ &i.Level,
+ &i.CreatedBy,
+ &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 listAppActionRules = `-- name: ListAppActionRules :many
+SELECT id, workspace_id, owner_user_id, toolkit_slug, action_class, policy, updated_by, updated_at FROM app_action_rule
+WHERE workspace_id = $1
+ AND toolkit_slug = $2
+ AND owner_user_id IS NOT DISTINCT FROM $3::uuid
+`
+
+type ListAppActionRulesParams struct {
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ ToolkitSlug string `json:"toolkit_slug"`
+ OwnerUserID pgtype.UUID `json:"owner_user_id"`
+}
+
+// Rules of one account: owner_user_id NULL is the team account.
+func (q *Queries) ListAppActionRules(ctx context.Context, arg ListAppActionRulesParams) ([]AppActionRule, error) {
+ rows, err := q.db.Query(ctx, listAppActionRules, arg.WorkspaceID, arg.ToolkitSlug, arg.OwnerUserID)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ items := []AppActionRule{}
+ for rows.Next() {
+ var i AppActionRule
+ if err := rows.Scan(
+ &i.ID,
+ &i.WorkspaceID,
+ &i.OwnerUserID,
+ &i.ToolkitSlug,
+ &i.ActionClass,
+ &i.Policy,
+ &i.UpdatedBy,
+ &i.UpdatedAt,
+ ); err != nil {
+ return nil, err
+ }
+ items = append(items, i)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+ return items, nil
+}
+
+const listAppActionRulesForRun = `-- name: ListAppActionRulesForRun :many
+SELECT id, workspace_id, owner_user_id, toolkit_slug, action_class, policy, updated_by, updated_at FROM app_action_rule
+WHERE workspace_id = $1
+ AND toolkit_slug = ANY($2::text[])
+ AND (owner_user_id IS NULL OR owner_user_id = $3::uuid)
+`
+
+type ListAppActionRulesForRunParams struct {
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ ToolkitSlugs []string `json:"toolkit_slugs"`
+ OwnerUserID pgtype.UUID `json:"owner_user_id"`
+}
+
+// Every rule that can apply to a run: the team rules and the triggering
+// member's personal rules for the run's apps.
+func (q *Queries) ListAppActionRulesForRun(ctx context.Context, arg ListAppActionRulesForRunParams) ([]AppActionRule, error) {
+ rows, err := q.db.Query(ctx, listAppActionRulesForRun, arg.WorkspaceID, arg.ToolkitSlugs, arg.OwnerUserID)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ items := []AppActionRule{}
+ for rows.Next() {
+ var i AppActionRule
+ if err := rows.Scan(
+ &i.ID,
+ &i.WorkspaceID,
+ &i.OwnerUserID,
+ &i.ToolkitSlug,
+ &i.ActionClass,
+ &i.Policy,
+ &i.UpdatedBy,
+ &i.UpdatedAt,
+ ); err != nil {
+ return nil, err
+ }
+ items = append(items, i)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+ return items, nil
+}
+
+const listAppToolClassOverrides = `-- name: ListAppToolClassOverrides :many
+SELECT workspace_id, toolkit_slug, tool_slug, action_class, updated_by, updated_at FROM app_tool_class_override
+WHERE workspace_id = $1 AND toolkit_slug = $2
+`
+
+type ListAppToolClassOverridesParams struct {
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ ToolkitSlug string `json:"toolkit_slug"`
+}
+
+func (q *Queries) ListAppToolClassOverrides(ctx context.Context, arg ListAppToolClassOverridesParams) ([]AppToolClassOverride, error) {
+ rows, err := q.db.Query(ctx, listAppToolClassOverrides, arg.WorkspaceID, arg.ToolkitSlug)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ items := []AppToolClassOverride{}
+ for rows.Next() {
+ var i AppToolClassOverride
+ if err := rows.Scan(
+ &i.WorkspaceID,
+ &i.ToolkitSlug,
+ &i.ToolSlug,
+ &i.ActionClass,
+ &i.UpdatedBy,
+ &i.UpdatedAt,
+ ); err != nil {
+ return nil, err
+ }
+ items = append(items, i)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+ return items, nil
+}
+
+const listDecidedAppActionRequestsForChatSession = `-- name: ListDecidedAppActionRequestsForChatSession :many
+SELECT id, workspace_id, kind, status, task_id, agent_id, issue_id, chat_session_id, approver_user_id, account_scope, toolkit_slug, tool_slug, action_class, arguments, summary, approved_arguments, result, error, reason, expires_at, reminded_at, decided_by, decided_at, created_at, updated_at FROM app_action_request
+WHERE workspace_id = $1 AND chat_session_id = $2 AND status <> 'pending'
+ AND ($3::timestamptz IS NULL OR created_at < $3::timestamptz)
+ORDER BY created_at DESC
+LIMIT $4
+`
+
+type ListDecidedAppActionRequestsForChatSessionParams struct {
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ ChatSessionID pgtype.UUID `json:"chat_session_id"`
+ Before pgtype.Timestamptz `json:"before"`
+ PageSize int32 `json:"page_size"`
+}
+
+func (q *Queries) ListDecidedAppActionRequestsForChatSession(ctx context.Context, arg ListDecidedAppActionRequestsForChatSessionParams) ([]AppActionRequest, error) {
+ rows, err := q.db.Query(ctx, listDecidedAppActionRequestsForChatSession,
+ arg.WorkspaceID,
+ arg.ChatSessionID,
+ arg.Before,
+ arg.PageSize,
+ )
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ items := []AppActionRequest{}
+ for rows.Next() {
+ var i AppActionRequest
+ if err := rows.Scan(
+ &i.ID,
+ &i.WorkspaceID,
+ &i.Kind,
+ &i.Status,
+ &i.TaskID,
+ &i.AgentID,
+ &i.IssueID,
+ &i.ChatSessionID,
+ &i.ApproverUserID,
+ &i.AccountScope,
+ &i.ToolkitSlug,
+ &i.ToolSlug,
+ &i.ActionClass,
+ &i.Arguments,
+ &i.Summary,
+ &i.ApprovedArguments,
+ &i.Result,
+ &i.Error,
+ &i.Reason,
+ &i.ExpiresAt,
+ &i.RemindedAt,
+ &i.DecidedBy,
+ &i.DecidedAt,
+ &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 listDecidedAppActionRequestsForIssue = `-- name: ListDecidedAppActionRequestsForIssue :many
+SELECT id, workspace_id, kind, status, task_id, agent_id, issue_id, chat_session_id, approver_user_id, account_scope, toolkit_slug, tool_slug, action_class, arguments, summary, approved_arguments, result, error, reason, expires_at, reminded_at, decided_by, decided_at, created_at, updated_at FROM app_action_request
+WHERE workspace_id = $1 AND issue_id = $2 AND status <> 'pending'
+ AND ($3::timestamptz IS NULL OR created_at < $3::timestamptz)
+ORDER BY created_at DESC
+LIMIT $4
+`
+
+type ListDecidedAppActionRequestsForIssueParams struct {
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ IssueID pgtype.UUID `json:"issue_id"`
+ Before pgtype.Timestamptz `json:"before"`
+ PageSize int32 `json:"page_size"`
+}
+
+// One page of an issue's decided requests, newest first, before a cursor.
+func (q *Queries) ListDecidedAppActionRequestsForIssue(ctx context.Context, arg ListDecidedAppActionRequestsForIssueParams) ([]AppActionRequest, error) {
+ rows, err := q.db.Query(ctx, listDecidedAppActionRequestsForIssue,
+ arg.WorkspaceID,
+ arg.IssueID,
+ arg.Before,
+ arg.PageSize,
+ )
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ items := []AppActionRequest{}
+ for rows.Next() {
+ var i AppActionRequest
+ if err := rows.Scan(
+ &i.ID,
+ &i.WorkspaceID,
+ &i.Kind,
+ &i.Status,
+ &i.TaskID,
+ &i.AgentID,
+ &i.IssueID,
+ &i.ChatSessionID,
+ &i.ApproverUserID,
+ &i.AccountScope,
+ &i.ToolkitSlug,
+ &i.ToolSlug,
+ &i.ActionClass,
+ &i.Arguments,
+ &i.Summary,
+ &i.ApprovedArguments,
+ &i.Result,
+ &i.Error,
+ &i.Reason,
+ &i.ExpiresAt,
+ &i.RemindedAt,
+ &i.DecidedBy,
+ &i.DecidedAt,
+ &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 listIssueAppToolCalls = `-- name: ListIssueAppToolCalls :many
+SELECT id, workspace_id, task_id, agent_id, issue_id, chat_session_id, triggered_by, account_scope, account_owner_user_id, toolkit_slug, tool_slug, action_class, outcome, request_id, error, created_at FROM app_tool_call
+WHERE workspace_id = $1 AND issue_id = $2
+ORDER BY created_at DESC
+LIMIT 500
+`
+
+type ListIssueAppToolCallsParams struct {
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ IssueID pgtype.UUID `json:"issue_id"`
+}
+
+// The latest calls the runs of one issue made, newest first. Arguments are
+// never stored.
+func (q *Queries) ListIssueAppToolCalls(ctx context.Context, arg ListIssueAppToolCallsParams) ([]AppToolCall, error) {
+ rows, err := q.db.Query(ctx, listIssueAppToolCalls, arg.WorkspaceID, arg.IssueID)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ items := []AppToolCall{}
+ for rows.Next() {
+ var i AppToolCall
+ if err := rows.Scan(
+ &i.ID,
+ &i.WorkspaceID,
+ &i.TaskID,
+ &i.AgentID,
+ &i.IssueID,
+ &i.ChatSessionID,
+ &i.TriggeredBy,
+ &i.AccountScope,
+ &i.AccountOwnerUserID,
+ &i.ToolkitSlug,
+ &i.ToolSlug,
+ &i.ActionClass,
+ &i.Outcome,
+ &i.RequestID,
+ &i.Error,
+ &i.CreatedAt,
+ ); err != nil {
+ return nil, err
+ }
+ items = append(items, i)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+ return items, nil
+}
+
+const listPendingAppActionRequestsForApprover = `-- name: ListPendingAppActionRequestsForApprover :many
+SELECT id, workspace_id, kind, status, task_id, agent_id, issue_id, chat_session_id, approver_user_id, account_scope, toolkit_slug, tool_slug, action_class, arguments, summary, approved_arguments, result, error, reason, expires_at, reminded_at, decided_by, decided_at, created_at, updated_at FROM app_action_request
+WHERE workspace_id = $1 AND approver_user_id = $2 AND status = 'pending'
+ORDER BY created_at
+LIMIT 200
+`
+
+type ListPendingAppActionRequestsForApproverParams struct {
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ ApproverUserID pgtype.UUID `json:"approver_user_id"`
+}
+
+func (q *Queries) ListPendingAppActionRequestsForApprover(ctx context.Context, arg ListPendingAppActionRequestsForApproverParams) ([]AppActionRequest, error) {
+ rows, err := q.db.Query(ctx, listPendingAppActionRequestsForApprover, arg.WorkspaceID, arg.ApproverUserID)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ items := []AppActionRequest{}
+ for rows.Next() {
+ var i AppActionRequest
+ if err := rows.Scan(
+ &i.ID,
+ &i.WorkspaceID,
+ &i.Kind,
+ &i.Status,
+ &i.TaskID,
+ &i.AgentID,
+ &i.IssueID,
+ &i.ChatSessionID,
+ &i.ApproverUserID,
+ &i.AccountScope,
+ &i.ToolkitSlug,
+ &i.ToolSlug,
+ &i.ActionClass,
+ &i.Arguments,
+ &i.Summary,
+ &i.ApprovedArguments,
+ &i.Result,
+ &i.Error,
+ &i.Reason,
+ &i.ExpiresAt,
+ &i.RemindedAt,
+ &i.DecidedBy,
+ &i.DecidedAt,
+ &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 listPendingAppActionRequestsForChatSession = `-- name: ListPendingAppActionRequestsForChatSession :many
+SELECT id, workspace_id, kind, status, task_id, agent_id, issue_id, chat_session_id, approver_user_id, account_scope, toolkit_slug, tool_slug, action_class, arguments, summary, approved_arguments, result, error, reason, expires_at, reminded_at, decided_by, decided_at, created_at, updated_at FROM app_action_request
+WHERE workspace_id = $1 AND chat_session_id = $2 AND status = 'pending'
+ORDER BY created_at
+LIMIT 500
+`
+
+type ListPendingAppActionRequestsForChatSessionParams struct {
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ ChatSessionID pgtype.UUID `json:"chat_session_id"`
+}
+
+func (q *Queries) ListPendingAppActionRequestsForChatSession(ctx context.Context, arg ListPendingAppActionRequestsForChatSessionParams) ([]AppActionRequest, error) {
+ rows, err := q.db.Query(ctx, listPendingAppActionRequestsForChatSession, arg.WorkspaceID, arg.ChatSessionID)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ items := []AppActionRequest{}
+ for rows.Next() {
+ var i AppActionRequest
+ if err := rows.Scan(
+ &i.ID,
+ &i.WorkspaceID,
+ &i.Kind,
+ &i.Status,
+ &i.TaskID,
+ &i.AgentID,
+ &i.IssueID,
+ &i.ChatSessionID,
+ &i.ApproverUserID,
+ &i.AccountScope,
+ &i.ToolkitSlug,
+ &i.ToolSlug,
+ &i.ActionClass,
+ &i.Arguments,
+ &i.Summary,
+ &i.ApprovedArguments,
+ &i.Result,
+ &i.Error,
+ &i.Reason,
+ &i.ExpiresAt,
+ &i.RemindedAt,
+ &i.DecidedBy,
+ &i.DecidedAt,
+ &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 listPendingAppActionRequestsForIssue = `-- name: ListPendingAppActionRequestsForIssue :many
+SELECT id, workspace_id, kind, status, task_id, agent_id, issue_id, chat_session_id, approver_user_id, account_scope, toolkit_slug, tool_slug, action_class, arguments, summary, approved_arguments, result, error, reason, expires_at, reminded_at, decided_by, decided_at, created_at, updated_at FROM app_action_request
+WHERE workspace_id = $1 AND issue_id = $2 AND status = 'pending'
+ORDER BY created_at
+LIMIT 500
+`
+
+type ListPendingAppActionRequestsForIssueParams struct {
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ IssueID pgtype.UUID `json:"issue_id"`
+}
+
+// Every request of an issue still waiting for a decision. Expiry and the
+// per-minute call budget keep this short; the cap only bounds a runaway.
+func (q *Queries) ListPendingAppActionRequestsForIssue(ctx context.Context, arg ListPendingAppActionRequestsForIssueParams) ([]AppActionRequest, error) {
+ rows, err := q.db.Query(ctx, listPendingAppActionRequestsForIssue, arg.WorkspaceID, arg.IssueID)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ items := []AppActionRequest{}
+ for rows.Next() {
+ var i AppActionRequest
+ if err := rows.Scan(
+ &i.ID,
+ &i.WorkspaceID,
+ &i.Kind,
+ &i.Status,
+ &i.TaskID,
+ &i.AgentID,
+ &i.IssueID,
+ &i.ChatSessionID,
+ &i.ApproverUserID,
+ &i.AccountScope,
+ &i.ToolkitSlug,
+ &i.ToolSlug,
+ &i.ActionClass,
+ &i.Arguments,
+ &i.Summary,
+ &i.ApprovedArguments,
+ &i.Result,
+ &i.Error,
+ &i.Reason,
+ &i.ExpiresAt,
+ &i.RemindedAt,
+ &i.DecidedBy,
+ &i.DecidedAt,
+ &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 listPendingConnectRequestsForUser = `-- name: ListPendingConnectRequestsForUser :many
+SELECT id, workspace_id, kind, status, task_id, agent_id, issue_id, chat_session_id, approver_user_id, account_scope, toolkit_slug, tool_slug, action_class, arguments, summary, approved_arguments, result, error, reason, expires_at, reminded_at, decided_by, decided_at, created_at, updated_at FROM app_action_request
+WHERE approver_user_id = $1 AND toolkit_slug = $2 AND kind = 'connect'
+ AND status = 'pending' AND account_scope = 'personal'
+`
+
+type ListPendingConnectRequestsForUserParams struct {
+ ApproverUserID pgtype.UUID `json:"approver_user_id"`
+ ToolkitSlug string `json:"toolkit_slug"`
+}
+
+// Connection requests a member is asked to answer for one app; resolved when
+// they finish connecting it.
+func (q *Queries) ListPendingConnectRequestsForUser(ctx context.Context, arg ListPendingConnectRequestsForUserParams) ([]AppActionRequest, error) {
+ rows, err := q.db.Query(ctx, listPendingConnectRequestsForUser, arg.ApproverUserID, arg.ToolkitSlug)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ items := []AppActionRequest{}
+ for rows.Next() {
+ var i AppActionRequest
+ if err := rows.Scan(
+ &i.ID,
+ &i.WorkspaceID,
+ &i.Kind,
+ &i.Status,
+ &i.TaskID,
+ &i.AgentID,
+ &i.IssueID,
+ &i.ChatSessionID,
+ &i.ApproverUserID,
+ &i.AccountScope,
+ &i.ToolkitSlug,
+ &i.ToolSlug,
+ &i.ActionClass,
+ &i.Arguments,
+ &i.Summary,
+ &i.ApprovedArguments,
+ &i.Result,
+ &i.Error,
+ &i.Reason,
+ &i.ExpiresAt,
+ &i.RemindedAt,
+ &i.DecidedBy,
+ &i.DecidedAt,
+ &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 listPersonalAppToolCalls = `-- name: ListPersonalAppToolCalls :many
+SELECT id, workspace_id, task_id, agent_id, issue_id, chat_session_id, triggered_by, account_scope, account_owner_user_id, toolkit_slug, tool_slug, action_class, outcome, request_id, error, created_at FROM app_tool_call
+WHERE workspace_id = $1 AND toolkit_slug = $2 AND account_scope = 'personal'
+ AND account_owner_user_id = $3
+ORDER BY created_at DESC
+LIMIT $4
+`
+
+type ListPersonalAppToolCallsParams struct {
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ ToolkitSlug string `json:"toolkit_slug"`
+ AccountOwnerUserID pgtype.UUID `json:"account_owner_user_id"`
+ Limit int32 `json:"limit"`
+}
+
+// A member's own account activity. Only the owner reads this.
+func (q *Queries) ListPersonalAppToolCalls(ctx context.Context, arg ListPersonalAppToolCallsParams) ([]AppToolCall, error) {
+ rows, err := q.db.Query(ctx, listPersonalAppToolCalls,
+ arg.WorkspaceID,
+ arg.ToolkitSlug,
+ arg.AccountOwnerUserID,
+ arg.Limit,
+ )
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ items := []AppToolCall{}
+ for rows.Next() {
+ var i AppToolCall
+ if err := rows.Scan(
+ &i.ID,
+ &i.WorkspaceID,
+ &i.TaskID,
+ &i.AgentID,
+ &i.IssueID,
+ &i.ChatSessionID,
+ &i.TriggeredBy,
+ &i.AccountScope,
+ &i.AccountOwnerUserID,
+ &i.ToolkitSlug,
+ &i.ToolSlug,
+ &i.ActionClass,
+ &i.Outcome,
+ &i.RequestID,
+ &i.Error,
+ &i.CreatedAt,
+ ); err != nil {
+ return nil, err
+ }
+ items = append(items, i)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+ return items, nil
+}
+
+const listTeamAppToolCalls = `-- name: ListTeamAppToolCalls :many
+SELECT id, workspace_id, task_id, agent_id, issue_id, chat_session_id, triggered_by, account_scope, account_owner_user_id, toolkit_slug, tool_slug, action_class, outcome, request_id, error, created_at FROM app_tool_call
+WHERE workspace_id = $1 AND toolkit_slug = $2 AND account_scope = 'team'
+ORDER BY created_at DESC
+LIMIT $3
+`
+
+type ListTeamAppToolCallsParams struct {
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ ToolkitSlug string `json:"toolkit_slug"`
+ Limit int32 `json:"limit"`
+}
+
+func (q *Queries) ListTeamAppToolCalls(ctx context.Context, arg ListTeamAppToolCallsParams) ([]AppToolCall, error) {
+ rows, err := q.db.Query(ctx, listTeamAppToolCalls, arg.WorkspaceID, arg.ToolkitSlug, arg.Limit)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ items := []AppToolCall{}
+ for rows.Next() {
+ var i AppToolCall
+ if err := rows.Scan(
+ &i.ID,
+ &i.WorkspaceID,
+ &i.TaskID,
+ &i.AgentID,
+ &i.IssueID,
+ &i.ChatSessionID,
+ &i.TriggeredBy,
+ &i.AccountScope,
+ &i.AccountOwnerUserID,
+ &i.ToolkitSlug,
+ &i.ToolSlug,
+ &i.ActionClass,
+ &i.Outcome,
+ &i.RequestID,
+ &i.Error,
+ &i.CreatedAt,
+ ); err != nil {
+ return nil, err
+ }
+ items = append(items, i)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+ return items, nil
+}
+
+const listUserComposioConnectionsAnyStatus = `-- name: ListUserComposioConnectionsAnyStatus :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 <> 'revoked'
+ORDER BY connected_at DESC
+`
+
+// A member's personal accounts for the app list: active and expired.
+func (q *Queries) ListUserComposioConnectionsAnyStatus(ctx context.Context, userID pgtype.UUID) ([]UserComposioConnection, error) {
+ rows, err := q.db.Query(ctx, listUserComposioConnectionsAnyStatus, 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 listWorkspaceComposioConnections = `-- name: ListWorkspaceComposioConnections :many
+SELECT id, workspace_id, toolkit_slug, auth_config_id, connected_account_id, composio_user_id, connected_by, status, connected_at, last_used_at, created_at, updated_at FROM workspace_composio_connection
+WHERE workspace_id = $1 AND status <> 'revoked'
+ORDER BY connected_at DESC
+`
+
+// Active and expired team accounts, newest first. Revoked rows are history.
+func (q *Queries) ListWorkspaceComposioConnections(ctx context.Context, workspaceID pgtype.UUID) ([]WorkspaceComposioConnection, error) {
+ rows, err := q.db.Query(ctx, listWorkspaceComposioConnections, workspaceID)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ items := []WorkspaceComposioConnection{}
+ for rows.Next() {
+ var i WorkspaceComposioConnection
+ if err := rows.Scan(
+ &i.ID,
+ &i.WorkspaceID,
+ &i.ToolkitSlug,
+ &i.AuthConfigID,
+ &i.ConnectedAccountID,
+ &i.ComposioUserID,
+ &i.ConnectedBy,
+ &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 revokeOtherWorkspaceComposioConnections = `-- name: RevokeOtherWorkspaceComposioConnections :many
+UPDATE workspace_composio_connection
+SET status = 'revoked', updated_at = now()
+WHERE workspace_id = $1 AND toolkit_slug = $2 AND id <> $3 AND status <> 'revoked'
+RETURNING id, workspace_id, toolkit_slug, auth_config_id, connected_account_id, composio_user_id, connected_by, status, connected_at, last_used_at, created_at, updated_at
+`
+
+type RevokeOtherWorkspaceComposioConnectionsParams struct {
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ ToolkitSlug string `json:"toolkit_slug"`
+ ID pgtype.UUID `json:"id"`
+}
+
+// A workspace holds one team account per app: connecting again replaces the
+// previous account. Returns the replaced rows so their upstream grant can be
+// revoked.
+func (q *Queries) RevokeOtherWorkspaceComposioConnections(ctx context.Context, arg RevokeOtherWorkspaceComposioConnectionsParams) ([]WorkspaceComposioConnection, error) {
+ rows, err := q.db.Query(ctx, revokeOtherWorkspaceComposioConnections, arg.WorkspaceID, arg.ToolkitSlug, arg.ID)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ items := []WorkspaceComposioConnection{}
+ for rows.Next() {
+ var i WorkspaceComposioConnection
+ if err := rows.Scan(
+ &i.ID,
+ &i.WorkspaceID,
+ &i.ToolkitSlug,
+ &i.AuthConfigID,
+ &i.ConnectedAccountID,
+ &i.ComposioUserID,
+ &i.ConnectedBy,
+ &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 setAgentComposioToolkitAllowlist = `-- name: SetAgentComposioToolkitAllowlist :exec
+UPDATE agent SET composio_toolkit_allowlist = $2::text[], updated_at = now()
+WHERE id = $1
+`
+
+type SetAgentComposioToolkitAllowlistParams struct {
+ ID pgtype.UUID `json:"id"`
+ Slugs []string `json:"slugs"`
+}
+
+// Keeps the legacy allowlist column in step with agent_app for older clients.
+func (q *Queries) SetAgentComposioToolkitAllowlist(ctx context.Context, arg SetAgentComposioToolkitAllowlistParams) error {
+ _, err := q.db.Exec(ctx, setAgentComposioToolkitAllowlist, arg.ID, arg.Slugs)
+ return err
+}
+
+const setAppActionRequestOutcome = `-- name: SetAppActionRequestOutcome :one
+UPDATE app_action_request
+SET status = $3, result = $4::jsonb, error = $5::text, updated_at = now()
+WHERE id = $1 AND workspace_id = $2 AND status = 'approved'
+RETURNING id, workspace_id, kind, status, task_id, agent_id, issue_id, chat_session_id, approver_user_id, account_scope, toolkit_slug, tool_slug, action_class, arguments, summary, approved_arguments, result, error, reason, expires_at, reminded_at, decided_by, decided_at, created_at, updated_at
+`
+
+type SetAppActionRequestOutcomeParams struct {
+ ID pgtype.UUID `json:"id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ Status string `json:"status"`
+ Result []byte `json:"result"`
+ Error pgtype.Text `json:"error"`
+}
+
+// Records what executing an approved request produced. Only moves an approved
+// request; status becomes 'failed' when execution failed.
+func (q *Queries) SetAppActionRequestOutcome(ctx context.Context, arg SetAppActionRequestOutcomeParams) (AppActionRequest, error) {
+ row := q.db.QueryRow(ctx, setAppActionRequestOutcome,
+ arg.ID,
+ arg.WorkspaceID,
+ arg.Status,
+ arg.Result,
+ arg.Error,
+ )
+ var i AppActionRequest
+ err := row.Scan(
+ &i.ID,
+ &i.WorkspaceID,
+ &i.Kind,
+ &i.Status,
+ &i.TaskID,
+ &i.AgentID,
+ &i.IssueID,
+ &i.ChatSessionID,
+ &i.ApproverUserID,
+ &i.AccountScope,
+ &i.ToolkitSlug,
+ &i.ToolSlug,
+ &i.ActionClass,
+ &i.Arguments,
+ &i.Summary,
+ &i.ApprovedArguments,
+ &i.Result,
+ &i.Error,
+ &i.Reason,
+ &i.ExpiresAt,
+ &i.RemindedAt,
+ &i.DecidedBy,
+ &i.DecidedAt,
+ &i.CreatedAt,
+ &i.UpdatedAt,
+ )
+ return i, err
+}
+
+const setComposioConnectionStatusByAccount = `-- name: SetComposioConnectionStatusByAccount :exec
+WITH personal AS (
+ UPDATE user_composio_connection
+ SET status = $1::text, updated_at = now()
+ WHERE connected_account_id = $2::text AND status <> 'revoked'
+)
+UPDATE workspace_composio_connection
+SET status = $1::text, updated_at = now()
+WHERE connected_account_id = $2::text AND status <> 'revoked'
+`
+
+type SetComposioConnectionStatusByAccountParams struct {
+ Status string `json:"status"`
+ ConnectedAccountID string `json:"connected_account_id"`
+}
+
+// Webhook path: Composio names only the connected account. Applies to either
+// kind of row; revoked rows stay revoked.
+func (q *Queries) SetComposioConnectionStatusByAccount(ctx context.Context, arg SetComposioConnectionStatusByAccountParams) error {
+ _, err := q.db.Exec(ctx, setComposioConnectionStatusByAccount, arg.Status, arg.ConnectedAccountID)
+ return err
+}
+
+const setWorkspaceComposioConnectionStatus = `-- name: SetWorkspaceComposioConnectionStatus :exec
+UPDATE workspace_composio_connection
+SET status = $3, updated_at = now()
+WHERE id = $1 AND workspace_id = $2
+`
+
+type SetWorkspaceComposioConnectionStatusParams struct {
+ ID pgtype.UUID `json:"id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ Status string `json:"status"`
+}
+
+func (q *Queries) SetWorkspaceComposioConnectionStatus(ctx context.Context, arg SetWorkspaceComposioConnectionStatusParams) error {
+ _, err := q.db.Exec(ctx, setWorkspaceComposioConnectionStatus, arg.ID, arg.WorkspaceID, arg.Status)
+ return err
+}
+
+const touchUserComposioConnection = `-- name: TouchUserComposioConnection :exec
+UPDATE user_composio_connection SET last_used_at = now()
+WHERE id = $1 AND user_id = $2
+`
+
+type TouchUserComposioConnectionParams struct {
+ ID pgtype.UUID `json:"id"`
+ UserID pgtype.UUID `json:"user_id"`
+}
+
+func (q *Queries) TouchUserComposioConnection(ctx context.Context, arg TouchUserComposioConnectionParams) error {
+ _, err := q.db.Exec(ctx, touchUserComposioConnection, arg.ID, arg.UserID)
+ return err
+}
+
+const touchWorkspaceComposioConnection = `-- name: TouchWorkspaceComposioConnection :exec
+UPDATE workspace_composio_connection SET last_used_at = now()
+WHERE id = $1 AND workspace_id = $2
+`
+
+type TouchWorkspaceComposioConnectionParams struct {
+ ID pgtype.UUID `json:"id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+}
+
+func (q *Queries) TouchWorkspaceComposioConnection(ctx context.Context, arg TouchWorkspaceComposioConnectionParams) error {
+ _, err := q.db.Exec(ctx, touchWorkspaceComposioConnection, arg.ID, arg.WorkspaceID)
+ return err
+}
+
+const upsertAgentApp = `-- name: UpsertAgentApp :one
+INSERT INTO agent_app (workspace_id, agent_id, toolkit_slug, account_scope, level, created_by)
+VALUES ($1, $2, $3, $4, $5, $6)
+ON CONFLICT (agent_id, toolkit_slug) DO UPDATE SET
+ account_scope = EXCLUDED.account_scope,
+ level = EXCLUDED.level,
+ updated_at = now()
+RETURNING id, workspace_id, agent_id, toolkit_slug, account_scope, level, created_by, created_at, updated_at
+`
+
+type UpsertAgentAppParams struct {
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ AgentID pgtype.UUID `json:"agent_id"`
+ ToolkitSlug string `json:"toolkit_slug"`
+ AccountScope string `json:"account_scope"`
+ Level string `json:"level"`
+ CreatedBy pgtype.UUID `json:"created_by"`
+}
+
+func (q *Queries) UpsertAgentApp(ctx context.Context, arg UpsertAgentAppParams) (AgentApp, error) {
+ row := q.db.QueryRow(ctx, upsertAgentApp,
+ arg.WorkspaceID,
+ arg.AgentID,
+ arg.ToolkitSlug,
+ arg.AccountScope,
+ arg.Level,
+ arg.CreatedBy,
+ )
+ var i AgentApp
+ err := row.Scan(
+ &i.ID,
+ &i.WorkspaceID,
+ &i.AgentID,
+ &i.ToolkitSlug,
+ &i.AccountScope,
+ &i.Level,
+ &i.CreatedBy,
+ &i.CreatedAt,
+ &i.UpdatedAt,
+ )
+ return i, err
+}
+
+const upsertAppActionRule = `-- name: UpsertAppActionRule :one
+INSERT INTO app_action_rule (workspace_id, owner_user_id, toolkit_slug, action_class, policy, updated_by)
+VALUES ($1, $6::uuid, $2, $3, $4, $5)
+ON CONFLICT (workspace_id, toolkit_slug, action_class, COALESCE(owner_user_id, '00000000-0000-0000-0000-000000000000'::uuid))
+DO UPDATE SET policy = EXCLUDED.policy, updated_by = EXCLUDED.updated_by, updated_at = now()
+RETURNING id, workspace_id, owner_user_id, toolkit_slug, action_class, policy, updated_by, updated_at
+`
+
+type UpsertAppActionRuleParams struct {
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ ToolkitSlug string `json:"toolkit_slug"`
+ ActionClass string `json:"action_class"`
+ Policy string `json:"policy"`
+ UpdatedBy pgtype.UUID `json:"updated_by"`
+ OwnerUserID pgtype.UUID `json:"owner_user_id"`
+}
+
+func (q *Queries) UpsertAppActionRule(ctx context.Context, arg UpsertAppActionRuleParams) (AppActionRule, error) {
+ row := q.db.QueryRow(ctx, upsertAppActionRule,
+ arg.WorkspaceID,
+ arg.ToolkitSlug,
+ arg.ActionClass,
+ arg.Policy,
+ arg.UpdatedBy,
+ arg.OwnerUserID,
+ )
+ var i AppActionRule
+ err := row.Scan(
+ &i.ID,
+ &i.WorkspaceID,
+ &i.OwnerUserID,
+ &i.ToolkitSlug,
+ &i.ActionClass,
+ &i.Policy,
+ &i.UpdatedBy,
+ &i.UpdatedAt,
+ )
+ return i, err
+}
+
+const upsertAppToolClassOverride = `-- name: UpsertAppToolClassOverride :exec
+INSERT INTO app_tool_class_override (workspace_id, toolkit_slug, tool_slug, action_class, updated_by)
+VALUES ($1, $2, $3, $4, $5)
+ON CONFLICT (workspace_id, toolkit_slug, tool_slug) DO UPDATE SET
+ action_class = EXCLUDED.action_class,
+ updated_by = EXCLUDED.updated_by,
+ updated_at = now()
+`
+
+type UpsertAppToolClassOverrideParams struct {
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ ToolkitSlug string `json:"toolkit_slug"`
+ ToolSlug string `json:"tool_slug"`
+ ActionClass string `json:"action_class"`
+ UpdatedBy pgtype.UUID `json:"updated_by"`
+}
+
+func (q *Queries) UpsertAppToolClassOverride(ctx context.Context, arg UpsertAppToolClassOverrideParams) error {
+ _, err := q.db.Exec(ctx, upsertAppToolClassOverride,
+ arg.WorkspaceID,
+ arg.ToolkitSlug,
+ arg.ToolSlug,
+ arg.ActionClass,
+ arg.UpdatedBy,
+ )
+ return err
+}
+
+const upsertWorkspaceAppSetting = `-- name: UpsertWorkspaceAppSetting :one
+INSERT INTO workspace_app_setting (workspace_id, catalog_mode, allowed_toolkits, updated_by)
+VALUES ($1, $2, $4::text[], $3)
+ON CONFLICT (workspace_id) DO UPDATE SET
+ catalog_mode = EXCLUDED.catalog_mode,
+ allowed_toolkits = EXCLUDED.allowed_toolkits,
+ updated_by = EXCLUDED.updated_by,
+ updated_at = now()
+RETURNING workspace_id, catalog_mode, allowed_toolkits, updated_by, updated_at
+`
+
+type UpsertWorkspaceAppSettingParams struct {
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ CatalogMode string `json:"catalog_mode"`
+ UpdatedBy pgtype.UUID `json:"updated_by"`
+ AllowedToolkits []string `json:"allowed_toolkits"`
+}
+
+func (q *Queries) UpsertWorkspaceAppSetting(ctx context.Context, arg UpsertWorkspaceAppSettingParams) (WorkspaceAppSetting, error) {
+ row := q.db.QueryRow(ctx, upsertWorkspaceAppSetting,
+ arg.WorkspaceID,
+ arg.CatalogMode,
+ arg.UpdatedBy,
+ arg.AllowedToolkits,
+ )
+ var i WorkspaceAppSetting
+ err := row.Scan(
+ &i.WorkspaceID,
+ &i.CatalogMode,
+ &i.AllowedToolkits,
+ &i.UpdatedBy,
+ &i.UpdatedAt,
+ )
+ return i, err
+}
+
+const upsertWorkspaceComposioConnection = `-- name: UpsertWorkspaceComposioConnection :one
+
+INSERT INTO workspace_composio_connection (
+ workspace_id, toolkit_slug, auth_config_id, connected_account_id, composio_user_id, connected_by, status
+) VALUES (
+ $1, $2, $3, $4, $5, $6, 'active'
+)
+ON CONFLICT (workspace_id, connected_account_id) DO UPDATE SET
+ toolkit_slug = EXCLUDED.toolkit_slug,
+ auth_config_id = EXCLUDED.auth_config_id,
+ connected_by = EXCLUDED.connected_by,
+ status = 'active',
+ updated_at = now()
+RETURNING id, workspace_id, toolkit_slug, auth_config_id, connected_account_id, composio_user_id, connected_by, status, connected_at, last_used_at, created_at, updated_at
+`
+
+type UpsertWorkspaceComposioConnectionParams struct {
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ ToolkitSlug string `json:"toolkit_slug"`
+ AuthConfigID string `json:"auth_config_id"`
+ ConnectedAccountID string `json:"connected_account_id"`
+ ComposioUserID string `json:"composio_user_id"`
+ ConnectedBy pgtype.UUID `json:"connected_by"`
+}
+
+// =====================
+// Connected Apps v2 (MUL-8516)
+// =====================
+// Idempotent on (workspace_id, connected_account_id): a repeated callback for
+// the same account reactivates the row instead of inserting another.
+func (q *Queries) UpsertWorkspaceComposioConnection(ctx context.Context, arg UpsertWorkspaceComposioConnectionParams) (WorkspaceComposioConnection, error) {
+ row := q.db.QueryRow(ctx, upsertWorkspaceComposioConnection,
+ arg.WorkspaceID,
+ arg.ToolkitSlug,
+ arg.AuthConfigID,
+ arg.ConnectedAccountID,
+ arg.ComposioUserID,
+ arg.ConnectedBy,
+ )
+ var i WorkspaceComposioConnection
+ err := row.Scan(
+ &i.ID,
+ &i.WorkspaceID,
+ &i.ToolkitSlug,
+ &i.AuthConfigID,
+ &i.ConnectedAccountID,
+ &i.ComposioUserID,
+ &i.ConnectedBy,
+ &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.go
index 303482873a..a2cf087231 100644
--- a/server/pkg/db/generated/models.go
+++ b/server/pkg/db/generated/models.go
@@ -56,6 +56,18 @@ type Agent struct {
ConversationStarters []byte `json:"conversation_starters"`
}
+type AgentApp struct {
+ ID pgtype.UUID `json:"id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ AgentID pgtype.UUID `json:"agent_id"`
+ ToolkitSlug string `json:"toolkit_slug"`
+ AccountScope string `json:"account_scope"`
+ Level string `json:"level"`
+ CreatedBy pgtype.UUID `json:"created_by"`
+ CreatedAt pgtype.Timestamptz `json:"created_at"`
+ UpdatedAt pgtype.Timestamptz `json:"updated_at"`
+}
+
type AgentBuilderDraft struct {
ChatSessionID pgtype.UUID `json:"chat_session_id"`
WorkspaceID pgtype.UUID `json:"workspace_id"`
@@ -189,6 +201,73 @@ type AgentToLabel struct {
CreatedAt pgtype.Timestamptz `json:"created_at"`
}
+type AppActionRequest struct {
+ ID pgtype.UUID `json:"id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ Kind string `json:"kind"`
+ Status string `json:"status"`
+ TaskID pgtype.UUID `json:"task_id"`
+ AgentID pgtype.UUID `json:"agent_id"`
+ IssueID pgtype.UUID `json:"issue_id"`
+ ChatSessionID pgtype.UUID `json:"chat_session_id"`
+ ApproverUserID pgtype.UUID `json:"approver_user_id"`
+ AccountScope string `json:"account_scope"`
+ ToolkitSlug string `json:"toolkit_slug"`
+ ToolSlug string `json:"tool_slug"`
+ ActionClass string `json:"action_class"`
+ Arguments []byte `json:"arguments"`
+ Summary string `json:"summary"`
+ ApprovedArguments []byte `json:"approved_arguments"`
+ Result []byte `json:"result"`
+ Error pgtype.Text `json:"error"`
+ Reason pgtype.Text `json:"reason"`
+ ExpiresAt pgtype.Timestamptz `json:"expires_at"`
+ RemindedAt pgtype.Timestamptz `json:"reminded_at"`
+ DecidedBy pgtype.UUID `json:"decided_by"`
+ DecidedAt pgtype.Timestamptz `json:"decided_at"`
+ CreatedAt pgtype.Timestamptz `json:"created_at"`
+ UpdatedAt pgtype.Timestamptz `json:"updated_at"`
+}
+
+type AppActionRule struct {
+ ID pgtype.UUID `json:"id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ OwnerUserID pgtype.UUID `json:"owner_user_id"`
+ ToolkitSlug string `json:"toolkit_slug"`
+ ActionClass string `json:"action_class"`
+ Policy string `json:"policy"`
+ UpdatedBy pgtype.UUID `json:"updated_by"`
+ UpdatedAt pgtype.Timestamptz `json:"updated_at"`
+}
+
+type AppToolCall struct {
+ ID pgtype.UUID `json:"id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ TaskID pgtype.UUID `json:"task_id"`
+ AgentID pgtype.UUID `json:"agent_id"`
+ IssueID pgtype.UUID `json:"issue_id"`
+ ChatSessionID pgtype.UUID `json:"chat_session_id"`
+ TriggeredBy pgtype.UUID `json:"triggered_by"`
+ AccountScope string `json:"account_scope"`
+ AccountOwnerUserID pgtype.UUID `json:"account_owner_user_id"`
+ ToolkitSlug string `json:"toolkit_slug"`
+ ToolSlug string `json:"tool_slug"`
+ ActionClass string `json:"action_class"`
+ Outcome string `json:"outcome"`
+ RequestID pgtype.UUID `json:"request_id"`
+ Error pgtype.Text `json:"error"`
+ CreatedAt pgtype.Timestamptz `json:"created_at"`
+}
+
+type AppToolClassOverride struct {
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ ToolkitSlug string `json:"toolkit_slug"`
+ ToolSlug string `json:"tool_slug"`
+ ActionClass string `json:"action_class"`
+ UpdatedBy pgtype.UUID `json:"updated_by"`
+ UpdatedAt pgtype.Timestamptz `json:"updated_at"`
+}
+
type Attachment struct {
ID pgtype.UUID `json:"id"`
WorkspaceID pgtype.UUID `json:"workspace_id"`
@@ -1829,6 +1908,29 @@ type Workspace struct {
AttributionFailClosed bool `json:"attribution_fail_closed"`
}
+type WorkspaceAppSetting struct {
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ CatalogMode string `json:"catalog_mode"`
+ AllowedToolkits []string `json:"allowed_toolkits"`
+ UpdatedBy pgtype.UUID `json:"updated_by"`
+ UpdatedAt pgtype.Timestamptz `json:"updated_at"`
+}
+
+type WorkspaceComposioConnection struct {
+ ID pgtype.UUID `json:"id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ ToolkitSlug string `json:"toolkit_slug"`
+ AuthConfigID string `json:"auth_config_id"`
+ ConnectedAccountID string `json:"connected_account_id"`
+ ComposioUserID string `json:"composio_user_id"`
+ ConnectedBy pgtype.UUID `json:"connected_by"`
+ 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 WorkspaceInvitation struct {
ID pgtype.UUID `json:"id"`
WorkspaceID pgtype.UUID `json:"workspace_id"`
diff --git a/server/pkg/db/generated/workspace_delete.sql.go b/server/pkg/db/generated/workspace_delete.sql.go
index 648a6fd268..a010543da2 100644
--- a/server/pkg/db/generated/workspace_delete.sql.go
+++ b/server/pkg/db/generated/workspace_delete.sql.go
@@ -483,6 +483,27 @@ deleted_channel_binding_tokens AS (
deleted_wecom_install_sessions AS (
DELETE FROM wecom_install_session WHERE workspace_id = $1
),
+deleted_workspace_composio_connections AS (
+ DELETE FROM workspace_composio_connection WHERE workspace_id = $1
+),
+deleted_agent_apps AS (
+ DELETE FROM agent_app WHERE workspace_id = $1
+),
+deleted_app_action_rules AS (
+ DELETE FROM app_action_rule WHERE workspace_id = $1
+),
+deleted_app_action_requests AS (
+ DELETE FROM app_action_request WHERE workspace_id = $1
+),
+deleted_app_tool_calls AS (
+ DELETE FROM app_tool_call WHERE workspace_id = $1
+),
+deleted_workspace_app_settings AS (
+ DELETE FROM workspace_app_setting WHERE workspace_id = $1
+),
+deleted_app_tool_class_overrides AS (
+ DELETE FROM app_tool_class_override WHERE workspace_id = $1
+),
deleted_lark_chat_bindings AS (
DELETE FROM lark_chat_session_binding
WHERE installation_id IN (SELECT id FROM ws_lark_installations)
diff --git a/server/pkg/db/queries/connected_apps.sql b/server/pkg/db/queries/connected_apps.sql
new file mode 100644
index 0000000000..d6f882faf6
--- /dev/null
+++ b/server/pkg/db/queries/connected_apps.sql
@@ -0,0 +1,360 @@
+-- =====================
+-- Connected Apps v2 (MUL-8516)
+-- =====================
+
+-- name: UpsertWorkspaceComposioConnection :one
+-- Idempotent on (workspace_id, connected_account_id): a repeated callback for
+-- the same account reactivates the row instead of inserting another.
+INSERT INTO workspace_composio_connection (
+ workspace_id, toolkit_slug, auth_config_id, connected_account_id, composio_user_id, connected_by, status
+) VALUES (
+ $1, $2, $3, $4, $5, $6, 'active'
+)
+ON CONFLICT (workspace_id, connected_account_id) DO UPDATE SET
+ toolkit_slug = EXCLUDED.toolkit_slug,
+ auth_config_id = EXCLUDED.auth_config_id,
+ connected_by = EXCLUDED.connected_by,
+ status = 'active',
+ updated_at = now()
+RETURNING *;
+
+-- name: ListWorkspaceComposioConnections :many
+-- Active and expired team accounts, newest first. Revoked rows are history.
+SELECT * FROM workspace_composio_connection
+WHERE workspace_id = $1 AND status <> 'revoked'
+ORDER BY connected_at DESC;
+
+-- name: GetWorkspaceComposioConnection :one
+SELECT * FROM workspace_composio_connection
+WHERE id = $1 AND workspace_id = $2;
+
+-- name: SetWorkspaceComposioConnectionStatus :exec
+UPDATE workspace_composio_connection
+SET status = $3, updated_at = now()
+WHERE id = $1 AND workspace_id = $2;
+
+-- name: RevokeOtherWorkspaceComposioConnections :many
+-- A workspace holds one team account per app: connecting again replaces the
+-- previous account. Returns the replaced rows so their upstream grant can be
+-- revoked.
+UPDATE workspace_composio_connection
+SET status = 'revoked', updated_at = now()
+WHERE workspace_id = $1 AND toolkit_slug = $2 AND id <> $3 AND status <> 'revoked'
+RETURNING *;
+
+-- name: TouchWorkspaceComposioConnection :exec
+UPDATE workspace_composio_connection SET last_used_at = now()
+WHERE id = $1 AND workspace_id = $2;
+
+-- name: TouchUserComposioConnection :exec
+UPDATE user_composio_connection SET last_used_at = now()
+WHERE id = $1 AND user_id = $2;
+
+-- name: SetComposioConnectionStatusByAccount :exec
+-- Webhook path: Composio names only the connected account. Applies to either
+-- kind of row; revoked rows stay revoked.
+WITH personal AS (
+ UPDATE user_composio_connection
+ SET status = sqlc.arg('status')::text, updated_at = now()
+ WHERE connected_account_id = sqlc.arg('connected_account_id')::text AND status <> 'revoked'
+)
+UPDATE workspace_composio_connection
+SET status = sqlc.arg('status')::text, updated_at = now()
+WHERE connected_account_id = sqlc.arg('connected_account_id')::text AND status <> 'revoked';
+
+-- name: ListUserComposioConnectionsAnyStatus :many
+-- A member's personal accounts for the app list: active and expired.
+SELECT * FROM user_composio_connection
+WHERE user_id = $1 AND status <> 'revoked'
+ORDER BY connected_at DESC;
+
+-- name: ListAgentApps :many
+SELECT * FROM agent_app
+WHERE agent_id = $1
+ORDER BY toolkit_slug;
+
+-- name: ListAgentAppsInWorkspace :many
+SELECT * FROM agent_app
+WHERE workspace_id = $1
+ORDER BY toolkit_slug, agent_id;
+
+-- name: UpsertAgentApp :one
+INSERT INTO agent_app (workspace_id, agent_id, toolkit_slug, account_scope, level, created_by)
+VALUES ($1, $2, $3, $4, $5, $6)
+ON CONFLICT (agent_id, toolkit_slug) DO UPDATE SET
+ account_scope = EXCLUDED.account_scope,
+ level = EXCLUDED.level,
+ updated_at = now()
+RETURNING *;
+
+-- name: DeleteAgentAppsExcept :exec
+DELETE FROM agent_app
+WHERE agent_id = $1 AND NOT (toolkit_slug = ANY(sqlc.arg('keep')::text[]));
+
+-- name: ListAppActionRules :many
+-- Rules of one account: owner_user_id NULL is the team account.
+SELECT * FROM app_action_rule
+WHERE workspace_id = $1
+ AND toolkit_slug = $2
+ AND owner_user_id IS NOT DISTINCT FROM sqlc.narg('owner_user_id')::uuid;
+
+-- name: ListAppActionRulesForRun :many
+-- Every rule that can apply to a run: the team rules and the triggering
+-- member's personal rules for the run's apps.
+SELECT * FROM app_action_rule
+WHERE workspace_id = $1
+ AND toolkit_slug = ANY(sqlc.arg('toolkit_slugs')::text[])
+ AND (owner_user_id IS NULL OR owner_user_id = sqlc.narg('owner_user_id')::uuid);
+
+-- name: UpsertAppActionRule :one
+INSERT INTO app_action_rule (workspace_id, owner_user_id, toolkit_slug, action_class, policy, updated_by)
+VALUES ($1, sqlc.narg('owner_user_id')::uuid, $2, $3, $4, $5)
+ON CONFLICT (workspace_id, toolkit_slug, action_class, COALESCE(owner_user_id, '00000000-0000-0000-0000-000000000000'::uuid))
+DO UPDATE SET policy = EXCLUDED.policy, updated_by = EXCLUDED.updated_by, updated_at = now()
+RETURNING *;
+
+-- name: CreateAppActionRequest :one
+INSERT INTO app_action_request (
+ workspace_id, kind, task_id, agent_id, issue_id, chat_session_id, approver_user_id,
+ account_scope, toolkit_slug, tool_slug, action_class, arguments, summary, expires_at
+) VALUES (
+ $1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14
+)
+RETURNING *;
+
+-- name: FindPendingAppActionRequest :one
+-- The same run asking for the same call again (an agent retrying after a
+-- "submitted" answer) reuses the open request instead of stacking another.
+SELECT * FROM app_action_request
+WHERE task_id = $1 AND kind = $2 AND toolkit_slug = $3 AND tool_slug = $4
+ AND arguments = sqlc.arg('arguments')::jsonb AND status = 'pending'
+ORDER BY created_at DESC
+LIMIT 1;
+
+-- name: GetAppActionRequest :one
+SELECT * FROM app_action_request
+WHERE id = $1 AND workspace_id = $2;
+
+-- name: ListPendingAppActionRequestsForIssue :many
+-- Every request of an issue still waiting for a decision. Expiry and the
+-- per-minute call budget keep this short; the cap only bounds a runaway.
+SELECT * FROM app_action_request
+WHERE workspace_id = $1 AND issue_id = $2 AND status = 'pending'
+ORDER BY created_at
+LIMIT 500;
+
+-- name: ListDecidedAppActionRequestsForIssue :many
+-- One page of an issue's decided requests, newest first, before a cursor.
+SELECT * FROM app_action_request
+WHERE workspace_id = $1 AND issue_id = $2 AND status <> 'pending'
+ AND (sqlc.narg('before')::timestamptz IS NULL OR created_at < sqlc.narg('before')::timestamptz)
+ORDER BY created_at DESC
+LIMIT sqlc.arg('page_size');
+
+-- name: ListPendingAppActionRequestsForChatSession :many
+SELECT * FROM app_action_request
+WHERE workspace_id = $1 AND chat_session_id = $2 AND status = 'pending'
+ORDER BY created_at
+LIMIT 500;
+
+-- name: ListDecidedAppActionRequestsForChatSession :many
+SELECT * FROM app_action_request
+WHERE workspace_id = $1 AND chat_session_id = $2 AND status <> 'pending'
+ AND (sqlc.narg('before')::timestamptz IS NULL OR created_at < sqlc.narg('before')::timestamptz)
+ORDER BY created_at DESC
+LIMIT sqlc.arg('page_size');
+
+-- name: CancelAppActionRequest :one
+-- Withdraws one pending request whose approver may no longer act on it.
+UPDATE app_action_request
+SET status = 'cancelled', updated_at = now()
+WHERE id = $1 AND workspace_id = $2 AND status = 'pending'
+RETURNING *;
+
+-- name: CancelPendingAppActionRequestsForApprover :many
+-- A member leaving the workspace withdraws everything waiting on them.
+UPDATE app_action_request
+SET status = 'cancelled', updated_at = now()
+WHERE workspace_id = $1 AND approver_user_id = $2 AND status = 'pending'
+RETURNING *;
+
+-- name: ListPendingAppActionRequestsForApprover :many
+SELECT * FROM app_action_request
+WHERE workspace_id = $1 AND approver_user_id = $2 AND status = 'pending'
+ORDER BY created_at
+LIMIT 200;
+
+-- name: DecideAppActionRequest :one
+-- Compare-and-set from pending: a second click, another device, or the expiry
+-- sweep racing the decision finds no pending row and returns no rows.
+UPDATE app_action_request
+SET status = $3,
+ approved_arguments = sqlc.narg('approved_arguments')::jsonb,
+ reason = sqlc.narg('reason')::text,
+ decided_by = $4,
+ decided_at = now(),
+ updated_at = now()
+WHERE id = $1 AND workspace_id = $2 AND status = 'pending' AND approver_user_id = $4
+RETURNING *;
+
+-- name: SetAppActionRequestOutcome :one
+-- Records what executing an approved request produced. Only moves an approved
+-- request; status becomes 'failed' when execution failed.
+UPDATE app_action_request
+SET status = $3, result = sqlc.narg('result')::jsonb, error = sqlc.narg('error')::text, updated_at = now()
+WHERE id = $1 AND workspace_id = $2 AND status = 'approved'
+RETURNING *;
+
+-- name: ExpireDueAppActionRequests :many
+UPDATE app_action_request
+SET status = 'expired', updated_at = now()
+WHERE id IN (
+ SELECT r.id FROM app_action_request r
+ WHERE r.status = 'pending' AND r.expires_at <= now()
+ ORDER BY r.expires_at
+ LIMIT 200
+ FOR UPDATE SKIP LOCKED
+)
+RETURNING *;
+
+-- name: ClaimAppActionRequestReminders :many
+-- Pending requests within two hours of expiry that have not been reminded.
+UPDATE app_action_request
+SET reminded_at = now(), updated_at = now()
+WHERE id IN (
+ SELECT r.id FROM app_action_request r
+ WHERE r.status = 'pending' AND r.reminded_at IS NULL
+ AND r.expires_at <= now() + interval '2 hours'
+ AND r.expires_at > now()
+ ORDER BY r.expires_at
+ LIMIT 200
+ FOR UPDATE SKIP LOCKED
+)
+RETURNING *;
+
+-- name: CancelPendingTeamAppActionRequests :many
+-- Disconnecting a team account cancels what was waiting to use it.
+UPDATE app_action_request
+SET status = 'cancelled', updated_at = now()
+WHERE workspace_id = $1 AND toolkit_slug = $2 AND account_scope = 'team' AND status = 'pending'
+RETURNING *;
+
+-- name: CountPendingTeamAppActionRequests :one
+SELECT count(*) FROM app_action_request
+WHERE workspace_id = $1 AND toolkit_slug = $2 AND account_scope = 'team' AND status = 'pending';
+
+-- name: CountActiveTasksForAgents :one
+SELECT count(*) FROM agent_task_queue
+WHERE agent_id = ANY(sqlc.arg('agent_ids')::uuid[])
+ AND status IN ('queued', 'dispatched', 'running');
+
+-- name: CountActiveAutopilotsForAgents :one
+SELECT count(*) FROM autopilot
+WHERE workspace_id = $1
+ AND assignee_type = 'agent'
+ AND assignee_id = ANY(sqlc.arg('agent_ids')::uuid[])
+ AND status = 'active';
+
+-- name: InsertAppToolCall :exec
+INSERT INTO app_tool_call (
+ workspace_id, task_id, agent_id, issue_id, chat_session_id, triggered_by,
+ account_scope, account_owner_user_id, toolkit_slug, tool_slug, action_class,
+ outcome, request_id, error
+) VALUES (
+ $1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14
+);
+
+-- name: ListTeamAppToolCalls :many
+SELECT * FROM app_tool_call
+WHERE workspace_id = $1 AND toolkit_slug = $2 AND account_scope = 'team'
+ORDER BY created_at DESC
+LIMIT $3;
+
+-- name: ListPersonalAppToolCalls :many
+-- A member's own account activity. Only the owner reads this.
+SELECT * FROM app_tool_call
+WHERE workspace_id = $1 AND toolkit_slug = $2 AND account_scope = 'personal'
+ AND account_owner_user_id = $3
+ORDER BY created_at DESC
+LIMIT $4;
+
+-- name: GetWorkspaceAppSetting :one
+SELECT * FROM workspace_app_setting WHERE workspace_id = $1;
+
+-- name: UpsertWorkspaceAppSetting :one
+INSERT INTO workspace_app_setting (workspace_id, catalog_mode, allowed_toolkits, updated_by)
+VALUES ($1, $2, sqlc.arg('allowed_toolkits')::text[], $3)
+ON CONFLICT (workspace_id) DO UPDATE SET
+ catalog_mode = EXCLUDED.catalog_mode,
+ allowed_toolkits = EXCLUDED.allowed_toolkits,
+ updated_by = EXCLUDED.updated_by,
+ updated_at = now()
+RETURNING *;
+
+-- name: ListAppToolClassOverrides :many
+SELECT * FROM app_tool_class_override
+WHERE workspace_id = $1 AND toolkit_slug = $2;
+
+-- name: GetAppToolClassOverride :one
+SELECT action_class FROM app_tool_class_override
+WHERE workspace_id = $1 AND toolkit_slug = $2 AND tool_slug = $3;
+
+-- name: UpsertAppToolClassOverride :exec
+INSERT INTO app_tool_class_override (workspace_id, toolkit_slug, tool_slug, action_class, updated_by)
+VALUES ($1, $2, $3, $4, $5)
+ON CONFLICT (workspace_id, toolkit_slug, tool_slug) DO UPDATE SET
+ action_class = EXCLUDED.action_class,
+ updated_by = EXCLUDED.updated_by,
+ updated_at = now();
+
+-- name: DeleteAppToolClassOverride :exec
+DELETE FROM app_tool_class_override
+WHERE workspace_id = $1 AND toolkit_slug = $2 AND tool_slug = $3;
+
+-- name: CountRecentAppAccountCalls :one
+-- Calls that reached the app through one account within the window; backs the
+-- per-account rate limit. Blocked, pending and limited calls never ran.
+SELECT count(*) FROM app_tool_call
+WHERE workspace_id = $1 AND toolkit_slug = $2 AND account_scope = $3
+ AND account_owner_user_id IS NOT DISTINCT FROM sqlc.narg('owner')::uuid
+ AND outcome IN ('ok', 'error', 'approved')
+ AND created_at > sqlc.arg('since')::timestamptz;
+
+-- name: HasBlockedAppToolCall :one
+-- Whether a run already hit a block on this tool, so the person is told once.
+SELECT EXISTS (
+ SELECT 1 FROM app_tool_call
+ WHERE workspace_id = $1 AND toolkit_slug = $2 AND task_id = $3
+ AND tool_slug = $4 AND outcome = 'blocked'
+ AND created_at > sqlc.arg('since')::timestamptz
+);
+
+-- name: ListIssueAppToolCalls :many
+-- The latest calls the runs of one issue made, newest first. Arguments are
+-- never stored.
+SELECT * FROM app_tool_call
+WHERE workspace_id = $1 AND issue_id = $2
+ORDER BY created_at DESC
+LIMIT 500;
+
+-- name: ListPendingConnectRequestsForUser :many
+-- Connection requests a member is asked to answer for one app; resolved when
+-- they finish connecting it.
+SELECT * FROM app_action_request
+WHERE approver_user_id = $1 AND toolkit_slug = $2 AND kind = 'connect'
+ AND status = 'pending' AND account_scope = 'personal';
+
+-- name: AppendQueuedTaskHandoffNote :execrows
+-- Folds a decision into a run that has not been claimed yet, so approving a
+-- batch of requests starts one run instead of one per request.
+UPDATE agent_task_queue
+SET handoff_note = CASE
+ WHEN handoff_note IS NULL OR handoff_note = '' THEN sqlc.arg('note')::text
+ ELSE handoff_note || E'\n\n' || sqlc.arg('note')::text
+ END
+WHERE id = $1 AND status = 'queued';
+
+-- name: SetAgentComposioToolkitAllowlist :exec
+-- Keeps the legacy allowlist column in step with agent_app for older clients.
+UPDATE agent SET composio_toolkit_allowlist = sqlc.arg('slugs')::text[], updated_at = now()
+WHERE id = $1;
diff --git a/server/pkg/db/queries/workspace_delete.sql b/server/pkg/db/queries/workspace_delete.sql
index a6c3c0079d..a53a4b14ad 100644
--- a/server/pkg/db/queries/workspace_delete.sql
+++ b/server/pkg/db/queries/workspace_delete.sql
@@ -493,6 +493,27 @@ deleted_channel_binding_tokens AS (
deleted_wecom_install_sessions AS (
DELETE FROM wecom_install_session WHERE workspace_id = $1
),
+deleted_workspace_composio_connections AS (
+ DELETE FROM workspace_composio_connection WHERE workspace_id = $1
+),
+deleted_agent_apps AS (
+ DELETE FROM agent_app WHERE workspace_id = $1
+),
+deleted_app_action_rules AS (
+ DELETE FROM app_action_rule WHERE workspace_id = $1
+),
+deleted_app_action_requests AS (
+ DELETE FROM app_action_request WHERE workspace_id = $1
+),
+deleted_app_tool_calls AS (
+ DELETE FROM app_tool_call WHERE workspace_id = $1
+),
+deleted_workspace_app_settings AS (
+ DELETE FROM workspace_app_setting WHERE workspace_id = $1
+),
+deleted_app_tool_class_overrides AS (
+ DELETE FROM app_tool_class_override WHERE workspace_id = $1
+),
deleted_lark_chat_bindings AS (
DELETE FROM lark_chat_session_binding
WHERE installation_id IN (SELECT id FROM ws_lark_installations)