Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-8821: simplify connected app access (#10177)
Multica Eveb37b0f0005ad
diff --git a/packages/core/api/connected-apps.test.ts b/packages/core/api/connected-apps.test.tsindex 21b59f4bc1..9136e3d697 100644--- a/packages/core/api/connected-apps.test.ts+++ b/packages/core/api/connected-apps.test.ts@@ -49,12 +49,25 @@ describe("Connected Apps API parsing", () => {const overview = await client.getAppsOverview();expect(overview.catalog_mode).toBe("custom");expect(overview.personal[0]?.connected_by).toBeNull();+ expect(overview.personal[0]?.actions_blocked).toBe(false);expect(overview.agent_apps[0]?.level).toBe("write");({ client } = respondWith({ team: "nope" }));expect(await client.getAppsOverview()).toEqual(EMPTY_APPS_OVERVIEW);});+ it("reads saved account restrictions and tolerates malformed optional flags", async () => {+ const { client } = respondWith({+ catalog_mode: "all", team: [], agent_apps: [],+ personal: [+ { id: "c1", toolkit_slug: "gmail", actions_blocked: true },+ { id: "c2", toolkit_slug: "notion", actions_blocked: "yes" },+ ],+ });+ const overview = await client.getAppsOverview();+ expect(overview.personal.map((c) => c.actions_blocked)).toEqual([true, false]);+ });+it("maps enum values this client does not know to the cautious ones", async () => {const { client } = respondWith({catalog_mode: "future_mode",diff --git a/packages/core/api/schemas.ts b/packages/core/api/schemas.tsindex afe9cdfe17..3686b3fbfd 100644--- a/packages/core/api/schemas.ts+++ b/packages/core/api/schemas.ts@@ -4104,6 +4104,7 @@ const AppConnectionSchema = z.object({connected_by: appNullableString,connected_at: z.string().default(""),last_used_at: appNullableString,+ actions_blocked: z.boolean().default(false).catch(false),}).loose();const AgentAppSchema = z.object({diff --git a/packages/core/connected-apps/index.ts b/packages/core/connected-apps/index.tsindex a6cefca2fd..a42de1ecea 100644--- a/packages/core/connected-apps/index.ts+++ b/packages/core/connected-apps/index.ts@@ -2,10 +2,7 @@ export {connectedAppsKeys,appsOverviewOptions,appCatalogOptions,- fullAppCatalogOptions,- appToolsOptions,issueAppCallsOptions,- appRulesOptions,appActivityOptions,teamAppImpactOptions,agentAppsOptions,@@ -13,10 +10,8 @@ export {chatAppRequestsOptions,} from "./queries";export {- useUpdateAppSettings,- useUpdateAppRules,- useUpdateAppToolClass,useDisconnectTeamApp,+ useRestoreAppAccess,useUpdateAgentApps,useDecideAppRequest,} from "./mutations";diff --git a/packages/core/connected-apps/mutations.ts b/packages/core/connected-apps/mutations.tsindex 2f7b2c9cde..5156ec555c 100644--- a/packages/core/connected-apps/mutations.ts+++ b/packages/core/connected-apps/mutations.ts@@ -1,46 +1,25 @@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 type { AppAccountScope, AppActionClass, UpdateAgentAppsRequest } from "../types";import { workspaceKeys } from "../workspace/queries";import { connectedAppsKeys } from "./queries";-export function useUpdateAppSettings() {+/** Explicitly replaces saved restrictions; never runs automatically on load. */+export function useRestoreAppAccess() {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) });+ mutationFn: async (target: { slug: string; scope: AppAccountScope } | { catalog: true }) => {+ if ("catalog" in target) {+ await api.updateAppSettings({ catalog_mode: "all", allowed_toolkits: [] });+ } else {+ await api.updateAppRules(target.slug, target.scope,+ (["read", "write", "send", "delete", "share"] as AppActionClass[])+ .map((action_class) => ({ action_class, policy: "allow" })));+ }},- });-}--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) }),+ onSettled: () => qc.invalidateQueries({ queryKey: connectedAppsKeys.all(wsId) }),});}diff --git a/packages/core/connected-apps/queries.ts b/packages/core/connected-apps/queries.tsindex 51fa5b35ad..9d5704ff0c 100644--- a/packages/core/connected-apps/queries.ts+++ b/packages/core/connected-apps/queries.ts@@ -3,18 +3,14 @@ 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. */+ * workspace id: team accounts, activity, 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,@@ -41,20 +37,6 @@ export const appCatalogOptions = (wsId: string) =>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({@@ -62,12 +44,6 @@ export const issueAppCallsOptions = (wsId: string, issueId: string) =>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),diff --git a/packages/core/types/connected-apps.ts b/packages/core/types/connected-apps.tsindex 720c4d6caa..1e3b121f81 100644--- a/packages/core/types/connected-apps.ts+++ b/packages/core/types/connected-apps.ts@@ -6,12 +6,13 @@* 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. */+/** How far an agent may go with an app. The saved `confirm_writes` value+ * is accepted for compatibility and now runs directly like `write`. */export type AppAccessLevel = "read" | "confirm_writes" | "write";export type AppActionClass = "read" | "write" | "send" | "delete" | "share";+/** Saved `confirm` rules now allow calls directly. */export type AppActionPolicy = "allow" | "confirm" | "block";/** `all` lists every connectable app; `curated` only Multica's reviewed set;@@ -25,6 +26,8 @@ export interface AppConnection {connected_by?: string | null;connected_at: string;last_used_at: string | null;+ /** Saved account rules still block one or more action classes. */+ actions_blocked?: boolean;}export interface AgentApp {diff --git a/packages/views/agents/components/tabs/agent-apps-tab.test.tsx b/packages/views/agents/components/tabs/agent-apps-tab.test.tsxnew file mode 100644index 0000000000..6c6a5cbba4--- /dev/null+++ b/packages/views/agents/components/tabs/agent-apps-tab.test.tsx@@ -0,0 +1,94 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import type { ReactNode } from "react";+import { cleanup, render, screen, waitFor, within } from "@testing-library/react";+import userEvent from "@testing-library/user-event";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { api } from "@multica/core/api";+import { I18nProvider } from "@multica/core/i18n/react";+import type { Agent, AgentApp } from "@multica/core/types";+import enCommon from "../../../locales/en/common.json";+import enAgents from "../../../locales/en/agents.json";+import enSettings from "../../../locales/en/settings.json";+import { AgentAppsTab } from "./agent-apps-tab";++vi.mock("@multica/core/api", () => ({ api: {+ listAgentApps: vi.fn(), getAppsOverview: vi.fn(), listAppCatalog: vi.fn(), updateAgentApps: vi.fn(),+} }));+vi.mock("@multica/core/hooks", () => ({ useWorkspaceId: () => "ws-1" }));+vi.mock("@multica/core/paths", () => ({ useWorkspacePaths: () => ({ settings: () => "/ws/settings" }) }));+vi.mock("../../../navigation", () => ({+ AppLink: ({ href, children }: { href: string; children: ReactNode }) => <a href={href}>{children}</a>,+}));++const apps: AgentApp[] = [+ { agent_id: "a1", toolkit_slug: "gmail", account_scope: "personal", level: "read" },+];++beforeEach(() => {+ vi.mocked(api.listAgentApps).mockResolvedValue({ apps });+ vi.mocked(api.getAppsOverview).mockResolvedValue({+ catalog_mode: "all", can_manage: true, team: [], personal: [], agent_apps: apps,+ });+ vi.mocked(api.listAppCatalog).mockResolvedValue({+ catalog_mode: "all",+ apps: [+ { slug: "gmail", name: "Gmail", curated: true },+ { slug: "notion", name: "Notion", curated: true },+ ],+ });+ vi.mocked(api.updateAgentApps).mockResolvedValue({ apps });+});++afterEach(() => {+ cleanup();+ vi.clearAllMocks();+});++function renderApps() {+ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });+ return render(+ <QueryClientProvider client={queryClient}>+ <I18nProvider locale="en" resources={{ en: { common: enCommon, agents: enAgents, settings: enSettings } }}>+ <AgentAppsTab agent={{ id: "a1", permission_mode: "private" } as Agent} />+ </I18nProvider>+ </QueryClientProvider>,+ );+}++describe("AgentAppsTab", () => {+ it("assigns apps and accounts without a permission control, preserving existing grants", async () => {+ const user = userEvent.setup();+ renderApps();+ await screen.findByText("Gmail");+ expect(screen.queryByRole("combobox", { name: "Level" })).not.toBeInTheDocument();+ expect(screen.getByRole("combobox", { name: "Account" })).toBeVisible();+ await user.click(screen.getByRole("combobox", { name: "Add an app…" }));+ await user.click(await screen.findByRole("option", { name: "Notion" }));+ await waitFor(() => expect(api.updateAgentApps).toHaveBeenCalledWith("a1", {+ apps: [+ { toolkit_slug: "gmail", account_scope: "personal", level: "read" },+ { toolkit_slug: "notion", account_scope: "personal", level: "write" },+ ],+ }));+ });++ it("revokes access by removing the app", async () => {+ const user = userEvent.setup();+ renderApps();+ await user.click(await screen.findByRole("button", { name: "Remove Gmail" }));+ await waitFor(() => expect(api.updateAgentApps).toHaveBeenCalledWith("a1", { apps: [] }));+ });++ it("explains saved read-only access and only replaces it after confirmation", async () => {+ const user = userEvent.setup();+ renderApps();+ expect(await screen.findByText("This app still has read-only access from an earlier setup.")).toBeVisible();+ expect(api.updateAgentApps).not.toHaveBeenCalled();+ await user.click(screen.getByRole("button", { name: "Allow all actions" }));+ expect(api.updateAgentApps).not.toHaveBeenCalled();+ await user.click(within(screen.getByRole("alertdialog")).getByRole("button", { name: "Allow all actions" }));+ await waitFor(() => expect(api.updateAgentApps).toHaveBeenCalledWith("a1", {+ apps: [{ toolkit_slug: "gmail", account_scope: "personal", level: "write" }],+ }));+ });+});diff --git a/packages/views/agents/components/tabs/agent-apps-tab.tsx b/packages/views/agents/components/tabs/agent-apps-tab.tsxindex 97e5e81a72..a4299d8eb9 100644--- a/packages/views/agents/components/tabs/agent-apps-tab.tsx+++ b/packages/views/agents/components/tabs/agent-apps-tab.tsx@@ -18,28 +18,25 @@ import {appCatalogOptions,appsOverviewOptions,useUpdateAgentApps,+ useRestoreAppAccess,} 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 { SavedAppRestriction } from "../../../common/saved-app-restriction";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.- */+/** Apps this agent can use and whose account each acts as.+ * Team account changes require a workspace admin. */export function AgentAppsTab({ agent }: { agent: Agent }) {const { t } = useT("agents");const { t: ts } = useT("settings");@@ -49,6 +46,7 @@ export function AgentAppsTab({ agent }: { agent: Agent }) {const overview = useQuery(appsOverviewOptions(wsId));const catalog = useQuery(appCatalogOptions(wsId));const update = useUpdateAgentApps(agent.id);+ const restore = useRestoreAppAccess();const canManageTeam = overview.data?.can_manage ?? false;const apps = useMemo(() => appsQuery.data ?? [], [appsQuery.data]);@@ -81,14 +79,11 @@ export function AgentAppsTab({ agent }: { agent: Agent }) {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 }]);+ save([...apps, { agent_id: agent.id, toolkit_slug: slug, account_scope: scope, level: "write" }]);};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) {@@ -102,6 +97,11 @@ export function AgentAppsTab({ agent }: { agent: Agent }) {<div className="space-y-4"><p className="text-caption text-muted-foreground">{t(($) => $.tab_body.connected_apps.subtitle)}</p>+ {overview.data && overview.data.catalog_mode !== "all" && (+ <SavedAppRestriction kind="catalog" onRestore={canManageTeam+ ? () => restore.mutateAsync({ catalog: true }) : undefined} />+ )}+{hasTeamApp && agent.permission_mode !== "private" && (<divrole="alert"@@ -162,25 +162,6 @@ export function AgentAppsTab({ agent }: { agent: Agent }) {))}</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><Buttonvariant="ghost"size="icon-sm"@@ -190,6 +171,20 @@ export function AgentAppsTab({ agent }: { agent: Agent }) {><X /></Button>+ {app.level === "read" && (+ <div className="w-full">+ <SavedAppRestriction kind="agent" onRestore={lockedTeam ? undefined : () => update.mutateAsync({+ apps: apps.map((a) => ({+ toolkit_slug: a.toolkit_slug,+ account_scope: a.account_scope,+ level: a.toolkit_slug === app.toolkit_slug ? "write" : a.level,+ })),+ })} />+ </div>+ )}+ {(overview.data?.[app.account_scope]?.some((c) => c.toolkit_slug === app.toolkit_slug && c.actions_blocked === true)) && (+ <p className="w-full text-caption text-warning">{ts(($) => $.connected_apps.saved_access.account_link)}</p>+ )}</li>);})}diff --git a/packages/views/common/saved-app-restriction.tsx b/packages/views/common/saved-app-restriction.tsxnew file mode 100644index 0000000000..38bace61c9--- /dev/null+++ b/packages/views/common/saved-app-restriction.tsx@@ -0,0 +1,62 @@+"use client";++import { useState } from "react";+import { toast } from "sonner";+import { Button } from "@multica/ui/components/ui/button";+import {+ AlertDialog, AlertDialogCancel, AlertDialogContent, AlertDialogDescription,+ AlertDialogFooter, AlertDialogHeader, AlertDialogTitle,+} from "@multica/ui/components/ui/alert-dialog";+import { useT } from "../i18n";++/** A one-time recovery action, shown only while saved restrictions apply. */+export function SavedAppRestriction({ kind, onRestore }: {+ kind: "account" | "agent" | "catalog";+ onRestore?: () => Promise<unknown>;+}) {+ const { t } = useT("settings");+ const [open, setOpen] = useState(false);+ const [pending, setPending] = useState(false);+ const action = kind === "catalog"+ ? t(($) => $.connected_apps.saved_access.open_catalog)+ : t(($) => $.connected_apps.saved_access.allow_actions);++ return (+ <div className="flex flex-wrap items-center gap-3 rounded-md border border-warning/40 bg-warning/10 px-3 py-2 text-caption">+ <p className="min-w-0 flex-1">{t(($) => $.connected_apps.saved_access[kind])}</p>+ {onRestore ? (+ <>+ <Button variant="outline" size="sm" onClick={() => setOpen(true)}>{action}</Button>+ <AlertDialog open={open} onOpenChange={(value) => !pending && setOpen(value)}>+ <AlertDialogContent>+ <AlertDialogHeader>+ <AlertDialogTitle>{action}</AlertDialogTitle>+ <AlertDialogDescription>+ {kind === "catalog"+ ? t(($) => $.connected_apps.saved_access.catalog_confirm)+ : kind === "agent"+ ? t(($) => $.connected_apps.saved_access.agent_confirm)+ : t(($) => $.connected_apps.saved_access.account_confirm)}+ </AlertDialogDescription>+ </AlertDialogHeader>+ <AlertDialogFooter>+ <AlertDialogCancel disabled={pending}>{t(($) => $.connected_apps.saved_access.cancel)}</AlertDialogCancel>+ <Button disabled={pending} aria-busy={pending} onClick={async () => {+ setPending(true);+ try {+ await onRestore();+ setOpen(false);+ } catch {+ toast.error(t(($) => $.connected_apps.toast_failed));+ } finally {+ setPending(false);+ }+ }}>{action}</Button>+ </AlertDialogFooter>+ </AlertDialogContent>+ </AlertDialog>+ </>+ ) : <span className="text-muted-foreground">{t(($) => $.connected_apps.saved_access.admin_required)}</span>}+ </div>+ );+}diff --git a/packages/views/locales/en/agents.json b/packages/views/locales/en/agents.jsonindex 8ff074d1d2..ff29e358a7 100644--- a/packages/views/locales/en/agents.json+++ b/packages/views/locales/en/agents.json@@ -838,7 +838,7 @@"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.",+ "subtitle": "Apps this agent can use, through the team account or the account of whoever triggers the run.","loading": "Loading apps…","load_failed": "Couldn't load this agent's apps.","empty": "No apps yet.",diff --git a/packages/views/locales/en/settings.json b/packages/views/locales/en/settings.jsonindex 3b9c4c34f2..61865196b9 100644--- a/packages/views/locales/en/settings.json+++ b/packages/views/locales/en/settings.json@@ -1449,11 +1449,11 @@"title": "Ways to give agents tools","current": "This page","mcp": "Added by admins and shared across the workspace, then assigned per agent.",- "apps": "Team or personal accounts connected through Multica, given to each agent with an account and a permission level.",+ "apps": "Team or personal accounts connected through Multica and added to each agent.","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.",+ "description": "Accounts your agents use to access external apps. Allowed actions run immediately.","add_app": "Add app","loading": "Loading apps…","load_failed": "Couldn't load apps.",@@ -1623,6 +1623,19 @@"row_label": "Allowed apps","row_description_one": "{{count}} app allowed","row_description_other": "{{count}} apps allowed"+ },+ "saved_access": {+ "account": "Saved action restrictions are still blocking this account.",+ "agent": "This app still has read-only access from an earlier setup.",+ "catalog": "A saved app list is hiding other apps.",+ "allow_actions": "Allow all actions",+ "open_catalog": "Show all apps",+ "account_confirm": "Agents assigned this account will be able to read, write, send, delete, and share through it. Saved action restrictions will be replaced.",+ "agent_confirm": "This agent will be able to read, write, send, delete, and share through this app, within the account’s allowed actions.",+ "catalog_confirm": "All connectable apps will be available to the workspace. Existing connections and agent assignments will stay as they are.",+ "cancel": "Cancel",+ "admin_required": "A workspace admin can restore access.",+ "account_link": "This account has saved action restrictions. Restore access in Connected apps."}}}diff --git a/packages/views/locales/es/agents.json b/packages/views/locales/es/agents.jsonindex 4eac1bd4ba..4a95eb10d5 100644--- a/packages/views/locales/es/agents.json+++ b/packages/views/locales/es/agents.json@@ -820,7 +820,7 @@"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.",+ "subtitle": "Aplicaciones que puede usar este agente con la cuenta del equipo o la de quien inicia la ejecución.","loading": "Cargando aplicaciones…","load_failed": "No se pudieron cargar las aplicaciones de este agente.","empty": "Aún no hay aplicaciones.",diff --git a/packages/views/locales/es/settings.json b/packages/views/locales/es/settings.jsonindex cc19675d05..4a6cfe5d50 100644--- a/packages/views/locales/es/settings.json+++ b/packages/views/locales/es/settings.json@@ -1418,7 +1418,7 @@}},"mcp_sources": {- "apps": "Cuentas del equipo o personales conectadas mediante Multica, asignadas a cada agente con una cuenta y un nivel de permisos.",+ "apps": "Cuentas del equipo o personales conectadas a través de Multica y añadidas a cada agente.","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.",@@ -1453,7 +1453,7 @@"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.",+ "description": "Cuentas que usan tus agentes para acceder a aplicaciones externas. Las acciones permitidas se ejecutan de inmediato.","add_app": "Añadir aplicación","loading": "Cargando aplicaciones…","load_failed": "No se pudieron cargar las aplicaciones.",@@ -1623,6 +1623,19 @@"row_label": "Aplicaciones permitidas","row_description_one": "{{count}} aplicación permitida","row_description_other": "{{count}} aplicaciones permitidas"+ },+ "saved_access": {+ "account": "Las restricciones guardadas aún bloquean algunas acciones de esta cuenta.",+ "agent": "Esta app conserva un acceso anterior de solo lectura.",+ "catalog": "Una lista guardada oculta otras apps.",+ "allow_actions": "Permitir todas las acciones",+ "open_catalog": "Mostrar todas las apps",+ "account_confirm": "Los agentes que usen esta cuenta podrán leer, escribir, enviar, eliminar y compartir. Se reemplazarán las restricciones guardadas.",+ "agent_confirm": "Este agente podrá leer, escribir, enviar, eliminar y compartir mediante esta app, dentro de los límites de la cuenta.",+ "catalog_confirm": "Todas las apps conectables estarán disponibles en el espacio de trabajo. Se conservarán las conexiones y asignaciones existentes.",+ "cancel": "Cancelar",+ "admin_required": "Un administrador puede restablecer el acceso.",+ "account_link": "Esta cuenta conserva restricciones. Restablece el acceso en Apps conectadas."}}}diff --git a/packages/views/locales/fr/agents.json b/packages/views/locales/fr/agents.jsonindex ebea18698f..0ae209e34e 100644--- a/packages/views/locales/fr/agents.json+++ b/packages/views/locales/fr/agents.json@@ -838,7 +838,7 @@"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.",+ "subtitle": "Les apps que cet agent peut utiliser avec le compte d'équipe ou celui de la personne qui lance l'exécution.","loading": "Chargement des apps…","load_failed": "Impossible de charger les apps de cet agent.","empty": "Aucune app pour l'instant.",diff --git a/packages/views/locales/fr/settings.json b/packages/views/locales/fr/settings.jsonindex efea9583dd..3a979b68d9 100644--- a/packages/views/locales/fr/settings.json+++ b/packages/views/locales/fr/settings.json@@ -1449,11 +1449,11 @@"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": "Comptes d'équipe ou personnels connectés via Multica, attribués à chaque agent avec un compte et un niveau de permission.",+ "apps": "Des comptes d'équipe ou personnels connectés via Multica et ajoutés à chaque agent.","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.",+ "description": "Les comptes que vos agents utilisent pour accéder aux apps externes. Les actions autorisées sont exécutées immédiatement.","add_app": "Ajouter une app","loading": "Chargement des apps…","load_failed": "Impossible de charger les apps.",@@ -1623,6 +1623,19 @@"row_label": "Apps autorisées","row_description_one": "{{count}} app autorisée","row_description_other": "{{count}} apps autorisées"+ },+ "saved_access": {+ "account": "Des restrictions enregistrées bloquent encore certaines actions de ce compte.",+ "agent": "Cette app conserve un ancien accès en lecture seule.",+ "catalog": "Une liste enregistrée masque les autres apps.",+ "allow_actions": "Autoriser toutes les actions",+ "open_catalog": "Afficher toutes les apps",+ "account_confirm": "Les agents utilisant ce compte pourront lire, écrire, envoyer, supprimer et partager. Les restrictions enregistrées seront remplacées.",+ "agent_confirm": "Cet agent pourra lire, écrire, envoyer, supprimer et partager via cette app, dans les limites du compte.",+ "catalog_confirm": "Toutes les apps connectables seront disponibles dans l’espace de travail. Les connexions et les attributions existantes seront conservées.",+ "cancel": "Annuler",+ "admin_required": "Un administrateur peut rétablir l’accès.",+ "account_link": "Ce compte conserve des restrictions. Rétablissez l’accès dans les apps connectées."}}}diff --git a/packages/views/locales/ja/agents.json b/packages/views/locales/ja/agents.jsonindex ab86aa8454..ba708f2bdc 100644--- a/packages/views/locales/ja/agents.json+++ b/packages/views/locales/ja/agents.json@@ -659,7 +659,7 @@"queued_prefix": "{{when}} に待機開始"},"connected_apps": {- "subtitle": "このエージェントが使えるアプリです。各アプリはチームアカウントか、実行を起動した人のアカウントとして、選んだレベルで動作します。",+ "subtitle": "このエージェントが使えるアプリです。チームアカウントか、実行を起動した人のアカウントとして動作します。","loading": "アプリを読み込み中…","load_failed": "このエージェントのアプリを読み込めませんでした。","empty": "アプリはまだありません。",diff --git a/packages/views/locales/ja/settings.json b/packages/views/locales/ja/settings.jsonindex 9ef3c9a692..9aab6e2b16 100644--- a/packages/views/locales/ja/settings.json+++ b/packages/views/locales/ja/settings.json@@ -1438,11 +1438,11 @@"title": "エージェントにツールを与える方法","current": "このページ","mcp": "管理者が追加してワークスペースで共有し、エージェントごとに割り当てます。",- "apps": "Multica で接続したチームまたは個人のアカウント。エージェントごとにアカウントと権限レベルを割り当てます。",+ "apps": "Multica で接続したチームまたは個人のアカウントを、各エージェントに追加します。","plugins": "インストールするとツール、定期フック、ストレージを追加でき、プラグインごとに権限を付与します。"},"connected_apps": {- "description": "エージェントが外部アプリを操作するアカウントです。すべての呼び出しは Multica を経由し、ルールを適用し、送信・削除・共有の前に確認を求めます。",+ "description": "エージェントが外部アプリを操作するアカウントです。許可された操作はすぐに実行されます。","add_app": "アプリを追加","loading": "アプリを読み込み中…","load_failed": "アプリを読み込めませんでした。",@@ -1607,6 +1607,19 @@"edit": "リストを編集","row_label": "許可するアプリ","row_description_other": "{{count}} 個のアプリを許可"+ },+ "saved_access": {+ "account": "保存済みの操作制限が、このアカウントの一部の操作をブロックしています。",+ "agent": "このアプリには以前の読み取り専用設定が残っています。",+ "catalog": "保存済みのアプリ一覧により、他のアプリが非表示になっています。",+ "allow_actions": "すべての操作を許可",+ "open_catalog": "すべてのアプリを表示",+ "account_confirm": "このアカウントを割り当てられたエージェントは、読み取り、書き込み、送信、削除、共有を行えるようになります。保存済みの操作制限は置き換えられます。",+ "agent_confirm": "このエージェントは、アカウントで許可された範囲で、このアプリの読み取り、書き込み、送信、削除、共有を行えるようになります。",+ "catalog_confirm": "ワークスペースですべての接続可能なアプリを選べるようになります。既存の接続とエージェントへの割り当ては変わりません。",+ "cancel": "キャンセル",+ "admin_required": "ワークスペース管理者が制限を解除できます。",+ "account_link": "このアカウントには保存済みの操作制限があります。接続済みアプリで解除してください。"}}}diff --git a/packages/views/locales/ko/agents.json b/packages/views/locales/ko/agents.jsonindex 4f5feda8d7..37c6ae1415 100644--- a/packages/views/locales/ko/agents.json+++ b/packages/views/locales/ko/agents.json@@ -667,7 +667,7 @@"queued_prefix": "{{when}} 대기 시작"},"connected_apps": {- "subtitle": "이 에이전트가 사용할 수 있는 앱입니다. 각 앱은 팀 계정 또는 실행한 사람의 계정으로, 선택한 수준에서 동작합니다.",+ "subtitle": "이 에이전트가 사용할 수 있는 앱입니다. 팀 계정 또는 실행한 사람의 계정으로 동작합니다.","loading": "앱을 불러오는 중…","load_failed": "이 에이전트의 앱을 불러오지 못했습니다.","empty": "아직 앱이 없습니다.",diff --git a/packages/views/locales/ko/settings.json b/packages/views/locales/ko/settings.jsonindex e8e7ae7b1f..83f4626e79 100644--- a/packages/views/locales/ko/settings.json+++ b/packages/views/locales/ko/settings.json@@ -1438,11 +1438,11 @@"title": "에이전트에 도구를 제공하는 방법","current": "현재 페이지","mcp": "관리자가 추가해 워크스페이스에서 공유하고, 에이전트별로 할당합니다.",- "apps": "Multica로 연결한 팀 또는 개인 계정으로, 에이전트마다 계정과 권한 수준을 지정합니다.",+ "apps": "Multica로 연결한 팀 또는 개인 계정을 각 에이전트에 추가합니다.","plugins": "설치하면 도구, 예약 훅, 저장소를 추가할 수 있으며 플러그인마다 권한을 부여합니다."},"connected_apps": {- "description": "에이전트가 외부 앱을 사용할 때 쓰는 계정입니다. 모든 호출은 Multica를 거치며, 규칙을 적용하고 보내기·삭제·공유 전에 확인을 받습니다.",+ "description": "에이전트가 외부 앱을 사용할 때 쓰는 계정입니다. 허용된 작업은 즉시 실행됩니다.","add_app": "앱 추가","loading": "앱을 불러오는 중…","load_failed": "앱을 불러오지 못했습니다.",@@ -1607,6 +1607,19 @@"edit": "목록 편집","row_label": "허용된 앱","row_description_other": "앱 {{count}}개 허용"+ },+ "saved_access": {+ "account": "저장된 작업 제한이 이 계정의 일부 작업을 차단하고 있습니다.",+ "agent": "이 앱에 이전 읽기 전용 설정이 남아 있습니다.",+ "catalog": "저장된 앱 목록이 다른 앱을 숨기고 있습니다.",+ "allow_actions": "모든 작업 허용",+ "open_catalog": "모든 앱 표시",+ "account_confirm": "이 계정이 할당된 에이전트는 읽기, 쓰기, 전송, 삭제, 공유를 할 수 있게 됩니다. 저장된 작업 제한이 대체됩니다.",+ "agent_confirm": "이 에이전트는 계정에서 허용한 범위 내에서 이 앱의 읽기, 쓰기, 전송, 삭제, 공유를 할 수 있게 됩니다.",+ "catalog_confirm": "워크스페이스에서 연결 가능한 모든 앱을 선택할 수 있게 됩니다. 기존 연결과 에이전트 앱 할당은 유지됩니다.",+ "cancel": "취소",+ "admin_required": "워크스페이스 관리자가 제한을 해제할 수 있습니다.",+ "account_link": "이 계정에 저장된 작업 제한이 있습니다. 연결된 앱에서 해제하세요."}}}diff --git a/packages/views/locales/ru/agents.json b/packages/views/locales/ru/agents.jsonindex f482c38e45..a6a88afc0c 100644--- a/packages/views/locales/ru/agents.json+++ b/packages/views/locales/ru/agents.json@@ -880,7 +880,7 @@"runs_many": "запусков"},"connected_apps": {- "subtitle": "Приложения, доступные этому агенту. Каждое использует аккаунт команды или того, кто запустил выполнение, с выбранным уровнем доступа.",+ "subtitle": "Приложения, доступные этому агенту через аккаунт команды или того, кто запустил выполнение.","loading": "Загрузка приложений…","load_failed": "Не удалось загрузить приложения этого агента.","empty": "Приложений пока нет.",diff --git a/packages/views/locales/ru/settings.json b/packages/views/locales/ru/settings.jsonindex 27229c61b4..e4788dcda4 100644--- a/packages/views/locales/ru/settings.json+++ b/packages/views/locales/ru/settings.json@@ -1470,11 +1470,11 @@"title": "Способы дать агентам инструменты","current": "Эта страница","mcp": "Добавляются администраторами и доступны всему рабочему пространству, затем назначаются отдельным агентам.",- "apps": "Аккаунты команды или личные аккаунты, подключённые через Multica. Для каждого агента выбираются аккаунт и уровень доступа.",+ "apps": "Аккаунты команды или личные аккаунты, подключённые через Multica и добавленные каждому агенту.","plugins": "Установленные пакеты, которые могут добавлять инструменты, запланированные хуки и хранилище, каждый со своими правами доступа."},"connected_apps": {- "description": "Аккаунты, через которые действуют ваши агенты. Каждый вызов проходит через Multica, которая применяет ваши правила и запрашивает подтверждение перед отправкой, удалением или предоставлением доступа.",+ "description": "Аккаунты, через которые ваши агенты работают с внешними приложениями. Разрешённые действия выполняются сразу.","add_app": "Добавить приложение","loading": "Загрузка приложений…","load_failed": "Не удалось загрузить приложения.",@@ -1654,6 +1654,19 @@"row_description_few": "Разрешено {{count}} приложения","row_description_many": "Разрешено {{count}} приложений","row_description_other": "Разрешено {{count}} приложения"+ },+ "saved_access": {+ "account": "Сохранённые ограничения всё ещё блокируют некоторые действия этого аккаунта.",+ "agent": "Для этого приложения сохранился прежний доступ только для чтения.",+ "catalog": "Сохранённый список скрывает другие приложения.",+ "allow_actions": "Разрешить все действия",+ "open_catalog": "Показать все приложения",+ "account_confirm": "Агенты с этим аккаунтом смогут читать, записывать, отправлять, удалять и делиться. Сохранённые ограничения будут заменены.",+ "agent_confirm": "Этот агент сможет читать, записывать, отправлять, удалять и делиться через приложение в пределах разрешений аккаунта.",+ "catalog_confirm": "Все подключаемые приложения станут доступны в рабочем пространстве. Существующие подключения и назначения агентам сохранятся.",+ "cancel": "Отмена",+ "admin_required": "Администратор может восстановить доступ.",+ "account_link": "У этого аккаунта сохранились ограничения. Восстановите доступ в подключённых приложениях."}}}diff --git a/packages/views/locales/zh-Hans/agents.json b/packages/views/locales/zh-Hans/agents.jsonindex d6711687df..7559947141 100644--- a/packages/views/locales/zh-Hans/agents.json+++ b/packages/views/locales/zh-Hans/agents.json@@ -817,7 +817,7 @@"queued_prefix": "{{when}}排队"},"connected_apps": {- "subtitle": "这个智能体可以使用的应用。每个应用以团队账号或触发者的账号身份操作,权限级别由你设定。",+ "subtitle": "这个智能体可以使用的应用,以团队账号或发起运行的成员账号操作。","loading": "正在加载应用…","load_failed": "无法加载此智能体的应用。","empty": "还没有应用。",diff --git a/packages/views/locales/zh-Hans/settings.json b/packages/views/locales/zh-Hans/settings.jsonindex a3a3cec568..9f7af4655e 100644--- a/packages/views/locales/zh-Hans/settings.json+++ b/packages/views/locales/zh-Hans/settings.json@@ -1438,11 +1438,11 @@"title": "为智能体接入工具的方式","current": "当前页面","mcp": "由管理员添加、在工作区内共享,再按智能体分配。",- "apps": "通过 Multica 连接的团队或个人账号,按智能体分配账号和权限级别。",+ "apps": "通过 Multica 连接团队或个人账号,再将应用添加到智能体。","plugins": "安装后可提供工具、定时 hook 和存储,每个插件单独授权。"},"connected_apps": {- "description": "智能体通过这些账号操作外部应用。每次调用都经过 Multica:按规则执行,发送、删除、分享前先征得同意。",+ "description": "智能体通过这些账号操作外部应用,允许的操作会直接执行。","add_app": "添加应用","loading": "正在加载应用…","load_failed": "无法加载应用。",@@ -1607,6 +1607,19 @@"edit": "编辑名单","row_label": "允许的应用","row_description_other": "已允许 {{count}} 个应用"+ },+ "saved_access": {+ "account": "旧操作限制仍在阻止此账号的部分操作。",+ "agent": "此应用仍受旧的只读授权限制。",+ "catalog": "旧应用名单仍在隐藏其他应用。",+ "allow_actions": "允许全部操作",+ "open_catalog": "显示全部应用",+ "account_confirm": "使用此账号的智能体将能读取、写入、发送、删除和共享内容。旧操作限制将被替换。",+ "agent_confirm": "此智能体将能通过此应用读取、写入、发送、删除和共享内容,仍受账号本身的限制。",+ "catalog_confirm": "工作区将能选择所有可连接的应用。现有连接和智能体的应用分配保持不变。",+ "cancel": "取消",+ "admin_required": "请工作区管理员解除限制。",+ "account_link": "此账号仍有旧操作限制。请在已连接应用中解除。"}}}diff --git a/packages/views/locales/zh-Hant/agents.json b/packages/views/locales/zh-Hant/agents.jsonindex 036cb2bead..ad117c4a17 100644--- a/packages/views/locales/zh-Hant/agents.json+++ b/packages/views/locales/zh-Hant/agents.json@@ -817,7 +817,7 @@"queued_prefix": "{{when}}排隊"},"connected_apps": {- "subtitle": "這個 AI 代理可以使用的應用。每個應用以團隊帳號或觸發者的帳號身分操作,權限等級由你設定。",+ "subtitle": "這個 AI 代理可以使用的應用,以團隊帳號或發起執行的成員帳號操作。","loading": "正在載入應用…","load_failed": "無法載入此 AI 代理的應用。","empty": "還沒有應用。",diff --git a/packages/views/locales/zh-Hant/settings.json b/packages/views/locales/zh-Hant/settings.jsonindex 472d630310..02b90de821 100644--- a/packages/views/locales/zh-Hant/settings.json+++ b/packages/views/locales/zh-Hant/settings.json@@ -1438,11 +1438,11 @@"title": "為 AI 代理接入工具的方式","current": "當前頁面","mcp": "由管理員新增、在工作區內共享,再按 AI 代理分配。",- "apps": "透過 Multica 連線的團隊或個人帳號,依 AI 代理分配帳號和權限等級。",+ "apps": "透過 Multica 連線團隊或個人帳號,再將應用新增至 AI 代理。","plugins": "安裝後可提供工具、定時 hook 和儲存,每個外掛單獨授權。"},"connected_apps": {- "description": "AI 代理透過這些帳號操作外部應用。每次呼叫都經過 Multica:依規則執行,傳送、刪除、分享前先徵得同意。",+ "description": "AI 代理透過這些帳號操作外部應用,允許的操作會直接執行。","add_app": "新增應用","loading": "正在載入應用…","load_failed": "無法載入應用。",@@ -1607,6 +1607,19 @@"edit": "編輯名單","row_label": "允許的應用","row_description_other": "已允許 {{count}} 個應用"+ },+ "saved_access": {+ "account": "舊操作限制仍在阻擋此帳號的部分操作。",+ "agent": "此應用仍受舊的唯讀授權限制。",+ "catalog": "舊應用清單仍在隱藏其他應用。",+ "allow_actions": "允許全部操作",+ "open_catalog": "顯示全部應用",+ "account_confirm": "使用此帳號的 AI 代理將能讀取、寫入、傳送、刪除和共享內容。舊操作限制將被取代。",+ "agent_confirm": "此 AI 代理將能透過此應用讀取、寫入、傳送、刪除和共享內容,仍受帳號本身的限制。",+ "catalog_confirm": "工作區將能選擇所有可連接的應用。現有連線和 AI 代理的應用指派維持不變。",+ "cancel": "取消",+ "admin_required": "請工作區管理員解除限制。",+ "account_link": "此帳號仍有舊操作限制。請在已連接應用中解除。"}}}diff --git a/packages/views/settings/components/app-account-dialog.test.tsx b/packages/views/settings/components/app-account-dialog.test.tsxnew file mode 100644index 0000000000..2a9dbb5f2e--- /dev/null+++ b/packages/views/settings/components/app-account-dialog.test.tsx@@ -0,0 +1,42 @@+import { afterEach, expect, it, vi } from "vitest";+import { cleanup, render, screen } from "@testing-library/react";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { api } from "@multica/core/api";+import { I18nProvider } from "@multica/core/i18n/react";+import enCommon from "../../locales/en/common.json";+import enSettings from "../../locales/en/settings.json";+import { AppAccountDialog } from "./app-account-dialog";++vi.mock("@multica/core/api", () => ({ api: {+ getAppRules: vi.fn(), listAppTools: vi.fn(), listAppActivity: vi.fn(),+} }));+vi.mock("@multica/core/hooks", () => ({ useWorkspaceId: () => "ws-1" }));++afterEach(() => {+ cleanup();+ vi.clearAllMocks();+});++it("opens account activity directly without fetching or showing permission settings", async () => {+ vi.mocked(api.getAppRules).mockResolvedValue({ rules: [] });+ vi.mocked(api.listAppTools).mockResolvedValue({ tools: [] });+ vi.mocked(api.listAppActivity).mockResolvedValue({ calls: [{+ id: "call-1", agent_id: "a1", issue_id: null, chat_session_id: null, triggered_by: null,+ tool_slug: "GMAIL_SEND_EMAIL", action_class: "send", outcome: "ok", error: null,+ created_at: "2026-11-09T10:00:00Z",+ }] });+ const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });+ render(+ <QueryClientProvider client={client}>+ <I18nProvider locale="en" resources={{ en: { common: enCommon, settings: enSettings } }}>+ <AppAccountDialog scope="personal" slug="gmail" name="Gmail" onClose={vi.fn()} />+ </I18nProvider>+ </QueryClientProvider>,+ );+ expect(await screen.findByText("GMAIL_SEND_EMAIL")).toBeVisible();+ expect(api.listAppActivity).toHaveBeenCalledWith("gmail", "personal");+ expect(api.getAppRules).not.toHaveBeenCalled();+ expect(api.listAppTools).not.toHaveBeenCalled();+ expect(screen.queryByRole("tab")).not.toBeInTheDocument();+ expect(screen.queryByRole("combobox")).not.toBeInTheDocument();+});diff --git a/packages/views/settings/components/app-account-dialog.tsx b/packages/views/settings/components/app-account-dialog.tsxindex aef84161f1..21a6165706 100644--- a/packages/views/settings/components/app-account-dialog.tsx+++ b/packages/views/settings/components/app-account-dialog.tsx@@ -1,61 +1,27 @@"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 { appActivityOptions } from "@multica/core/connected-apps";+import type { AppAccountScope } 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. */+/** Recent calls through one connected account. */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");@@ -69,193 +35,12 @@ export function AppAccountDialog({: 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>+ <ActivityList scope={scope} slug={slug} /></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();diff --git a/packages/views/settings/components/apps-settings.test.tsx b/packages/views/settings/components/apps-settings.test.tsxnew file mode 100644index 0000000000..2cbf4d7f02--- /dev/null+++ b/packages/views/settings/components/apps-settings.test.tsx@@ -0,0 +1,80 @@+import { afterEach, beforeEach, expect, it, vi } from "vitest";+import { cleanup, render, screen, waitFor, within } from "@testing-library/react";+import userEvent from "@testing-library/user-event";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { api } from "@multica/core/api";+import { I18nProvider } from "@multica/core/i18n/react";+import type { AppsOverview } from "@multica/core/types";+import enCommon from "../../locales/en/common.json";+import enSettings from "../../locales/en/settings.json";+import { AppsSettings } from "./apps-settings";++vi.mock("@multica/core/api", () => ({ api: {+ getAppsOverview: vi.fn(), listAppCatalog: vi.fn(), updateAppSettings: vi.fn(), updateAppRules: vi.fn(),+} }));+vi.mock("@multica/core/hooks", () => ({ useWorkspaceId: () => "ws-1" }));+vi.mock("@multica/core/workspace/hooks", () => ({ useActorName: () => ({ getActorName: () => "Admin" }) }));+vi.mock("../../navigation", () => ({ useNavigation: () => ({ searchParams: new URLSearchParams() }) }));++let overview: AppsOverview;+beforeEach(() => {+ overview = {+ catalog_mode: "custom", allowed_toolkits: [], can_manage: true, agent_apps: [],+ team: [{ id: "team-1", toolkit_slug: "gmail", status: "active", connected_at: "", last_used_at: null, actions_blocked: true }],+ personal: [{ id: "personal-1", toolkit_slug: "gmail", status: "active", connected_at: "", last_used_at: null, actions_blocked: true }],+ };+ vi.mocked(api.getAppsOverview).mockImplementation(async () => overview);+ vi.mocked(api.listAppCatalog).mockResolvedValue({ catalog_mode: "custom", apps: [] });+ vi.mocked(api.updateAppSettings).mockImplementation(async () => {+ overview = { ...overview, catalog_mode: "all" };+ return { catalog_mode: "all", allowed_toolkits: [] };+ });+ vi.mocked(api.updateAppRules).mockImplementation(async (_slug, scope) => {+ overview = { ...overview, [scope]: overview[scope].map((c) => ({ ...c, actions_blocked: false })) };+ return { rules: [] };+ });+});+afterEach(() => { cleanup(); vi.clearAllMocks(); });++function renderSettings() {+ const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });+ render(<QueryClientProvider client={client}>+ <I18nProvider locale="en" resources={{ en: { common: enCommon, settings: enSettings } }}>+ <AppsSettings />+ </I18nProvider>+ </QueryClientProvider>);+}++it("recovers an empty saved catalog only after the admin confirms", async () => {+ const user = userEvent.setup();+ renderSettings();+ await user.click(await screen.findByRole("button", { name: "Show all apps" }));+ expect(api.updateAppSettings).not.toHaveBeenCalled();+ await user.click(within(screen.getByRole("alertdialog")).getByRole("button", { name: "Show all apps" }));+ await waitFor(() => expect(api.updateAppSettings).toHaveBeenCalledWith({ catalog_mode: "all", allowed_toolkits: [] }));+ await waitFor(() => expect(screen.queryByText("A saved app list is hiding other apps.")).not.toBeInTheDocument());+});++it("lets a member recover only their personal account and keeps failed confirmation open", async () => {+ overview.can_manage = false;+ vi.mocked(api.updateAppRules).mockRejectedValueOnce(new Error("offline"));+ const user = userEvent.setup();+ renderSettings();+ await screen.findByText("A saved app list is hiding other apps.");+ expect(screen.queryByRole("button", { name: "Show all apps" })).not.toBeInTheDocument();+ expect(screen.getAllByRole("button", { name: "Allow all actions" })).toHaveLength(1);+ await user.click(screen.getByRole("button", { name: "Allow all actions" }));+ expect(api.updateAppRules).not.toHaveBeenCalled();+ const confirm = within(screen.getByRole("alertdialog")).getByRole("button", { name: "Allow all actions" });+ await user.click(confirm);+ await waitFor(() => expect(confirm).toBeEnabled());+ expect(screen.getByRole("alertdialog")).toBeVisible();+ await user.click(confirm);+ await waitFor(() => expect(api.updateAppRules).toHaveBeenLastCalledWith("gmail", "personal", [+ { action_class: "read", policy: "allow" }, { action_class: "write", policy: "allow" },+ { action_class: "send", policy: "allow" }, { action_class: "delete", policy: "allow" },+ { action_class: "share", policy: "allow" },+ ]));+ await waitFor(() => expect(screen.queryByRole("alertdialog")).not.toBeInTheDocument());+ expect(screen.getAllByText("Saved action restrictions are still blocking this account.")).toHaveLength(1);+});diff --git a/packages/views/settings/components/apps-settings.tsx b/packages/views/settings/components/apps-settings.tsxindex 4e0e277977..90ec78fd43 100644--- a/packages/views/settings/components/apps-settings.tsx+++ b/packages/views/settings/components/apps-settings.tsx@@ -15,13 +15,6 @@ import {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 {@@ -30,30 +23,26 @@ import {connectedAppsKeys,teamAppImpactOptions,useDisconnectTeamApp,- useUpdateAppSettings,+ useRestoreAppAccess,} 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 { SavedAppRestriction } from "../../common/saved-app-restriction";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";+import { SettingsCard, 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.- */+/** Connected team and personal accounts, with activity and disconnect actions.+ * Which agents use each account is set on the agent. */export function AppsSettings() {const { t } = useT("settings");const wsId = useWorkspaceId();@@ -61,12 +50,11 @@ export function AppsSettings() {const navigation = useNavigation();const overview = useQuery(appsOverviewOptions(wsId));const catalog = useQuery(appCatalogOptions(wsId));- const updateSettings = useUpdateAppSettings();+ const restore = useRestoreAppAccess();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@@ -119,14 +107,6 @@ export function AppsSettings() {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")@@ -155,6 +135,13 @@ export function AppsSettings() {</Button></div>+ {data.catalog_mode !== "all" && (+ <SavedAppRestriction+ kind="catalog"+ onRestore={canManage ? () => restore.mutateAsync({ catalog: true }) : undefined}+ />+ )}+<SettingsSectionanchor="team-accounts"title={t(($) => $.connected_apps.team_title)}@@ -185,55 +172,6 @@ export function AppsSettings() {)}</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>-<AddAppDialogopen={adding}onOpenChange={setAdding}@@ -248,14 +186,9 @@ export function AppsSettings() {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)} />)}@@ -294,6 +227,7 @@ function AccountRow({const { t } = useT("settings");const timeAgo = useTimeAgo();const { getActorName } = useActorName();+ const restore = useRestoreAppAccess();const name = app?.name || connection.toolkit_slug;const expired = connection.status === "expired";const meta = [@@ -307,33 +241,44 @@ function AccountRow({].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>+ <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>+ {canManage && (+ <>+ <Button variant="ghost" size="sm" onClick={onOpen}>+ {t(($) => $.connected_apps.activity)}+ </Button>+ <Button+ variant="ghost"+ size="icon-sm"+ aria-label={t(($) => $.connected_apps.disconnect)}+ onClick={onDisconnect}+ >+ <Trash2 />+ </Button>+ </>+ )}</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>+ {connection.actions_blocked === true && (+ <div className="px-4 pb-3">+ <SavedAppRestriction kind="account" onRestore={canManage+ ? () => restore.mutateAsync({ slug: connection.toolkit_slug, scope })+ : undefined} />+ </div>)}</div>);diff --git a/packages/views/settings/components/custom-catalog-dialog.tsx b/packages/views/settings/components/custom-catalog-dialog.tsxdeleted file mode 100644index 53438f2087..0000000000--- a/packages/views/settings/components/custom-catalog-dialog.tsx+++ /dev/null@@ -1,129 +0,0 @@-"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/server/internal/connectedapps/catalog.go b/server/internal/connectedapps/catalog.goindex 44af167d04..e6030d1bf2 100644--- a/server/internal/connectedapps/catalog.go+++ b/server/internal/connectedapps/catalog.go@@ -1,6 +1,5 @@// 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.+// account a run acts as and what each tool call is allowed to do.//// Agents never see a provider credential. A run reaches its apps through the// Multica MCP gateway, which resolves the account, classifies the tool, applies@@ -37,8 +36,6 @@ 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}@@ -68,11 +65,7 @@ var curatedApps = []CuratedApp{{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: "stripe", Scope: ScopeTeam},{Slug: "airtable", Scope: ScopeTeam},}@@ -109,14 +102,9 @@ 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+// DefaultLevel lets newly attached apps run directly for every agent.+func DefaultLevel(_ string) string {+ return LevelWrite}// ValidLevel reports whether level is an agent permission level.diff --git a/server/internal/connectedapps/classify.go b/server/internal/connectedapps/classify.goindex 0440226329..d704041cc1 100644--- a/server/internal/connectedapps/classify.go+++ b/server/internal/connectedapps/classify.go@@ -79,7 +79,7 @@ var sendObjects = map[string]bool{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.+// reaches those people, so it is classified as 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,@@ -103,8 +103,7 @@ var deleteArgs = map[string]bool{// 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.+// nothing recognizes is "send", so account rules for outward actions apply.func Classify(toolkitSlug, toolSlug string, tags []string) string {upper := strings.ToUpper(strings.TrimSpace(toolSlug))if app, ok := Curated(toolkitSlug); ok {diff --git a/server/internal/connectedapps/gateway.go b/server/internal/connectedapps/gateway.goindex f0ab489f6a..720be946ef 100644--- a/server/internal/connectedapps/gateway.go+++ b/server/internal/connectedapps/gateway.go@@ -140,6 +140,11 @@ func (s *Service) loadRun(ctx context.Context, taskID string) (*run, error) {if err != nil {return nil, err}+ // A task can remain running on another member's runtime after its+ // initiator loses access. Recheck on every gateway request, not at enqueue.+ if !s.mayRun(ctx, task, agent) {+ return nil, ErrNoLongerAllowed+ }apps, err := s.q.ListAgentApps(ctx, agent.ID)if err != nil {return nil, err@@ -160,6 +165,18 @@ func (s *Service) loadRun(ctx context.Context, taskID string) (*run, error) {return rn, nil}+func (s *Service) mayRun(ctx context.Context, task db.AgentTaskQueue, agent db.Agent) bool {+ if agent.ArchivedAt.Valid || s.resumer == nil {+ return false+ }+ if task.OriginatorUserID.Valid {+ return s.mayUseAgent(ctx, agent.WorkspaceID, agent.ID, task.OriginatorUserID)+ }+ // Without a human originator, use the system invocation grant. The+ // accountable member is audit metadata and must never lend authority.+ return s.resumer.CanActFor(ctx, agent.WorkspaceID, agent.ID, pgtype.UUID{})+}+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"@@ -203,8 +220,8 @@ func (s *Service) dispatch(ctx context.Context, rn *run, req rpcRequest) (rpcRes}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."+ "Allowed calls run immediately and return their result. Never work around a blocked call. " ++ "If an account is not connected, use apps_request_connection and end your turn; you will be resumed after it is connected."func gatewayTools() []map[string]any {str := func(desc string) map[string]any { return map[string]any{"type": "string", "description": desc} }@@ -216,7 +233,7 @@ func gatewayTools() []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.",+ "description": "Search the tools of one app. Returns tool slugs, what they do, and whether a call is allowed or blocked.","inputSchema": map[string]any{"type": "object","properties": map[string]any{@@ -236,15 +253,14 @@ func gatewayTools() []map[string]any {},},{- "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.",+ "name": toolRunTool,+ "description": "Run an app tool immediately and return its 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."),+ "summary": str("Optional summary of what this call does and why."),},"required": []string{"tool", "arguments"},},@@ -318,13 +334,17 @@ func (s *Service) toolListApps(ctx context.Context, rn *run) map[string]any {}out := []appView{}for slug, app := range rn.apps {+ level := app.Level+ if level == LevelConfirmWrites {+ level = LevelWrite+ }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,+ Account: app.AccountScope, Level: level, Status: status,})}sort.Slice(out, func(i, j int) bool { return out[i].App < out[j].App })@@ -478,20 +498,11 @@ func (s *Service) toolRun(ctx context.Context, rn *run, toolSlug string, args ma}, 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)+ }+ // Tool lookup may involve a network call, and one gateway request may+ // contain a batch. Check again immediately before allowing execution.+ if !s.mayRun(ctx, rn.task, rn.agent) {+ return textResult("this run is no longer allowed to use this agent", true)}if s.overLimit(ctx, rn.workspaceID, slug, acct) {call.outcome = "rate_limited"diff --git a/server/internal/connectedapps/policy.go b/server/internal/connectedapps/policy.goindex 13fc6e9230..a87076d9b7 100644--- a/server/internal/connectedapps/policy.go+++ b/server/internal/connectedapps/policy.go@@ -12,14 +12,6 @@ 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:@@ -39,18 +31,13 @@ func Stricter(a, b string) string {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+// DefaultPolicy allows every supported action class unless an account rule+// or the agent's read-only level restricts it.+func DefaultPolicy(_ string, class string) string {+ if ValidClass(class) {+ return PolicyAllow}- return PolicyConfirm+ return PolicyBlock}// levelCap is the loosest policy an agent level permits for class.@@ -61,21 +48,25 @@ func levelCap(level, class string) string {switch level {case LevelRead:return PolicyBlock- case LevelWrite:+ case LevelWrite, LevelConfirmWrites:return PolicyAllowdefault:- return PolicyConfirm+ return PolicyBlock}}// 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.+// the account owner allows and never loosen it. Saved confirmation settings+// allow calls directly now that per-call approval has been removed.func Decide(toolkitSlug, level, class, rule string) string {account := ruleif !ValidPolicy(account) {account = DefaultPolicy(toolkitSlug, class)}+ if account == PolicyConfirm {+ account = PolicyAllow+ }return Stricter(account, levelCap(level, class))}diff --git a/server/internal/connectedapps/policy_test.go b/server/internal/connectedapps/policy_test.goindex a86694543c..b5aca20ad4 100644--- a/server/internal/connectedapps/policy_test.go+++ b/server/internal/connectedapps/policy_test.go@@ -45,24 +45,26 @@ func TestDecide(t *testing.T) {// 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", LevelWrite, ClassSend, "", PolicyAllow},+ {"notion", LevelWrite, ClassDelete, "", PolicyAllow},+ {"notion", LevelWrite, ClassShare, "", PolicyAllow},+ // Saved confirmation levels run directly.+ {"notion", LevelConfirmWrites, ClassWrite, "", PolicyAllow},{"notion", LevelConfirmWrites, ClassRead, "", PolicyAllow},// Read-only agents never write, whatever the rule says.{"notion", LevelRead, ClassWrite, PolicyAllow, PolicyBlock},+ {"notion", LevelRead, ClassWrite, PolicyConfirm, 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", LevelConfirmWrites, ClassSend, PolicyAllow, PolicyAllow},+ {"gmail", LevelConfirmWrites, ClassSend, PolicyBlock, PolicyBlock},{"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},+ // Curated apps share the same allow-by-default policy.+ {"stripe", LevelWrite, ClassWrite, "", PolicyAllow},+ {"stripe", LevelWrite, ClassWrite, PolicyConfirm, PolicyAllow},// An unknown rule value falls back to the default.- {"notion", LevelWrite, ClassShare, "bogus", PolicyBlock},+ {"notion", LevelWrite, ClassShare, "bogus", PolicyAllow},}for _, c := range cases {if got := Decide(c.toolkit, c.level, c.class, c.rule); got != c.want {@@ -97,12 +99,23 @@ func TestTaskToken(t *testing.T) {}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{"private", "public_to", ""} {+ if got := DefaultLevel(mode); got != LevelWrite {+ t.Fatalf("%q agent default = %q, want %q", mode, 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 TestDefaultPolicyAllowsEveryAction(t *testing.T) {+ for _, app := range append(CuratedSlugs(), "custom_app") {+ for _, class := range Classes {+ for _, level := range []string{LevelWrite, LevelConfirmWrites} {+ for _, rule := range []string{"", PolicyConfirm} {+ if got := Decide(app, level, class, rule); got != PolicyAllow {+ t.Errorf("Decide(%q, %q, %q, %q) = %q, want allow", app, level, class, rule, got)+ }+ }+ }}}}@@ -123,8 +136,8 @@ func TestClassifyOutwardWrites(t *testing.T) {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)+ if got := Decide("slack", LevelWrite, Classify("slack", "SLACK_SET_ADMIN_USER", nil), ""); got != PolicyAllow {+ t.Errorf("SLACK_SET_ADMIN_USER at write level = %s, want allow", got)}}diff --git a/server/internal/connectedapps/requests.go b/server/internal/connectedapps/requests.goindex 40c37304f7..63f81d4115 100644--- a/server/internal/connectedapps/requests.go+++ b/server/internal/connectedapps/requests.go@@ -14,7 +14,6 @@ import ("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")@@ -42,10 +41,6 @@ const (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 {@@ -315,12 +310,16 @@ func (s *Service) agentApp(ctx context.Context, agentID pgtype.UUID, slug string// 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 {+ return s.mayUseAgent(ctx, req.WorkspaceID, req.AgentID, req.ApproverUserID)+}++func (s *Service) mayUseAgent(ctx context.Context, workspaceID, agentID, userID pgtype.UUID) bool {if _, err := s.q.GetMemberByUserAndWorkspace(ctx, db.GetMemberByUserAndWorkspaceParams{- UserID: req.ApproverUserID, WorkspaceID: req.WorkspaceID,+ UserID: userID, WorkspaceID: workspaceID,}); err != nil {return false}- return s.resumer == nil || s.resumer.CanActFor(ctx, req.WorkspaceID, req.AgentID, req.ApproverUserID)+ return s.resumer == nil || s.resumer.CanActFor(ctx, workspaceID, agentID, userID)}func (s *Service) withdraw(ctx context.Context, req db.AppActionRequest) {diff --git a/server/internal/connectedapps/service.go b/server/internal/connectedapps/service.goindex 1de7691a8e..9461b5768b 100644--- a/server/internal/connectedapps/service.go+++ b/server/internal/connectedapps/service.go@@ -69,7 +69,8 @@ var (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.+ // workspace, by the same rule that admits a new run. An invalid userID+ // checks a system principal with no human originator.CanActFor(ctx context.Context, workspaceID, agentID, userID pgtype.UUID) bool}@@ -247,13 +248,17 @@ func (s *Service) BuildTaskOverlay(ctx context.Context, originatorUserID pgtype.} else if _, ok := personal[app.ToolkitSlug]; ok {status = "connected"}+ level := app.Level+ if level == LevelConfirmWrites {+ level = LevelWrite+ }meta = append(meta, runtimeapps.ConnectedApp{Provider: Provider,ServerName: GatewayServerName,ToolkitSlug: app.ToolkitSlug,ToolkitName: runtimeapps.DisplayNameForToolkitSlug(app.ToolkitSlug),AccountScope: app.AccountScope,- Level: app.Level,+ Level: level,AccountStatus: status,})}diff --git a/server/internal/daemon/execenv/runtime_config_sections.go b/server/internal/daemon/execenv/runtime_config_sections.goindex e1bca8d872..2170fcac33 100644--- a/server/internal/daemon/execenv/runtime_config_sections.go+++ b/server/internal/daemon/execenv/runtime_config_sections.go@@ -195,8 +195,8 @@ func BuildConnectedAppsBlock(apps []runtimeapps.ConnectedApp) string {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)+ "Allowed calls run immediately and return their result. Never work around a blocked call. "++ "For a `not connected` account, call `apps_request_connection` and end your turn.\n", gateway)}b.WriteString("\n")return b.String()@@ -215,9 +215,7 @@ func gatewayAppDetail(app runtimeapps.ConnectedApp) string {switch app.Level {case "read":parts = append(parts, "read only")- case "confirm_writes":- parts = append(parts, "writes need confirmation")- case "write":+ case "write", "confirm_writes":parts = append(parts, "can write")}if app.AccountStatus == "not_connected" {diff --git a/server/internal/daemon/execenv/runtime_config_test.go b/server/internal/daemon/execenv/runtime_config_test.goindex 70c8ca53cb..bcfc40efcc 100644--- a/server/internal/daemon/execenv/runtime_config_test.go+++ b/server/internal/daemon/execenv/runtime_config_test.go@@ -877,6 +877,24 @@ func TestConnectedAppsBlockLivesOutsideBrief(t *testing.T) {}}+func TestConnectedAppsBlockRunsDirectly(t *testing.T) {+ t.Parallel()+ for _, level := range []string{"write", "confirm_writes"} {+ block := BuildConnectedAppsBlock([]runtimeapps.ConnectedApp{{+ Provider: "multica", ServerName: "multica_apps", ToolkitSlug: "gmail",+ AccountScope: "personal", Level: level, AccountStatus: "not_connected",+ }})+ for _, want := range []string{"can write", "Allowed calls run immediately", "apps_request_connection", "not connected"} {+ if !strings.Contains(block, want) {+ t.Errorf("level %s: missing %q in %s", level, want, block)+ }+ }+ if strings.Contains(block, "confirmation") || strings.Contains(block, "submitted") {+ t.Errorf("level %s: retired approval instructions in %s", level, block)+ }+ }+}+func TestConnectedAppsHeadingSkippedWhenEmpty(t *testing.T) {t.Parallel()out := buildMetaSkillContent("claude", TaskContextForEnv{IssueID: "11111111-2222-3333-4444-555555555555"})diff --git a/server/internal/handler/connected_apps.go b/server/internal/handler/connected_apps.goindex 96318721b4..c73f9e1ec7 100644--- a/server/internal/handler/connected_apps.go+++ b/server/internal/handler/connected_apps.go@@ -27,12 +27,13 @@ import (// 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"`+ 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"`+ ActionsBlocked bool `json:"actions_blocked"`}// AgentAppResponse is one app attached to an agent.@@ -225,6 +226,26 @@ func (h *Handler) GetAppsOverview(w http.ResponseWriter, r *http.Request) {writeError(w, http.StatusInternalServerError, "failed to list agent apps")return}+ slugs := make([]string, 0, len(team)+len(personal))+ for _, row := range team {+ slugs = append(slugs, row.ToolkitSlug)+ }+ for _, row := range personal {+ slugs = append(slugs, row.ToolkitSlug)+ }+ rules, err := h.Queries.ListAppActionRulesForRun(ctx, db.ListAppActionRulesForRunParams{+ WorkspaceID: workspaceID, ToolkitSlugs: slugs, OwnerUserID: member.UserID,+ })+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to load account access")+ return+ }+ blocked := map[string]bool{}+ for _, rule := range rules {+ if rule.Policy == connectedapps.PolicyBlock {+ blocked[uuidToString(rule.OwnerUserID)+":"+rule.ToolkitSlug] = true+ }+ }catalog := h.ConnectedApps.Catalog(ctx, workspaceID)resp := AppsOverviewResponse{CatalogMode: catalog.Mode,@@ -235,10 +256,14 @@ func (h *Handler) GetAppsOverview(w http.ResponseWriter, r *http.Request) {AgentApps: make([]AgentAppResponse, 0, len(agentApps)),}for _, row := range team {- resp.Team = append(resp.Team, connectionFromTeam(row))+ connection := connectionFromTeam(row)+ connection.ActionsBlocked = blocked[uuidToString(pgtype.UUID{})+":"+row.ToolkitSlug]+ resp.Team = append(resp.Team, connection)}for _, row := range personal {- resp.Personal = append(resp.Personal, connectionFromPersonal(row))+ connection := connectionFromPersonal(row)+ connection.ActionsBlocked = blocked[uuidToString(member.UserID)+":"+row.ToolkitSlug]+ resp.Personal = append(resp.Personal, connection)}for _, row := range agentApps {resp.AgentApps = append(resp.AgentApps, agentAppResponse(row))@@ -597,8 +622,15 @@ func (h *Handler) UpdateAppRules(w http.ResponseWriter, r *http.Request) {return}}+ tx, err := h.TxStarter.Begin(r.Context())+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to save rules")+ return+ }+ defer tx.Rollback(r.Context())+ qtx := h.Queries.WithTx(tx)for _, rule := range req.Rules {- if _, err := h.Queries.UpsertAppActionRule(r.Context(), db.UpsertAppActionRuleParams{+ if _, err := qtx.UpsertAppActionRule(r.Context(), db.UpsertAppActionRuleParams{WorkspaceID: workspaceID, OwnerUserID: owner, ToolkitSlug: slug,ActionClass: rule.ActionClass, Policy: rule.Policy, UpdatedBy: member.UserID,}); err != nil {@@ -606,6 +638,10 @@ func (h *Handler) UpdateAppRules(w http.ResponseWriter, r *http.Request) {return}}+ if err := tx.Commit(r.Context()); 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")@@ -852,6 +888,9 @@ func (h *Handler) UpdateAgentApps(w http.ResponseWriter, r *http.Request) {type want struct{ slug, scope, level string }var wants []wantfor _, app := range req.Apps {+ if app.Level == "" {+ app.Level = connectedapps.DefaultLevel(agent.PermissionMode)+ }slug := connectedapps.NormalizeSlug(app.ToolkitSlug)if slug == "" || seen[slug] || !connectedapps.ValidScope(app.AccountScope) || !connectedapps.ValidLevel(app.Level) {writeError(w, http.StatusBadRequest, "invalid app")@@ -1144,20 +1183,22 @@ func (h *Handler) AppsGateway(w http.ResponseWriter, r *http.Request) {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.+// authorizing human, or to a system principal when no human originator exists.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}+ if !userID.Valid {+ return h.canInvokeAgent(ctx, agent, "system", "", "", uuidToString(workspaceID))+ }uid := uuidToString(userID)return h.canInvokeAgent(ctx, agent, "member", uid, uid, uuidToString(workspaceID))}+// ResumeAfterDecision implements connectedapps.Resumer: a run on the issue,+// or a message in the chat from the person who decided.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)diff --git a/server/internal/handler/connected_apps_access_test.go b/server/internal/handler/connected_apps_access_test.gonew file mode 100644index 0000000000..766e8d2e52--- /dev/null+++ b/server/internal/handler/connected_apps_access_test.go@@ -0,0 +1,242 @@+package handler++import (+ "context"+ "net/http"+ "strings"+ "testing"++ "github.com/jackc/pgx/v5/pgtype"+ "github.com/multica-ai/multica/server/internal/connectedapps"+ "github.com/multica-ai/multica/server/internal/testutil"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++func TestConnectedApps_GatewayRechecksAccess(t *testing.T) {+ for _, change := range []string{"departed", "private", "archived"} {+ t.Run(change, func(t *testing.T) {+ f := newAppsFixture(t)+ ctx := context.Background()+ f.executionAccount(t, "team")+ if w := f.putAgentApps(t, testUserID, []map[string]string{{"toolkit_slug": "gmail", "account_scope": "team", "level": "write"}}); w.Code != http.StatusOK {+ t.Fatalf("attach: %d %s", w.Code, w.Body.String())+ }+ dbfx.Exec(t, `UPDATE agent_task_queue SET originator_user_id=$1, accountable_user_id=$1 WHERE id=$2`, f.member, f.taskID)+ if !f.h.CanActFor(ctx, parseUUID(testWorkspaceID), parseUUID(f.agentID), parseUUID(f.member)) {+ t.Fatal("member must initially be allowed to invoke the shared agent")+ }+ if code, response, isErr := f.gateway(t, f.token(t), "apps_run_tool", map[string]any{"tool": "GMAIL_SEND_EMAIL"}); code != http.StatusOK || isErr {+ t.Fatalf("authorized call: %d %s", code, response)+ }+ switch change {+ case "departed":+ 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)+ }+ case "private":+ dbfx.Exec(t, `UPDATE agent SET permission_mode='private' WHERE id=$1`, f.agentID)+ case "archived":+ dbfx.Exec(t, `UPDATE agent SET archived_at=now() WHERE id=$1`, f.agentID)+ }+ var status string+ dbfx.QueryRow(t, `SELECT status FROM agent_task_queue WHERE id=$1`, f.taskID).Scan(&status)+ if status != "running" && status != "dispatched" {+ t.Fatalf("task must still be active to exercise gateway revocation, got %s", status)+ }+ if code, response, _ := f.gateway(t, f.token(t), "apps_run_tool", map[string]any{"tool": "GMAIL_SEND_EMAIL"}); code != http.StatusUnauthorized {+ t.Fatalf("revoked call: %d %s", code, response)+ }+ if n := len(f.sdk.executions()); n != 1 {+ t.Fatalf("executions = %d, want only the initial authorized send", n)+ }+ })+ }+}++func TestConnectedApps_SystemRunRechecksInvocationPermission(t *testing.T) {+ for _, accountable := range []string{"none", "owner", "departed_member"} {+ for _, revoke := range []string{"private", "member_only", "no_workspace_grant"} {+ t.Run(accountable+"/"+revoke, func(t *testing.T) {+ f := newAppsFixture(t)+ ctx := context.Background()+ f.executionAccount(t, "team")+ if w := f.putAgentApps(t, testUserID, []map[string]string{{"toolkit_slug": "gmail", "account_scope": "team", "level": "write"}}); w.Code != http.StatusOK {+ t.Fatalf("attach: %d %s", w.Code, w.Body.String())+ }+ var accountableID any+ if accountable == "owner" {+ accountableID = testUserID+ } else if accountable == "departed_member" {+ accountableID = f.member+ }+ dbfx.Exec(t, `UPDATE agent_task_queue SET originator_user_id=NULL, accountable_user_id=$1 WHERE id=$2`, accountableID, f.taskID)+ if accountable == "departed_member" {+ 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)+ }+ }+ agent, err := f.h.Queries.GetAgent(ctx, parseUUID(f.agentID))+ if err != nil {+ t.Fatal(err)+ }+ if !f.h.canInvokeAgent(ctx, agent, "system", "", "", testWorkspaceID) {+ t.Fatal("workspace-wide agent must initially admit a system run")+ }+ if code, response, isErr := f.gateway(t, f.token(t), "apps_run_tool", map[string]any{"tool": "GMAIL_FETCH_EMAILS"}); code != http.StatusOK || isErr {+ t.Fatalf("authorized system call: %d %s", code, response)+ }+ switch revoke {+ case "private":+ dbfx.Exec(t, `UPDATE agent SET permission_mode='private' WHERE id=$1`, f.agentID)+ case "member_only":+ dbfx.Exec(t, `UPDATE agent_invocation_target SET target_type='member', target_id=$1 WHERE agent_id=$2`, testUserID, f.agentID)+ case "no_workspace_grant":+ dbfx.Exec(t, `DELETE FROM agent_invocation_target WHERE agent_id=$1`, f.agentID)+ }+ if code, response, _ := f.gateway(t, f.token(t), "apps_run_tool", map[string]any{"tool": "GMAIL_SEND_EMAIL"}); code != http.StatusUnauthorized {+ t.Fatalf("revoked system call: %d %s", code, response)+ }+ if n := len(f.sdk.executions()); n != 1 {+ t.Fatalf("executions = %d, want only the initial authorized read", n)+ }+ })+ }+ }+}++func TestConnectedApps_SystemAccessRevokedDuringToolLookup(t *testing.T) {+ for _, accountable := range []string{"none", "owner"} {+ t.Run(accountable, func(t *testing.T) {+ f := newAppsFixture(t)+ f.executionAccount(t, "team")+ if w := f.putAgentApps(t, testUserID, []map[string]string{{"toolkit_slug": "gmail", "account_scope": "team", "level": "write"}}); w.Code != http.StatusOK {+ t.Fatalf("attach: %d %s", w.Code, w.Body.String())+ }+ var accountableID any+ if accountable == "owner" {+ accountableID = testUserID+ }+ dbfx.Exec(t, `UPDATE agent_task_queue SET originator_user_id=NULL, accountable_user_id=$1 WHERE id=$2`, accountableID, f.taskID)+ f.sdk.beforeListTools = func() {+ dbfx.Exec(t, `UPDATE agent SET permission_mode='private' WHERE id=$1`, f.agentID)+ }+ if _, text, isErr := f.gateway(t, f.token(t), "apps_run_tool", map[string]any{"tool": "GMAIL_SEND_EMAIL"}); !isErr {+ t.Fatalf("system access revoked during lookup: %s", text)+ }+ if n := len(f.sdk.executions()); n != 0 {+ t.Fatalf("executed %d system calls after revocation during lookup", n)+ }+ })+ }+}++func TestConnectedApps_GatewayRequiresInvocationAuthorizer(t *testing.T) {+ for _, principal := range []string{"human", "system"} {+ t.Run(principal, func(t *testing.T) {+ f := newAppsFixture(t)+ f.executionAccount(t, "team")+ if w := f.putAgentApps(t, testUserID, []map[string]string{{"toolkit_slug": "gmail", "account_scope": "team", "level": "write"}}); w.Code != http.StatusOK {+ t.Fatalf("attach: %d %s", w.Code, w.Body.String())+ }+ if principal == "system" {+ dbfx.Exec(t, `UPDATE agent_task_queue SET originator_user_id=NULL WHERE id=$1`, f.taskID)+ }+ f.h.ConnectedApps.SetResumer(nil)+ if code, response, _ := f.gateway(t, f.token(t), "apps_run_tool", map[string]any{"tool": "GMAIL_SEND_EMAIL"}); code != http.StatusUnauthorized {+ t.Fatalf("call without invocation authorizer: %d %s", code, response)+ }+ if n := len(f.sdk.executions()); n != 0 {+ t.Fatalf("executed %d calls without an invocation authorizer", n)+ }+ })+ }+}++func TestConnectedApps_AccessRevokedDuringToolLookup(t *testing.T) {+ f := newAppsFixture(t)+ f.executionAccount(t, "team")+ if w := f.putAgentApps(t, testUserID, []map[string]string{{"toolkit_slug": "gmail", "account_scope": "team", "level": "write"}}); w.Code != http.StatusOK {+ t.Fatalf("attach: %d %s", w.Code, w.Body.String())+ }+ f.sdk.beforeListTools = func() {+ dbfx.Exec(t, `UPDATE agent SET archived_at=now() WHERE id=$1`, f.agentID)+ }+ if _, text, isErr := f.gateway(t, f.token(t), "apps_run_tool", map[string]any{"tool": "GMAIL_SEND_EMAIL"}); !isErr {+ t.Fatalf("revoked during lookup: %s", text)+ }+ if n := len(f.sdk.executions()); n != 0 {+ t.Fatalf("executed %d calls after revocation during lookup", n)+ }+}++func TestConnectedApps_RestoreSavedAccess(t *testing.T) {+ f := newAppsFixture(t)+ f.executionAccount(t, "team")+ ctx := context.Background()+ for _, owner := range []pgtype.UUID{{}, parseUUID(testUserID), parseUUID(f.member)} {+ if _, err := f.h.Queries.UpsertAppActionRule(ctx, db.UpsertAppActionRuleParams{+ WorkspaceID: parseUUID(testWorkspaceID), OwnerUserID: owner, ToolkitSlug: "gmail",+ ActionClass: "send", Policy: "block", UpdatedBy: parseUUID(testUserID),+ }); err != nil {+ t.Fatal(err)+ }+ }+ if w := f.putAgentApps(t, testUserID, []map[string]string{{"toolkit_slug": "gmail", "account_scope": "personal", "level": "write"}}); w.Code != http.StatusOK {+ t.Fatalf("attach: %d %s", w.Code, w.Body.String())+ }+ var before AppsOverviewResponse+ testutil.Call(t, f.h.GetAppsOverview, appsReqAs(t, testUserID, http.MethodGet, "/api/apps", nil)).Want(http.StatusOK).JSON(&before)+ if len(before.Team) != 1 || len(before.Personal) != 1 || !before.Team[0].ActionsBlocked || !before.Personal[0].ActionsBlocked {+ t.Fatalf("saved restrictions are not visible: %+v", before)+ }+ if _, text, isErr := f.gateway(t, f.token(t), "apps_run_tool", map[string]any{"tool": "GMAIL_SEND_EMAIL"}); !isErr || !strings.HasPrefix(text, "blocked") {+ t.Fatalf("saved rule must apply until restored: %s", text)+ }+ rules := []map[string]string{}+ for _, class := range connectedapps.Classes {+ rules = append(rules, map[string]string{"action_class": class, "policy": "allow"})+ }+ previous := f.h.TxStarter+ f.h.TxStarter = rollbackOnCommitTxStarter{pool: testPool}+ testutil.Call(t, f.h.UpdateAppRules, appsReqAs(t, testUserID, http.MethodPut, "/api/apps/rules?toolkit_slug=gmail&scope=personal", map[string]any{"rules": rules})).Want(http.StatusInternalServerError)+ f.h.TxStarter = previous+ if n := dbfx.Count(t, `SELECT count(*) FROM app_action_rule WHERE workspace_id=$1 AND owner_user_id=$2 AND policy='block'`, testWorkspaceID, testUserID); n != 1 {+ t.Fatal("failed restore partially changed the account's rules")+ }+ // Restoring a personal account changes only the caller's rules.+ testutil.Call(t, f.h.UpdateAppRules, appsReqAs(t, testUserID, http.MethodPut, "/api/apps/rules?toolkit_slug=gmail&scope=personal", map[string]any{"rules": rules})).Want(http.StatusOK)+ var after AppsOverviewResponse+ testutil.Call(t, f.h.GetAppsOverview, appsReqAs(t, testUserID, http.MethodGet, "/api/apps", nil)).Want(http.StatusOK).JSON(&after)+ if after.Personal[0].ActionsBlocked || !after.Team[0].ActionsBlocked {+ t.Fatalf("restore crossed account scopes: %+v", after)+ }+ if _, text, isErr := f.gateway(t, f.token(t), "apps_run_tool", map[string]any{"tool": "GMAIL_SEND_EMAIL"}); isErr {+ t.Fatalf("restored account could not send: %s", text)+ }+ if n := dbfx.Count(t, `SELECT count(*) FROM app_action_rule WHERE workspace_id=$1 AND owner_user_id=$2 AND policy='block'`, testWorkspaceID, f.member); n != 1 {+ t.Fatal("another member's restriction was changed")+ }+ testutil.Call(t, f.h.UpdateAppRules, appsReqAs(t, f.member, http.MethodPut, "/api/apps/rules?toolkit_slug=gmail&scope=team", map[string]any{"rules": rules})).Want(http.StatusForbidden)+ testutil.Call(t, f.h.UpdateAppRules, appsReqAs(t, testUserID, http.MethodPut, "/api/apps/rules?toolkit_slug=gmail&scope=team", map[string]any{"rules": rules})).Want(http.StatusOK)++ // Even an empty saved catalog can be recovered without reconnecting.+ testutil.Call(t, f.h.UpdateAppSettings, appsReqAs(t, testUserID, http.MethodPut, "/api/apps/settings", map[string]any{"catalog_mode": "custom", "allowed_toolkits": []string{}})).Want(http.StatusOK)+ testutil.Call(t, f.h.GetAppsOverview, appsReqAs(t, testUserID, http.MethodGet, "/api/apps", nil)).Want(http.StatusOK).JSON(&after)+ if after.CatalogMode != "custom" {+ t.Fatal("saved empty catalog must remain visible until restored")+ }+ testutil.Call(t, f.h.UpdateAppSettings, appsReqAs(t, f.member, http.MethodPut, "/api/apps/settings", map[string]any{"catalog_mode": "all"})).Want(http.StatusForbidden)+ testutil.Call(t, f.h.UpdateAppSettings, appsReqAs(t, testUserID, http.MethodPut, "/api/apps/settings", map[string]any{"catalog_mode": "all"})).Want(http.StatusOK)+ testutil.Call(t, f.h.GetAppsOverview, appsReqAs(t, testUserID, http.MethodGet, "/api/apps", nil)).Want(http.StatusOK).JSON(&after)+ if after.CatalogMode != "all" || after.Team[0].ActionsBlocked || len(after.AgentApps) != 1 {+ t.Fatalf("restore did not preserve the connected apps: %+v", after)+ }+}diff --git a/server/internal/handler/connected_apps_boundary_test.go b/server/internal/handler/connected_apps_boundary_test.goindex 3c8e0989ec..6c1e097ccd 100644--- a/server/internal/handler/connected_apps_boundary_test.go+++ b/server/internal/handler/connected_apps_boundary_test.go@@ -21,15 +21,7 @@ import (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]+ return f.legacyRequest(t, "personal", "gmail", "GMAIL_SEND_EMAIL", "send", map[string]any{"to": "[email protected]"}, "")}func (f *appsFixture) requestStatus(t *testing.T, id string) string {@@ -248,17 +240,8 @@ func TestConnectedApps_ArchiveViaUpdateObeysDeleteRule(t *testing.T) {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+ request := f.legacyRequest(t, "personal", "notion", notionUpdatePage, "write", map[string]any{"page_id": "p1", "properties": map[string]any{"title": "Q3"}}, "")+ id := request.IDw := 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},@@ -282,10 +265,7 @@ func TestConnectedApps_PendingVisibleAfterHistoricalRequests(t *testing.T) {`, 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)- }+ f.legacyRequest(t, "personal", "gmail", "GMAIL_SEND_EMAIL", "send", map[string]any{"to": "[email protected]"}, "")type page struct {Requests []AppRequestResponse `json:"requests"`diff --git a/server/internal/handler/connected_apps_test.go b/server/internal/handler/connected_apps_test.goindex f01d8ecf89..cda714bf7f 100644--- a/server/internal/handler/connected_apps_test.go+++ b/server/internal/handler/connected_apps_test.go@@ -15,6 +15,7 @@ import ("testing""time"+ "github.com/jackc/pgx/v5/pgtype""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"@@ -27,10 +28,11 @@ import (// appsFakeSDK serves a small Gmail toolkit and records executions.type appsFakeSDK struct {composioFakeSDK- mu sync.Mutex- executed []sdk.ExecuteToolRequest- executeErr error- toolError string+ mu sync.Mutex+ executed []sdk.ExecuteToolRequest+ executeErr error+ toolError string+ beforeListTools func()}var appsFakeGmailTools = []sdk.Tool{@@ -44,6 +46,9 @@ func (f *appsFakeSDK) GetToolkit(_ context.Context, slug string) (*sdk.Toolkit,}func (f *appsFakeSDK) ListTools(_ context.Context, req sdk.ListToolsRequest) (*sdk.ListToolsResponse, error) {+ if f.beforeListTools != nil {+ f.beforeListTools()+ }if req.ToolkitSlug != "gmail" {return &sdk.ListToolsResponse{}, nil}@@ -230,7 +235,28 @@ func (f *appsFixture) listRequests(t *testing.T, userID string) []AppRequestRespreturn resp.Requests}-func TestConnectedApps_ConfirmApproveResumes(t *testing.T) {+// legacyRequest seeds an action submitted before per-call approval was removed.+// Existing requests retain their approver, isolation, expiry, and execution checks.+func (f *appsFixture) legacyRequest(t *testing.T, scope, slug, tool, class string, args map[string]any, summary string) AppRequestResponse {+ t.Helper()+ raw, err := json.Marshal(args)+ if err != nil {+ t.Fatal(err)+ }+ req, err := f.h.Queries.CreateAppActionRequest(context.Background(), db.CreateAppActionRequestParams{+ WorkspaceID: parseUUID(testWorkspaceID), Kind: connectedapps.KindAction,+ TaskID: parseUUID(f.taskID), AgentID: parseUUID(f.agentID), IssueID: parseUUID(f.issueID),+ ApproverUserID: parseUUID(testUserID), AccountScope: scope, ToolkitSlug: slug,+ ToolSlug: tool, ActionClass: class, Arguments: raw, Summary: summary,+ ExpiresAt: pgtype.Timestamptz{Time: time.Now().Add(connectedapps.RequestTTL), Valid: true},+ })+ if err != nil {+ t.Fatal(err)+ }+ return f.h.requestResponse(req, parseUUID(testUserID))+}++func TestConnectedApps_LegacyApprovalResumes(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 {@@ -258,17 +284,8 @@ func TestConnectedApps_ConfirmApproveResumes(t *testing.T) {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})+ f.legacyRequest(t, "personal", "gmail", "GMAIL_SEND_EMAIL", "send", args, "Reply to the customer")mine := f.listRequests(t, testUserID)if len(mine) != 1 || mine[0].Status != "pending" || mine[0].Redacted || mine[0].Summary != "Reply to the customer" {@@ -279,12 +296,6 @@ func TestConnectedApps_ConfirmApproveResumes(t *testing.T) {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)@@ -325,6 +336,84 @@ func TestConnectedApps_ConfirmApproveResumes(t *testing.T) {}}+func TestConnectedApps_RunWithoutApproval(t *testing.T) {+ for _, scope := range []string{"personal", "team"} {+ for _, level := range []string{"", "write", "confirm_writes"} {+ for _, rule := range []string{"", "confirm"} {+ t.Run(fmt.Sprintf("%s/level=%s/rule=%s", scope, level, rule), func(t *testing.T) {+ f := newAppsFixture(t)+ _, _, userID, accountID := f.executionAccount(t, scope)+ app := map[string]string{"toolkit_slug": "gmail", "account_scope": scope}+ if level != "" {+ app["level"] = level+ }+ if w := f.putAgentApps(t, testUserID, []map[string]string{app}); w.Code != http.StatusOK {+ t.Fatalf("attach app: %d %s", w.Code, w.Body.String())+ }+ if level == "" {+ var saved string+ if err := testPool.QueryRow(context.Background(), `SELECT level FROM agent_app WHERE agent_id=$1 AND toolkit_slug='gmail'`, f.agentID).Scan(&saved); err != nil || saved != "write" {+ t.Fatalf("default level = %q, error %v", saved, err)+ }+ }+ if rule != "" {+ rules := []map[string]string{}+ for _, class := range connectedapps.Classes {+ rules = append(rules, map[string]string{"action_class": class, "policy": rule})+ }+ w := httptest.NewRecorder()+ f.h.UpdateAppRules(w, appsReqAs(t, testUserID, http.MethodPut, "/api/apps/rules?toolkit_slug=gmail&scope="+scope, map[string]any{"rules": rules}))+ if w.Code != http.StatusOK {+ t.Fatalf("save rules: %d %s", w.Code, w.Body.String())+ }+ }+ oldTools := appsFakeGmailTools+ appsFakeGmailTools = append(append([]sdk.Tool{}, oldTools...),+ sdk.Tool{Slug: "GMAIL_CREATE_EMAIL_DRAFT", Name: "Create draft", Toolkit: sdk.Toolkit{Slug: "gmail"}},+ sdk.Tool{Slug: "GMAIL_SHARE_MAILBOX", Name: "Share mailbox", Toolkit: sdk.Toolkit{Slug: "gmail"}})+ t.Cleanup(func() { appsFakeGmailTools = oldTools })+ agent, err := f.h.Queries.GetAgent(context.Background(), parseUUID(f.agentID))+ if err != nil {+ t.Fatal(err)+ }+ overlay, err := f.h.ConnectedApps.BuildTaskOverlay(context.Background(), parseUUID(testUserID), agent)+ if err != nil || len(overlay.ConnectedApps) != 1 || overlay.ConnectedApps[0].Level != "write" {+ t.Fatalf("runtime app metadata = %+v, error %v", overlay.ConnectedApps, err)+ }+ token := f.token(t)+ if _, text, isErr := f.gateway(t, token, "apps_list", nil); isErr || !strings.Contains(text, `"level": "write"`) {+ t.Fatalf("runtime app list: %s", text)+ }+ for i, tool := range appsFakeGmailTools {+ for _, discovery := range []string{"apps_get_tool", "apps_search_tools"} {+ if _, text, isErr := f.gateway(t, token, discovery, map[string]any{"app": "gmail", "tool": tool.Slug, "query": tool.Slug}); isErr || !strings.Contains(text, `"policy": "allow"`) {+ t.Fatalf("%s %s: %s", discovery, tool.Slug, text)+ }+ }+ args := map[string]any{"user_id": "me", "body": "test message"}+ if _, text, isErr := f.gateway(t, token, "apps_run_tool", map[string]any{"tool": tool.Slug, "arguments": args}); isErr || !strings.Contains(text, tool.Slug) || strings.HasPrefix(text, "submitted") {+ t.Fatalf("direct call %s: %s (error %v)", tool.Slug, text, isErr)+ }+ execs := f.sdk.executions()+ if len(execs) != i+1 || execs[i].UserID != userID || execs[i].ConnectedAccountID != accountID || !reflect.DeepEqual(execs[i].Arguments, args) {+ t.Fatalf("execution %d: %+v", i, execs)+ }+ }+ if requests := f.listRequests(t, testUserID); len(requests) != 0 {+ t.Fatalf("direct calls created approval requests: %+v", requests)+ }+ if n := f.inboxCount(t, testUserID, connectedapps.NotifActionRequested); n != 0 {+ t.Fatalf("direct calls created %d approval notifications", n)+ }+ if n := dbfx.Count(t, `SELECT count(*) FROM app_tool_call WHERE task_id=$1 AND outcome='ok' AND request_id IS NULL`, f.taskID); n != len(appsFakeGmailTools) {+ t.Fatalf("successful audited calls = %d", n)+ }+ })+ }+ }+ }+}+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 {@@ -368,6 +457,11 @@ func TestConnectedApps_RulesAndLevels(t *testing.T) {func TestConnectedApps_AdminOnlyTeamSurfaces(t *testing.T) {f := newAppsFixture(t)+ activity := httptest.NewRecorder()+ f.h.ListAppActivity(activity, appsReqAs(t, f.member, http.MethodGet, "/api/apps/activity?toolkit_slug=gmail&scope=team", nil))+ if activity.Code != http.StatusForbidden {+ t.Fatalf("member reads team activity: %d, want 403", activity.Code)+ }w := f.putAgentApps(t, f.member, []map[string]string{{"toolkit_slug": "gmail", "account_scope": "team", "level": "read"}})if w.Code != http.StatusForbidden {@@ -436,9 +530,7 @@ func TestConnectedApps_ResultNotifications(t *testing.T) {// 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)- }+ f.legacyRequest(t, "personal", "gmail", "GMAIL_SEND_EMAIL", "send", map[string]any{"to": "x"}, "")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" {@@ -448,7 +540,7 @@ func TestConnectedApps_ResultNotifications(t *testing.T) {t.Fatalf("result notifications after expiry = %d, want 2", n)}- // Muting agent activity mutes results, never confirmations.+ // Muting agent activity also mutes expiry results for legacy requests.testPool.Exec(context.Background(), `INSERT INTO notification_preference (workspace_id, user_id, preferences)VALUES ($1, $2, '{"agent_activity":"muted"}')@@ -457,10 +549,7 @@ func TestConnectedApps_ResultNotifications(t *testing.T) {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)- }+ f.legacyRequest(t, "personal", "gmail", "GMAIL_SEND_EMAIL", "send", map[string]any{"to": "y"}, "")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 {@@ -565,9 +654,15 @@ func TestConnectedApps_ToolClassOverride(t *testing.T) {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)+ // The corrected class drives explicit account restrictions.+ 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": "block"}}}))+ if w.Code != http.StatusOK {+ t.Fatalf("set send rule: %d %s", w.Code, w.Body.String())+ }+ 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, "blocked") {+ t.Fatalf("overridden read = %s, want blocked", text)}if code := setClass(testUserID, ""); code != http.StatusNoContent {t.Fatalf("reset override: %d", code)@@ -657,23 +752,18 @@ func TestConnectedApps_ExecutionIdentity(t *testing.T) {tool = "GMAIL_SEND_EMAIL"}args := map[string]any{"user_id": "me", "connected_account_id": "caller_account", "body": "private draft"}- _, text, isErr := f.gateway(t, f.token(t), "apps_run_tool", map[string]any{"tool": tool, "arguments": args})- if isErr {- t.Fatalf("gateway call failed: %s", text)+ if !approved {+ if _, text, isErr := f.gateway(t, f.token(t), "apps_run_tool", map[string]any{"tool": tool, "arguments": args}); isErr {+ t.Fatalf("gateway call failed: %s", text)+ }}if approved {- if !strings.HasPrefix(text, "submitted") || len(f.sdk.executions()) != 0 {- t.Fatalf("call did not wait for approval: %s", text)- }- requests := f.listRequests(t, testUserID)- if len(requests) != 1 {- t.Fatalf("requests = %+v", requests)- }+ request := f.legacyRequest(t, scope, "gmail", tool, "send", args, "")// Execution must resolve the current pair again after approval.userID, accountID = userID+"_reconnected", accountID+"_reconnected"dbfx.Exec(t, "UPDATE "+table+" SET composio_user_id = $1, connected_account_id = $2 WHERE id = $3", userID, accountID, id)args["body"] = "edited draft"- if out := f.approve(t, requests[0].ID, args); out.Status != "approved" {+ if out := f.approve(t, request.ID, args); out.Status != "approved" {t.Fatalf("approved call = %+v", out)}}@@ -701,10 +791,7 @@ func TestConnectedApps_ExecutionRejectsMissingIdentity(t *testing.T) {}args := map[string]any{"user_id": "me"}if approved {- _, text, isErr := f.gateway(t, f.token(t), "apps_run_tool", map[string]any{"tool": "GMAIL_SEND_EMAIL", "arguments": args})- if isErr || !strings.HasPrefix(text, "submitted") {- t.Fatalf("submit = %s", text)- }+ f.legacyRequest(t, scope, "gmail", "GMAIL_SEND_EMAIL", "send", args, "")}dbfx.Exec(t, "UPDATE "+table+" SET composio_user_id = $1 WHERE id = $2", identity, id)if approved {@@ -739,7 +826,7 @@ func TestConnectedApps_ExecutionAccountIsolation(t *testing.T) {args := map[string]any{"user_id": "me"}var requestID stringif approved {- f.gateway(t, f.token(t), "apps_run_tool", map[string]any{"tool": "GMAIL_SEND_EMAIL", "arguments": args})+ f.legacyRequest(t, scope, "gmail", "GMAIL_SEND_EMAIL", "send", args, "")requests := f.listRequests(t, testUserID)if len(requests) != 1 {t.Fatalf("requests = %+v", requests)@@ -799,7 +886,14 @@ func TestConnectedApps_ExecutionFailureLogs(t *testing.T) {if approved {tool = "GMAIL_SEND_EMAIL"}- code, text, isErr := f.gateway(t, f.token(t), "apps_run_tool", map[string]any{"tool": tool, "arguments": map[string]any{"body": private}})+ var code int+ var text string+ var isErr bool+ if approved {+ f.legacyRequest(t, "personal", "gmail", tool, "send", map[string]any{"body": private}, "")+ } else {+ code, text, isErr = f.gateway(t, f.token(t), "apps_run_tool", map[string]any{"tool": tool, "arguments": map[string]any{"body": private}})+ }requestID := ""if approved {requests := f.listRequests(t, testUserID)