Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
feat(apps): Apps hub, one account model for team and personal accounts, app requests (MUL-8990) (#10806)
Jiayuan Zhangfd571019f4ee
diff --git a/apps/desktop/src/renderer/src/pages/app-detail-page.tsx b/apps/desktop/src/renderer/src/pages/app-detail-page.tsxnew file mode 100644index 0000000000..68e1e19336--- /dev/null+++ b/apps/desktop/src/renderer/src/pages/app-detail-page.tsx@@ -0,0 +1,8 @@+import { useParams } from "react-router-dom";+import { AppDetailPage as SharedAppDetailPage } from "@multica/views/apps";++export function AppDetailPage() {+ const { slug } = useParams<{ slug: string }>();+ if (!slug) return null;+ return <SharedAppDetailPage toolkitSlug={slug} />;+}diff --git a/apps/desktop/src/renderer/src/routes.tsx b/apps/desktop/src/renderer/src/routes.tsxindex 8f4bd56e32..a553414381 100644--- a/apps/desktop/src/renderer/src/routes.tsx+++ b/apps/desktop/src/renderer/src/routes.tsx@@ -7,6 +7,7 @@ import { IssueDetailPage } from "./pages/issue-detail-page";import { ProjectDetailPage } from "./pages/project-detail-page";import { AutopilotDetailPage } from "./pages/autopilot-detail-page";import { SkillDetailPage } from "./pages/skill-detail-page";+import { AppDetailPage } from "./pages/app-detail-page";import { AgentDetailPage } from "./pages/agent-detail-page";import { AiBuilderSessionPage } from "./pages/ai-builder-session-page";import { MemberDetailPage } from "./pages/member-detail-page";@@ -21,6 +22,7 @@ import { DashboardPage } from "@multica/views/dashboard";import { AutopilotsPage } from "@multica/views/autopilots/components";import { MyIssuesPage } from "@multica/views/my-issues";import { SkillsPage } from "@multica/views/skills";+import { AppsPage } from "@multica/views/apps";import { DesktopRuntimesPage } from "./components/desktop-runtimes-page";import { DesktopAgentsPage } from "./components/desktop-agents-page";import { ManualCreateAgentPage } from "@multica/views/agents";@@ -167,6 +169,8 @@ export const appRoutes: RouteObject[] = [{ path: "docs/:id/history", element: <DocHistoryRoute /> },{ path: "skills", element: <SkillsPage /> },{ path: "skills/:id", element: <SkillDetailPage /> },+ { path: "apps", element: <AppsPage /> },+ { path: "apps/:slug", element: <AppDetailPage /> },{ path: "agents", element: <DesktopAgentsPage /> },{ path: "agents/new", element: <DesktopChooseRuntimePage /> },{ path: "agents/new/done/:agentId", element: <AgentCreatedPage /> },diff --git a/apps/web/app/[workspaceSlug]/(dashboard)/apps/[slug]/page.tsx b/apps/web/app/[workspaceSlug]/(dashboard)/apps/[slug]/page.tsxnew file mode 100644index 0000000000..fd4cf2c05f--- /dev/null+++ b/apps/web/app/[workspaceSlug]/(dashboard)/apps/[slug]/page.tsx@@ -0,0 +1,13 @@+"use client";++import { use } from "react";+import { AppDetailPage } from "@multica/views/apps";++export default function AppDetailRoute({+ params,+}: {+ params: Promise<{ slug: string }>;+}) {+ const { slug } = use(params);+ return <AppDetailPage toolkitSlug={slug} />;+}diff --git a/apps/web/app/[workspaceSlug]/(dashboard)/apps/page.tsx b/apps/web/app/[workspaceSlug]/(dashboard)/apps/page.tsxnew file mode 100644index 0000000000..62ae31bbcb--- /dev/null+++ b/apps/web/app/[workspaceSlug]/(dashboard)/apps/page.tsx@@ -0,0 +1 @@+export { AppsPage as default } from "@multica/views/apps";diff --git a/apps/web/config/google-analytics.ts b/apps/web/config/google-analytics.tsindex b838f478fb..cf1434a9a9 100644--- a/apps/web/config/google-analytics.ts+++ b/apps/web/config/google-analytics.ts@@ -75,6 +75,7 @@ const GLOBAL_ROUTES_OUTSIDE_RESERVED = new Set(["join", "lark", "slack", "telegr// workspace page rather than echoing an unknown segment.const WORKSPACE_SECTIONS = new Set(["agents",+ "apps","attachments","autopilots","billing",diff --git a/e2e/settings.spec.ts b/e2e/settings.spec.tsindex a0f5d22877..11d8067b93 100644--- a/e2e/settings.spec.ts+++ b/e2e/settings.spec.ts@@ -1,4 +1,4 @@-import { test, expect } from "@playwright/test";+import { test, expect, type Page } from "@playwright/test";import { appRail, currentWorkspaceTile, loginAsDefault, waitForPageText } from "./helpers";test.describe("Settings", () => {@@ -39,82 +39,90 @@ test.describe("Settings", () => {await expect(appRail(page).getByRole("link", { name: originalName })).toBeVisible();});- // Composio connect flow, fully mocked at the network boundary so it runs- // without a configured COMPOSIO_API_KEY or a live Composio project. The- // backend redirect is simulated by pointing the init endpoint's redirect_url- // straight back at the settings page with ?connected=<slug> — exercising the- // frontend's callback toast + connections refresh (MUL-3718) end to end.- test("connecting a Composio toolkit shows a toast and refreshes the list", async ({- page,- }) => {- const workspaceSlug = await loginAsDefault(page);- const settingsUrl = `/${workspaceSlug}/settings?tab=integrations&integration=composio`;-- // Stateful: connections is empty until the (mocked) connect flow lands.+ // Connected apps are mocked at the network boundary so the flow runs without+ // a configured COMPOSIO_API_KEY or a live Composio project. A connect started+ // without a return path comes back as `/settings?tab=apps&connected=<slug>`+ // (the web proxy prepends the workspace slug); a personal one must land on+ // Connected accounts, report the result once and refresh the list.+ async function mockConnectedApps(page: Page) {let connected = false;-- await page.route("**/api/integrations/composio/toolkits", (route) =>- route.fulfill({- status: 200,- contentType: "application/json",- body: JSON.stringify([- { slug: "notion", name: "Notion", connectable: true },- ]),- }),+ await page.route(+ (url) => url.pathname === "/api/config",+ async (route) => {+ const response = await route.fetch();+ const body = await response.json();+ await route.fulfill({+ response,+ json: { ...body, feature_flags: { ...body.feature_flags, composio_mcp_apps: true } },+ });+ },+ );+ await page.route(+ (url) => url.pathname === "/api/integrations/composio/toolkits",+ (route) => route.fulfill({ json: [{ slug: "notion", name: "Notion", connectable: true }] }),+ );+ await page.route(+ (url) => url.pathname === "/api/apps",+ (route) => route.fulfill({ json: {+ catalog_mode: "all",+ can_manage: true,+ team: [],+ agent_apps: [{ agent_id: "agent-1", toolkit_slug: "notion", account_scope: "personal", level: "write" }],+ personal: connected+ ? [{ id: "conn-notion-1", toolkit_slug: "notion", status: "active", connected_at: new Date().toISOString(), last_used_at: null }]+ : [],+ } }),+ );+ await page.route(+ (url) => url.pathname === "/api/apps/catalog",+ (route) => route.fulfill({ json: {+ catalog_mode: "all",+ apps: [{ slug: "notion", name: "Notion", curated: true, recommended_scope: "team" }],+ } }),+ );+ await page.route(+ (url) => url.pathname === "/api/app-requests",+ (route) => route.fulfill({ json: { requests: [], next_before: null } }),);+ await page.route(+ (url) => /^\/api\/integrations\/composio\/connections\/[^/]+\/impact$/.test(url.pathname),+ (route) => route.fulfill({ json: { agents: [] } }),+ );+ await page.route(+ (url) => url.pathname === "/api/apps/personal/connect",+ (route) => {+ connected = true;+ return route.fulfill({ json: { redirect_url: "/settings?tab=apps&connected=notion" } });+ },+ );+ }- await page.route("**/api/integrations/composio/connections", (route) => {- if (route.request().method() !== "GET") return route.fallback();- return route.fulfill({- status: 200,- contentType: "application/json",- body: JSON.stringify(- connected- ? [- {- id: "conn-notion-1",- toolkit_slug: "notion",- status: "active",- connected_at: new Date().toISOString(),- last_used_at: null,- },- ]- : [],- ),- });- });+ test("the old Accounts settings link opens Apps › Accounts, and a personal connect returns there", async ({+ page,+ }) => {+ await mockConnectedApps(page);+ const workspaceSlug = await loginAsDefault(page);- await page.route("**/api/integrations/composio/connect/init", (route) => {- // Composio would 302 through its hosted consent and back to our callback,- // which emits CallbackRedirect's slug-less shape:- // `/settings?tab=integrations&connected=<slug>`. The web proxy's- // legacy-route redirect then prepends the last workspace slug, landing on- // the real settings route. Mock that exact backend shape (NOT the final- // slugged URL) so the test exercises the same redirect path real users hit.- connected = true;- return route.fulfill({- status: 200,- contentType: "application/json",- body: JSON.stringify({- redirect_url: `/settings?tab=integrations&connected=notion`,- }),- });- });+ await page.goto(`/${workspaceSlug}/settings?tab=accounts`, { waitUntil: "domcontentloaded" });+ await expect(page).toHaveURL(new RegExp(`/${workspaceSlug}/apps\\?tab=accounts$`), { timeout: 10000 });+ await waitForPageText(page, "Your accounts");- await page.goto(settingsUrl, { waitUntil: "domcontentloaded" });- await waitForPageText(page, "Composio");+ await page.locator('[data-account-row="personal:notion"]').getByRole("button", { name: "Connect" }).click();+ // Agents' abilities are disclosed before the hosted flow starts.+ await page.getByRole("dialog", { name: /Connect Notion/ }).getByRole("button", { name: "Continue" }).click();- // Notion starts disconnected → click Connect.- await page.getByRole("button", { name: /^Connect$/ }).first().click();+ await expect(page.getByText("Account connected").first()).toBeVisible({ timeout: 10000 });+ await expect(page.getByRole("button", { name: "Notion actions" })).toBeVisible({ timeout: 10000 });+ await expect(page).toHaveURL(/tab=accounts/);+ await expect(page).not.toHaveURL(/connected=notion/);+ });- // Success toast from the simulated callback redirect.- await expect(page.getByText("Connected").first()).toBeVisible({ timeout: 10000 });+ test("the retired Apps settings tab opens the Apps page", async ({ page }) => {+ await mockConnectedApps(page);+ const workspaceSlug = await loginAsDefault(page);- // List refreshed without a manual reload: the Notion card now offers- // Disconnect, and the one-shot ?connected param has been stripped.- await expect(- page.getByRole("button", { name: /Disconnect/ }).first(),- ).toBeVisible({ timeout: 10000 });- await expect(page).not.toHaveURL(/connected=notion/);+ await page.goto(`/${workspaceSlug}/settings?tab=apps`, { waitUntil: "domcontentloaded" });+ await expect(page).toHaveURL(new RegExp(`/${workspaceSlug}/apps$`), { timeout: 10000 });+ await expect(page.getByRole("tab", { name: /All apps/ })).toBeVisible();});});diff --git a/packages/core/api/client.ts b/packages/core/api/client.tsindex 5031f5af38..ebdbe99bf6 100644--- a/packages/core/api/client.ts+++ b/packages/core/api/client.ts@@ -250,6 +250,7 @@ import type {IssueAppCall,AppRequestList,TeamAppImpact,+ PersonalAppImpact,AppRequest,AgentApp,AppAccountScope,@@ -532,6 +533,7 @@ import {EMPTY_APPS_OVERVIEW,EMPTY_TEAM_APP_IMPACT,IssueAppCallsResponseSchema,+ PersonalAppImpactSchema,TeamAppImpactSchema,EMPTY_ISSUE_UNREAD_PAGE,SubscribedIssueIdsSchema,@@ -6264,6 +6266,29 @@ export class ApiClient {return parseWithFallback(raw, TeamAppImpactSchema, EMPTY_TEAM_APP_IMPACT, { endpoint: "GET /api/apps/team/impact" });}+ /** Asks the workspace's admins to connect a team account for an app. */+ async requestTeamApp(toolkitSlug: string, agentId?: string): Promise<void> {+ await this.fetch(`/api/apps/team/requests`, {+ method: "POST",+ body: JSON.stringify({ toolkit_slug: toolkitSlug, ...(agentId ? { agent_id: agentId } : {}) }),+ });+ }++ /** An admin declines every open team-account request for an app; a member+ * withdraws their own. */+ async dismissTeamAppRequests(toolkitSlug: string): Promise<void> {+ await this.fetch(`/api/apps/team/requests?toolkit_slug=${encodeURIComponent(toolkitSlug)}`, { method: "DELETE" });+ }++ /** What disconnecting one of the caller's personal accounts would stop in+ * its workspace. */+ async getPersonalAppImpact(connectionId: string): Promise<PersonalAppImpact> {+ const raw = await this.fetch<unknown>(`/api/integrations/composio/connections/${connectionId}/impact`);+ return parseWithFallback(raw, PersonalAppImpactSchema, { agents: [] }, {+ endpoint: "GET /api/integrations/composio/connections/:id/impact",+ });+ }+// Write responses parse to null when malformed; callers refetch instead of// caching a guess.diff --git a/packages/core/api/schemas.ts b/packages/core/api/schemas.tsindex eafff8ab39..b41683072a 100644--- a/packages/core/api/schemas.ts+++ b/packages/core/api/schemas.ts@@ -5054,6 +5054,23 @@ export const AppsOverviewSchema = z.object({team: z.array(AppConnectionSchema).default([]),personal: z.array(AppConnectionSchema).default([]),agent_apps: z.array(AgentAppSchema).default([]),+ team_requests: z.array(z.object({+ toolkit_slug: z.string(),+ requested_by: z.array(z.string()).default([]).catch([]),+ asked_by: z.array(z.string()).optional().catch(undefined),+ agent_ids: z.array(z.string()).default([]).catch([]),+ last_requested_at: z.string().default(""),+ }).loose()).default([]).catch([]),+}).loose();++export const PersonalAppImpactSchema = z.object({+ agents: z.array(z.object({+ id: z.string(),+ name: z.string().default(""),+ workspace_id: z.string().default(""),+ workspace_name: z.string().default(""),+ running: z.boolean().default(false).catch(false),+ }).loose()).default([]),}).loose();const AppCatalogEntrySchema = z.object({@@ -5131,6 +5148,8 @@ export const AppRequestSchema = z.object({reason: appNullableString,// Withhold the details unless the server said otherwise.redacted: z.boolean().default(true).catch(true),+ adds_app: z.boolean().default(false).catch(false),+ can_decide: z.boolean().optional().catch(undefined),expires_at: z.string(),decided_by: appNullableString,decided_at: appNullableString,@@ -5179,6 +5198,7 @@ export const EMPTY_APPS_OVERVIEW: AppsOverview = {team: [],personal: [],agent_apps: [],+ team_requests: [],};export const EMPTY_APP_CATALOG: AppCatalogResponse = { catalog_mode: "curated", apps: [] };diff --git a/packages/core/connected-apps/index.ts b/packages/core/connected-apps/index.tsindex a42de1ecea..709cbae858 100644--- a/packages/core/connected-apps/index.ts+++ b/packages/core/connected-apps/index.ts@@ -5,13 +5,18 @@ export {issueAppCallsOptions,appActivityOptions,teamAppImpactOptions,+ personalAppImpactOptions,+ myPendingAppRequestsOptions,agentAppsOptions,issueAppRequestsOptions,chatAppRequestsOptions,} from "./queries";export {useDisconnectTeamApp,+ useDisconnectPersonalApp,useRestoreAppAccess,useUpdateAgentApps,useDecideAppRequest,+ useRequestTeamApp,+ useDismissTeamAppRequests,} from "./mutations";diff --git a/packages/core/connected-apps/mutations.ts b/packages/core/connected-apps/mutations.tsindex 5156ec555c..454d64561d 100644--- a/packages/core/connected-apps/mutations.ts+++ b/packages/core/connected-apps/mutations.ts@@ -32,6 +32,36 @@ export function useDisconnectTeamApp() {});}+/** Removes one of the caller's own accounts from every workspace. */+export function useDisconnectPersonalApp() {+ const qc = useQueryClient();+ const wsId = useWorkspaceId();+ return useMutation({+ mutationFn: (connectionId: string) => api.deleteComposioConnection(connectionId),+ onSettled: () => qc.invalidateQueries({ queryKey: connectedAppsKeys.all(wsId) }),+ });+}++export function useRequestTeamApp() {+ const qc = useQueryClient();+ const wsId = useWorkspaceId();+ return useMutation({+ mutationFn: (input: { slug: string; agentId?: string }) => api.requestTeamApp(input.slug, input.agentId),+ onSettled: () => qc.invalidateQueries({ queryKey: connectedAppsKeys.all(wsId) }),+ });+}++/** An admin declines everything waiting for an app's team account; a member+ * withdraws their own ask. */+export function useDismissTeamAppRequests() {+ const qc = useQueryClient();+ const wsId = useWorkspaceId();+ return useMutation({+ mutationFn: (slug: string) => api.dismissTeamAppRequests(slug),+ onSettled: () => qc.invalidateQueries({ queryKey: connectedAppsKeys.all(wsId) }),+ });+}+/** Replaces an agent's apps. The legacy `composio_toolkit_allowlist` on the* agent follows server-side, so the agent list is refreshed too. */export function useUpdateAgentApps(agentId: string) {diff --git a/packages/core/connected-apps/queries.ts b/packages/core/connected-apps/queries.tsindex 9d5704ff0c..2b040cd16e 100644--- a/packages/core/connected-apps/queries.ts+++ b/packages/core/connected-apps/queries.ts@@ -14,9 +14,12 @@ export const connectedAppsKeys = {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,+ personalImpact: (wsId: string, connectionId: string) =>+ [...connectedAppsKeys.all(wsId), "personal-impact", connectionId] as const,agentApps: (wsId: string, agentId: string) =>[...connectedAppsKeys.all(wsId), "agent", agentId] as const,requests: (wsId: string) => [...connectedAppsKeys.all(wsId), "requests"] as const,+ myPendingRequests: (wsId: string) => [...connectedAppsKeys.requests(wsId), "mine"] as const,issueRequests: (wsId: string, issueId: string) =>[...connectedAppsKeys.requests(wsId), "issue", issueId] as const,chatRequests: (wsId: string, sessionId: string) =>@@ -56,6 +59,19 @@ export const teamAppImpactOptions = (wsId: string, slug: string) =>queryFn: () => api.getTeamAppImpact(slug),});+export const personalAppImpactOptions = (wsId: string, connectionId: string) =>+ queryOptions({+ queryKey: connectedAppsKeys.personalImpact(wsId, connectionId),+ queryFn: () => api.getPersonalAppImpact(connectionId),+ });++/** Requests in this workspace still waiting on the caller. */+export const myPendingAppRequestsOptions = (wsId: string) =>+ queryOptions({+ queryKey: connectedAppsKeys.myPendingRequests(wsId),+ queryFn: () => api.listAppRequests().then((r) => r.requests),+ });+export const agentAppsOptions = (wsId: string, agentId: string) =>queryOptions({queryKey: connectedAppsKeys.agentApps(wsId, agentId),diff --git a/packages/core/diagnostics/diagnostic-context.ts b/packages/core/diagnostics/diagnostic-context.tsindex ddd84e03d7..831ae2ac04 100644--- a/packages/core/diagnostics/diagnostic-context.ts+++ b/packages/core/diagnostics/diagnostic-context.ts@@ -85,6 +85,8 @@ const WORKSPACE_ROUTES: readonly RoutePattern[] = [["docs", "folders", ":id"],["skills"],["skills", ":id"],+ ["apps"],+ ["apps", ":id"],["settings"],["attachments", ":id", "preview"],];diff --git a/packages/core/paths/consistency.test.ts b/packages/core/paths/consistency.test.tsindex 87fc70a92f..2f25160c7f 100644--- a/packages/core/paths/consistency.test.ts+++ b/packages/core/paths/consistency.test.ts@@ -27,6 +27,7 @@ describe("paths.workspace() shape", () => {["myIssues", "my-issues"],["runtimes", "runtimes"],["skills", "skills"],+ ["apps", "apps"],["squads", "squads"],["settings", "settings"],];diff --git a/packages/core/paths/paths.test.ts b/packages/core/paths/paths.test.tsindex f8d4279834..004102c372 100644--- a/packages/core/paths/paths.test.ts+++ b/packages/core/paths/paths.test.ts@@ -31,6 +31,8 @@ describe("paths.workspace(slug)", () => {);expect(ws.skills()).toBe("/acme/skills");expect(ws.skillDetail("skl_123")).toBe("/acme/skills/skl_123");+ expect(ws.apps()).toBe("/acme/apps");+ expect(ws.appDetail("google_calendar")).toBe("/acme/apps/google_calendar");expect(ws.squads()).toBe("/acme/squads");expect(ws.squadDetail("sq_1")).toBe("/acme/squads/sq_1");expect(ws.settings()).toBe("/acme/settings");diff --git a/packages/core/paths/paths.ts b/packages/core/paths/paths.tsindex 39d2c4737f..f59396f014 100644--- a/packages/core/paths/paths.ts+++ b/packages/core/paths/paths.ts@@ -113,6 +113,8 @@ function workspaceScoped(slug: string) {docFolder: (id: string) => `${ws}/docs/folders/${encode(id)}`,skills: () => `${ws}/skills`,skillDetail: (id: string) => `${ws}/skills/${encode(id)}`,+ apps: () => `${ws}/apps`,+ appDetail: (toolkitSlug: string) => `${ws}/apps/${encode(toolkitSlug)}`,settings: () => `${ws}/settings`,attachmentPreview: (id: string) => `${ws}/attachments/${encode(id)}/preview`,};diff --git a/packages/core/paths/reserved-slugs.ts b/packages/core/paths/reserved-slugs.tsindex a0d7c9c913..91836eeba8 100644--- a/packages/core/paths/reserved-slugs.ts+++ b/packages/core/paths/reserved-slugs.ts@@ -300,6 +300,7 @@ export const RESERVED_SLUGS: ReadonlySet<string> = new Set(["usage","runtimes","skills",+ "apps","settings","workspaces","teams",diff --git a/packages/core/paths/route-icons.ts b/packages/core/paths/route-icons.tsindex 7e8d028963..ff631b4f7b 100644--- a/packages/core/paths/route-icons.ts+++ b/packages/core/paths/route-icons.ts@@ -33,6 +33,7 @@ export type RouteIconName =| "Monitor"| "Server"| "BookOpenText"+ | "Plug"| "Settings"| "File"| "FileText"@@ -58,6 +59,7 @@ export type NavLabelKey =| "runtimes"| "docs"| "skills"+ | "apps"| "settings";/** Stable identifier for each workspace navigation page. */@@ -75,6 +77,7 @@ export type WorkspacePageKey =| "runtimes"| "docs"| "skills"+ | "apps"| "settings";export interface WorkspacePage {@@ -104,6 +107,7 @@ export const WORKSPACE_PAGES: Record<WorkspacePageKey, WorkspacePage> = {runtimes: { segment: "runtimes", icon: "Monitor", navKey: "runtimes" },docs: { segment: "docs", icon: "FileText", navKey: "docs" },skills: { segment: "skills", icon: "BookOpenText", navKey: "skills" },+ apps: { segment: "apps", icon: "Plug", navKey: "apps" },settings: { segment: "settings", icon: "Settings", navKey: "settings" },};diff --git a/packages/core/paths/spaces.test.ts b/packages/core/paths/spaces.test.tsindex e57d785274..dbc34763d2 100644--- a/packages/core/paths/spaces.test.ts+++ b/packages/core/paths/spaces.test.ts@@ -25,6 +25,7 @@ describe("spaceForPath", () => {[ws.memberDetail("m-1"), "team"],[ws.runtimeDetail("r-1"), "team"],[ws.skills(), "team"],+ [ws.appDetail("gmail"), "team"],[ws.usage(), "team"],[ws.chatSession("c-1"), "chat"],[ws.autopilotDetail("ap-1"), "autopilots"],diff --git a/packages/core/paths/spaces.ts b/packages/core/paths/spaces.tsindex dada61af7b..0d72e426cd 100644--- a/packages/core/paths/spaces.ts+++ b/packages/core/paths/spaces.ts@@ -38,6 +38,7 @@ const SPACE_BY_SEGMENT: Record<string, AppSpaceId> = {members: "team",skills: "team",docs: "docs",+ apps: "team",runtimes: "team",usage: "team",chat: "chat",diff --git a/packages/core/paths/tab-presentation.test.ts b/packages/core/paths/tab-presentation.test.tsindex ff1d8bced6..e6e985e44f 100644--- a/packages/core/paths/tab-presentation.test.ts+++ b/packages/core/paths/tab-presentation.test.ts@@ -79,7 +79,7 @@ describe("resolveTabPresentation — direct resources", () => {});});- it("autopilot / skill / machine / runtime use a type icon + name", () => {+ it("autopilot / skill / app / machine / runtime use a type icon + name", () => {expect(present("/acme/autopilots/a1", { autopilot: { title: "Nightly" } })).toEqual({visual: { kind: "icon", icon: "Zap" },title: { kind: "text", text: "Nightly" },@@ -88,6 +88,11 @@ describe("resolveTabPresentation — direct resources", () => {visual: { kind: "icon", icon: "BookOpenText" },title: { kind: "text", text: "Deploy" },});+ expect(present("/acme/apps/gmail", { app: { name: "Gmail" } })).toEqual({+ visual: { kind: "icon", icon: "Plug" },+ title: { kind: "text", text: "Gmail" },+ });+ expect(present("/acme/apps/gmail").title).toEqual({ kind: "tab", tabKey: "app" });expect(present("/acme/runtimes/m1", { machine: { name: "Mac Studio" } })).toEqual({visual: { kind: "icon", icon: "Monitor" },title: { kind: "text", text: "Mac Studio" },diff --git a/packages/core/paths/tab-presentation.ts b/packages/core/paths/tab-presentation.tsindex b8464a40ff..ade5069a9a 100644--- a/packages/core/paths/tab-presentation.ts+++ b/packages/core/paths/tab-presentation.ts@@ -49,6 +49,7 @@ export type TabLabelKey =| "doc"| "docFolder"| "skill"+ | "app"| "machine"| "runtime"| "attachment"@@ -89,6 +90,7 @@ export interface TabEntityData {skill?: { name: string };doc?: {title: string};docFolder?: {title: string};+ app?: { name: string };machine?: { name: string };runtime?: { name: string };/** Resolved chat session title (already includes the "New chat" fallback). */@@ -200,6 +202,11 @@ export function resolveTabPresentation(visual: { kind: "icon", icon: "BookOpenText" },title: textOr(data.skill?.name, "skill"),};+ case "app":+ return {+ visual: { kind: "icon", icon: "Plug" },+ title: textOr(data.app?.name, "app"),+ };case "machine":return {visual: { kind: "icon", icon: "Monitor" },diff --git a/packages/core/paths/tab-subject.test.ts b/packages/core/paths/tab-subject.test.tsindex 6a5563bf2f..05f14f028b 100644--- a/packages/core/paths/tab-subject.test.ts+++ b/packages/core/paths/tab-subject.test.ts@@ -19,12 +19,14 @@ describe("parseTabSubject", () => {["/acme/usage", { kind: "page", page: "usage" }],["/acme/runtimes", { kind: "page", page: "runtimes" }],["/acme/skills", { kind: "page", page: "skills" }],+ ["/acme/apps", { kind: "page", page: "apps" }],["/acme/settings", { kind: "page", page: "settings" }],// Resource details["/acme/issues/bug-1", { kind: "issue", id: "bug-1" }],["/acme/projects/p1", { kind: "project", id: "p1" }],["/acme/autopilots/a1", { kind: "autopilot", id: "a1" }],["/acme/skills/s1", { kind: "skill", id: "s1" }],+ ["/acme/apps/gmail", { kind: "app", slug: "gmail" }],["/acme/attachments/att1/preview", { kind: "attachment", id: "att1", filename: null }],["/acme/attachments/att1/preview?name=report.pdf",diff --git a/packages/core/paths/tab-subject.ts b/packages/core/paths/tab-subject.tsindex 4fb1a1bc6c..ed0850fdc3 100644--- a/packages/core/paths/tab-subject.ts+++ b/packages/core/paths/tab-subject.ts@@ -35,6 +35,8 @@ export type TabSubject =| { kind: "skill"; id: string }| { kind: "doc"; id: string }| { kind: "docFolder"; id: string }+ /** One app's page, addressed by its toolkit slug. */+ | { kind: "app"; slug: string }/** A runtime machine detail. */| { kind: "machine"; machineId: string }/** A runtime nested under a machine. */@@ -127,6 +129,8 @@ export function parseTabSubject(url: string): TabSubject {return id ? { kind: "doc", id } : { kind: "page", page: "docs" };case "skills":return id ? { kind: "skill", id } : { kind: "page", page: "skills" };+ case "apps":+ return id ? { kind: "app", slug: id } : { kind: "page", page: "apps" };case "settings":return { kind: "page", page: "settings" };case "attachments":@@ -169,6 +173,8 @@ export function tabSubjectKey(subject: TabSubject): string {return `doc:${subject.id}`;case "docFolder":return `docFolder:${subject.id}`;+ case "app":+ return `app:${subject.slug}`;case "machine":return `machine:${subject.machineId}`;case "runtime":diff --git a/packages/core/types/connected-apps.ts b/packages/core/types/connected-apps.tsindex 1e3b121f81..222230205f 100644--- a/packages/core/types/connected-apps.ts+++ b/packages/core/types/connected-apps.ts@@ -37,6 +37,19 @@ export interface AgentApp {level: AppAccessLevel;}+/** Everything waiting for a team account for one app: agents' runs and+ * members' asks. */+export interface AppTeamRequest {+ toolkit_slug: string;+ /** People waiting: whoever started each run, and members who asked. */+ requested_by: string[];+ /** Members who asked themselves; they can withdraw it. */+ asked_by?: string[];+ /** Agents waiting on it, or that members wanted it for; may be empty. */+ agent_ids: string[];+ last_requested_at: string;+}+export interface AppsOverview {catalog_mode: AppCatalogMode;/** The apps of a custom catalog. */@@ -46,6 +59,20 @@ export interface AppsOverview {team: AppConnection[];personal: AppConnection[];agent_apps: AgentApp[];+ /** Open requests for team accounts the workspace has not connected. */+ team_requests?: AppTeamRequest[];+}++/** What disconnecting one of the caller's accounts stops in its workspace. */+export interface PersonalAppImpact {+ agents: {+ id: string;+ name: string;+ workspace_id: string;+ workspace_name: string;+ /** A run the caller started is using the agent right now. */+ running: boolean;+ }[];}export interface AppCatalogEntry {@@ -156,6 +183,12 @@ export interface AppRequest {error: string | null;reason: string | null;redacted: boolean;+ /** A connect request for an app the agent does not have yet; answering it+ * adds the app to the agent. */+ adds_app?: boolean;+ /** Whether the viewer may answer it: any admin for a team account request,+ * otherwise the approver. Older servers omit it. */+ can_decide?: boolean;expires_at: string;decided_by: string | null;decided_at: string | null;diff --git a/packages/core/types/index.ts b/packages/core/types/index.tsindex f243e2a2af..72d59db195 100644--- a/packages/core/types/index.ts+++ b/packages/core/types/index.ts@@ -309,6 +309,8 @@ export type {AppCallOutcome,IssueAppCall,TeamAppImpact,+ PersonalAppImpact,+ AppTeamRequest,AppRequestStatus,AppRequest,AppRequestList,diff --git a/packages/views/agents/components/add-agent-app-dialog.tsx b/packages/views/agents/components/add-agent-app-dialog.tsxnew file mode 100644index 0000000000..b5928b75c2--- /dev/null+++ b/packages/views/agents/components/add-agent-app-dialog.tsx@@ -0,0 +1,179 @@+"use client";++import { useMemo, useState } from "react";+import { useQuery } from "@tanstack/react-query";+import { toast } from "sonner";+import { Loader2, Plus } from "@multica/ui/icons";+import { Badge } from "@multica/ui/components/ui/badge";+import { Button } from "@multica/ui/components/ui/button";+import {+ Dialog,+ DialogContent,+ DialogDescription,+ DialogHeader,+ DialogTitle,+} from "@multica/ui/components/ui/dialog";+import { Input } from "@multica/ui/components/ui/input";+import { useWorkspaceId } from "@multica/core/hooks";+import {+ agentAppsOptions,+ appCatalogOptions,+ appsOverviewOptions,+ useUpdateAgentApps,+} from "@multica/core/connected-apps";+import type { Agent, AppCatalogEntry } from "@multica/core/types";+import { appAccountStatus } from "../../common/app-status";+import { ComposioToolkitLogo } from "../../common/composio-toolkit-logo";+import { useT } from "../../i18n";+import { useTeamAppAccess } from "../../common/use-team-app-access";+import { scopeForNewApp } from "./agent-app-status";+import { useAppStatusLabel } from "./use-agent-apps";++/**+ * Adds one catalog app to the agent. The account it uses is decided for the+ * viewer (`scopeForNewApp`); a personal-account app needs no account of the+ * viewer's own, since each run uses whoever starts it.+ */+export function AddAgentAppDialog({+ agent,+ open,+ onOpenChange,+}: {+ agent: Agent;+ open: boolean;+ onOpenChange: (open: boolean) => void;+}) {+ const { t } = useT("agents");+ const wsId = useWorkspaceId();+ const appsQuery = useQuery({ ...agentAppsOptions(wsId, agent.id), enabled: open });+ const overview = useQuery({ ...appsOverviewOptions(wsId), enabled: open });+ const catalog = useQuery({ ...appCatalogOptions(wsId), enabled: open });+ const update = useUpdateAgentApps(agent.id);+ const statusLabel = useAppStatusLabel();+ const teamAccess = useTeamAppAccess(overview.data);+ const [query, setQuery] = useState("");+ const [adding, setAdding] = useState<string | null>(null);++ const available = useMemo(() => {+ const onAgent = new Set((appsQuery.data ?? []).map((a) => a.toolkit_slug));+ return (catalog.data?.apps ?? []).filter((app) => app.allowed !== false && !onAgent.has(app.slug));+ }, [appsQuery.data, catalog.data]);++ const mixedCatalog = available.some((app) => app.curated) && available.some((app) => !app.curated);+ const filtered = useMemo(() => {+ const q = query.trim().toLowerCase();+ if (!q) return available;+ return available.filter(+ (app) =>+ app.name.toLowerCase().includes(q) ||+ app.slug.includes(q) ||+ (app.category ?? "").toLowerCase().includes(q),+ );+ }, [available, query]);++ const ready = appsQuery.isSuccess && overview.isSuccess;++ const add = (app: AppCatalogEntry) => {+ const current = appsQuery.data;+ if (!current || !overview.data || adding) return;+ const name = app.name || app.slug;+ setAdding(app.slug);+ update+ .mutateAsync({+ apps: [+ ...current.map((a) => ({+ toolkit_slug: a.toolkit_slug,+ account_scope: a.account_scope,+ level: a.level,+ })),+ {+ toolkit_slug: app.slug,+ account_scope: scopeForNewApp(overview.data, app.slug, app.recommended_scope, teamAccess.canAdd),+ level: "write",+ },+ ],+ })+ .then(+ () => {+ toast.success(t(($) => $.add_app_dialog.added_toast, { app: name, agent: agent.name }));+ onOpenChange(false);+ },+ (e: unknown) =>+ toast.error(e instanceof Error && e.message ? e.message : t(($) => $.tab_body.connected_apps.save_failed_toast)),+ )+ .finally(() => setAdding(null));+ };++ const hint = (app: AppCatalogEntry) => {+ const scope = scopeForNewApp(overview.data, app.slug, app.recommended_scope, teamAccess.canAdd);+ const status = scope === "team"+ ? t(($) => $.add_app_dialog.team_connected)+ : statusLabel(appAccountStatus(overview.data, "personal", app.slug));+ const usual = app.recommended_scope === "team"+ ? t(($) => $.add_app_dialog.recommended_team)+ : app.recommended_scope === "personal"+ ? t(($) => $.add_app_dialog.recommended_personal)+ : app.category;+ return [usual, overview.isSuccess ? status : null].filter(Boolean).join(" · ");+ };++ return (+ <Dialog+ open={open}+ onOpenChange={(next) => {+ if (!next) setQuery("");+ onOpenChange(next);+ }}+ >+ <DialogContent className="sm:max-w-xl">+ <DialogHeader>+ <DialogTitle>{t(($) => $.add_app_dialog.title, { agent: agent.name })}</DialogTitle>+ <DialogDescription>{t(($) => $.add_app_dialog.description)}</DialogDescription>+ </DialogHeader>+ <Input+ autoFocus+ value={query}+ onChange={(e) => setQuery(e.target.value)}+ placeholder={t(($) => $.add_app_dialog.search, { count: available.length })}+ aria-label={t(($) => $.add_app_dialog.search_label)}+ />+ <div className="max-h-[60vh] min-h-48 overflow-y-auto rounded-lg border">+ {catalog.isLoading || appsQuery.isLoading ? (+ <p className="p-4 text-caption text-muted-foreground">{t(($) => $.tab_body.connected_apps.loading)}</p>+ ) : catalog.isError || appsQuery.isError ? (+ <p className="p-4 text-caption text-destructive">{t(($) => $.add_app_dialog.load_failed)}</p>+ ) : filtered.length === 0 ? (+ <p className="p-4 text-caption text-muted-foreground">{t(($) => $.add_app_dialog.empty)}</p>+ ) : (+ <ul className="divide-y">+ {filtered.map((app) => (+ <li key={app.slug} className="flex items-center gap-3 px-3 py-2.5">+ <ComposioToolkitLogo slug={app.slug} name={app.name} fallbackLogo={app.logo} />+ <div className="min-w-0 flex-1">+ <p className="flex items-center gap-2 truncate text-body font-medium">+ {app.name || app.slug}+ {mixedCatalog && app.curated && <Badge variant="secondary">{t(($) => $.add_app_dialog.curated)}</Badge>}+ </p>+ <p className="truncate text-caption text-muted-foreground">{hint(app)}</p>+ </div>+ <Button+ size="xs"+ variant="outline"+ className="shrink-0"+ disabled={!ready || adding !== null}+ aria-busy={adding === app.slug}+ aria-label={t(($) => $.add_app_dialog.add_aria, { app: app.name || app.slug })}+ onClick={() => add(app)}+ >+ {adding === app.slug ? <Loader2 className="animate-spin" /> : <Plus />}+ {t(($) => $.add_app_dialog.add)}+ </Button>+ </li>+ ))}+ </ul>+ )}+ </div>+ </DialogContent>+ </Dialog>+ );+}diff --git a/packages/views/agents/components/agent-app-status.test.ts b/packages/views/agents/components/agent-app-status.test.tsnew file mode 100644index 0000000000..d1cef21896--- /dev/null+++ b/packages/views/agents/components/agent-app-status.test.ts@@ -0,0 +1,58 @@+// @vitest-environment node++import { describe, expect, it } from "vitest";+import type { AppConnection, AppsOverview } from "@multica/core/types";+import { needsViewerAccount, scopeForNewApp } from "./agent-app-status";++function account(status: string): AppConnection {+ return { id: `c-${status}`, toolkit_slug: "slack", status, connected_at: "", last_used_at: null };+}++function overview({+ admin,+ team,+ personal,+}: {+ admin: boolean;+ team?: string;+ personal?: string;+}): AppsOverview {+ return {+ catalog_mode: "all",+ can_manage: admin,+ team: team ? [account(team)] : [],+ personal: personal ? [account(personal)] : [],+ agent_apps: [],+ };+}++describe("scopeForNewApp", () => {+ it.each([+ { name: "admin, team account, usually team", admin: true, team: "active", personal: "active", recommended: "team", scope: "team" },+ { name: "admin, team account, no account of their own", admin: true, team: "active", personal: undefined, recommended: undefined, scope: "team" },+ { name: "admin, team account, own account, not usually team", admin: true, team: "active", personal: "active", recommended: "personal", scope: "personal" },+ { name: "admin, team account, own account expired", admin: true, team: "active", personal: "expired", recommended: undefined, scope: "team" },+ { name: "admin, expired team account", admin: true, team: "expired", personal: undefined, recommended: "team", scope: "personal" },+ { name: "admin, no team account", admin: true, team: undefined, personal: undefined, recommended: "team", scope: "personal" },+ { name: "member, team account, usually team", admin: false, team: "active", personal: undefined, recommended: "team", scope: "personal" },+ ] as const)("$name → $scope", ({ admin, team, personal, recommended, scope }) => {+ expect(scopeForNewApp(overview({ admin, team, personal }), "slack", recommended, true)).toBe(scope);+ });++ it("falls back to personal before the overview loads", () => {+ expect(scopeForNewApp(undefined, "slack", "team", true)).toBe("personal");+ });++ it("keeps new apps off the team account while the plan lacks team accounts", () => {+ expect(scopeForNewApp(overview({ admin: true, team: "active" }), "slack", "team", false)).toBe("personal");+ });+});++describe("needsViewerAccount", () => {+ it("flags personal-account apps the viewer has not connected or must reconnect", () => {+ expect(needsViewerAccount("personal", "not_connected")).toBe(true);+ expect(needsViewerAccount("personal", "needs_reconnecting")).toBe(true);+ expect(needsViewerAccount("personal", "connected")).toBe(false);+ expect(needsViewerAccount("team", "not_connected")).toBe(false);+ });+});diff --git a/packages/views/agents/components/agent-app-status.ts b/packages/views/agents/components/agent-app-status.tsnew file mode 100644index 0000000000..8d5a5ffa20--- /dev/null+++ b/packages/views/agents/components/agent-app-status.ts@@ -0,0 +1,30 @@+import type { AppAccountScope, AppsOverview } from "@multica/core/types";+import { appAccountStatus, type AppAccountStatus } from "../../common/app-status";++/**+ * The account a newly added app uses. Only an admin can give an agent the+ * team account, only one the workspace has connected, and only while the plan+ * includes team accounts (`canAddTeam`); it wins when the app is usually a+ * team app or the admin has no account of their own.+ */+export function scopeForNewApp(+ overview: AppsOverview | undefined,+ slug: string,+ recommended: AppAccountScope | undefined,+ canAddTeam: boolean,+): AppAccountScope {+ if (!overview?.can_manage || !canAddTeam) return "personal";+ if (appAccountStatus(overview, "team", slug) !== "connected") return "personal";+ if (recommended === "team") return "team";+ return appAccountStatus(overview, "personal", slug) === "connected" ? "personal" : "team";+}++/** The Properties panel's Apps line scrolls to this element. */+export function agentAppsSectionId(agentId: string) {+ return `agent-apps-${agentId}`;+}++/** A personal-account app the viewer cannot run the agent with yet. */+export function needsViewerAccount(scope: AppAccountScope, status: AppAccountStatus): boolean {+ return scope === "personal" && status !== "connected";+}diff --git a/packages/views/agents/components/agent-apps-property.tsx b/packages/views/agents/components/agent-apps-property.tsxnew file mode 100644index 0000000000..81086bbbde--- /dev/null+++ b/packages/views/agents/components/agent-apps-property.tsx@@ -0,0 +1,50 @@+"use client";++import { AlertTriangle, Plug } from "@multica/ui/icons";+import { cn } from "@multica/ui/lib/utils";+import type { Agent } from "@multica/core/types";+import { ObjectProperty } from "../../layout/object-page";+import { useT } from "../../i18n";+import { agentAppsSectionId, needsViewerAccount } from "./agent-app-status";+import { CHIP_CLASS } from "./inspector/chip";+import { useAgentApps } from "./use-agent-apps";++/** The agent's apps in one line, leading with the ones the viewer still has+ * to connect; it takes the viewer to the Apps section. */+export function AgentAppsProperty({ agent }: { agent: Agent }) {+ const { t } = useT("agents");+ const { rows, isLoading, isError } = useAgentApps(agent.id);+ const missing = rows.filter((row) => needsViewerAccount(row.app.account_scope, row.status)).length;++ const value = isLoading || isError+ ? "—"+ : missing > 0+ ? t(($) => $.panel.apps_needs_account, { count: missing })+ : rows.length > 0+ ? t(($) => $.panel.apps_count, { count: rows.length })+ : t(($) => $.panel.apps_none);++ const show = () => {+ const section = document.getElementById(agentAppsSectionId(agent.id));+ section?.scrollIntoView({ block: "start", behavior: "smooth" });+ section?.focus({ preventScroll: true });+ };++ const Icon = missing > 0 ? AlertTriangle : Plug;+ return (+ <ObjectProperty label={t(($) => $.panel.apps)}>+ <button+ type="button"+ className={cn(CHIP_CLASS, missing > 0 && "text-warning")}+ onClick={show}+ aria-label={t(($) => $.panel.apps_aria, { value })}+ >+ <Icon+ className={cn("size-3.5 shrink-0", missing > 0 ? "text-warning" : "text-muted-foreground")}+ aria-hidden="true"+ />+ <span className="truncate">{value}</span>+ </button>+ </ObjectProperty>+ );+}diff --git a/packages/views/agents/components/agent-apps-section.test.tsx b/packages/views/agents/components/agent-apps-section.test.tsxnew file mode 100644index 0000000000..1c7f63f152--- /dev/null+++ b/packages/views/agents/components/agent-apps-section.test.tsx@@ -0,0 +1,211 @@+import { afterEach, beforeEach, describe, 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 { Agent, AgentApp, AppsOverview } from "@multica/core/types";+import { getTestResources } from "../../test/i18n";+import { NavigationProvider, type NavigationAdapter } from "../../navigation";+import { AgentAppsSection } from "./agent-apps-section";++const toast = vi.hoisted(() => ({ success: vi.fn(), error: vi.fn() }));+vi.mock("sonner", () => ({ toast }));+vi.mock("@multica/core/api", () => ({ api: {+ listAgentApps: vi.fn(), getAppsOverview: vi.fn(), listAppCatalog: vi.fn(),+ updateAgentApps: vi.fn(), requestTeamApp: vi.fn(),+} }));+vi.mock("@multica/core/hooks", () => ({ useWorkspaceId: () => "ws-1" }));+vi.mock("@multica/core/workspace/hooks", () => ({ useActorName: () => ({ getActorName: () => "Ops Assistant" }) }));+vi.mock("@multica/core/auth", () => {+ const state = () => ({ user: { id: "me" } });+ return { useAuthStore: Object.assign((sel: (s: ReturnType<typeof state>) => unknown) => sel(state()), { getState: state }) };+});++const agent = { id: "a1", name: "Ops Assistant" } as Agent;+let apps: AgentApp[];+let overview: AppsOverview;+const active = (slug: string) => ({ id: `c-${slug}`, toolkit_slug: slug, status: "active", connected_at: "", last_used_at: null });++beforeEach(() => {+ apps = [+ { agent_id: "a1", toolkit_slug: "gmail", account_scope: "personal", level: "write" },+ { agent_id: "a1", toolkit_slug: "googlecalendar", account_scope: "personal", level: "write" },+ { agent_id: "a1", toolkit_slug: "sentry", account_scope: "team", level: "read" },+ { agent_id: "a1", toolkit_slug: "posthog", account_scope: "team", level: "write" },+ ];+ overview = {+ catalog_mode: "all", can_manage: false,+ team: [active("sentry"), active("slack")],+ personal: [active("gmail")],+ agent_apps: apps,+ };+ vi.mocked(api.listAgentApps).mockImplementation(async () => ({ apps }));+ vi.mocked(api.getAppsOverview).mockImplementation(async () => overview);+ vi.mocked(api.listAppCatalog).mockResolvedValue({+ catalog_mode: "all",+ apps: [+ { slug: "slack", name: "Slack", curated: true, recommended_scope: "team" },+ { slug: "linear", name: "Linear", curated: true, category: "Issues" },+ { slug: "gmail", name: "Gmail", curated: true },+ { slug: "googlecalendar", name: "Google Calendar", curated: true },+ { slug: "sentry", name: "Sentry", curated: true },+ { slug: "posthog", name: "PostHog", curated: false },+ { slug: "hidden", name: "Hidden", curated: false, allowed: false },+ ],+ });+ vi.mocked(api.updateAgentApps).mockImplementation(async (_id, body) => ({ apps: body.apps.map((app) => ({ ...app, agent_id: "a1" })) }));+ vi.mocked(api.requestTeamApp).mockResolvedValue(undefined);+});++afterEach(() => {+ cleanup();+ vi.clearAllMocks();+});++function renderSection({ canEdit = true }: { canEdit?: boolean } = {}) {+ const onManage = vi.fn();+ const navigation: NavigationAdapter = {+ push: vi.fn(), replace: vi.fn(), back: vi.fn(),+ pathname: "/ws/agents/a1", searchParams: new URLSearchParams(), hash: "",+ getShareableUrl: (p) => p,+ };+ render(+ <QueryClientProvider client={new QueryClient({ defaultOptions: { queries: { retry: false } } })}>+ <I18nProvider locale="en" resources={getTestResources()}>+ <NavigationProvider value={navigation}>+ <AgentAppsSection agent={agent} canEdit={canEdit} onManage={onManage} />+ </NavigationProvider>+ </I18nProvider>+ </QueryClientProvider>,+ );+ return { onManage };+}++const row = (scope: "team" | "personal", slug: string) =>+ document.querySelector(`[data-account-row="${scope}:${slug}"]`) as HTMLElement;++describe("AgentAppsSection", () => {+ it("says whose account each app acts as and where it stands, with one action each", async () => {+ renderSection();+ await screen.findByText("Google Calendar");+ expect(row("personal", "gmail")).toHaveTextContent("Acts as whoever starts the run");+ expect(row("personal", "gmail")).toHaveTextContent("Connected");+ expect(within(row("personal", "gmail")).queryByRole("button", { name: /Connect|Reconnect/ })).not.toBeInTheDocument();+ expect(row("personal", "googlecalendar")).toHaveTextContent("Not connected");+ expect(within(row("personal", "googlecalendar")).getByRole("button", { name: "Connect" })).toBeVisible();+ expect(row("team", "sentry")).toHaveTextContent("Acts as the team account");+ expect(within(row("team", "sentry")).queryByRole("button")).not.toBeInTheDocument();+ expect(row("team", "posthog")).toHaveTextContent("Not connected");+ expect(within(row("team", "posthog")).getByRole("button", { name: "Ask an admin" })).toBeVisible();+ });++ it("opens the pre-connect notice for the viewer's own account", async () => {+ const user = userEvent.setup();+ renderSection();+ await screen.findByText("Google Calendar");+ await user.click(within(row("personal", "googlecalendar")).getByRole("button", { name: "Connect" }));+ const dialog = await screen.findByRole("dialog", { name: "Connect Google Calendar" });+ expect(dialog).toHaveTextContent("Your own account");+ expect(api.requestTeamApp).not.toHaveBeenCalled();+ });++ it("asks an admin for a team account on behalf of this agent, then lets the asker withdraw", async () => {+ vi.mocked(api.requestTeamApp).mockImplementation(async () => {+ overview.team_requests = [{ toolkit_slug: "posthog", requested_by: ["me"], asked_by: ["me"], agent_ids: ["a1"], last_requested_at: "" }];+ });+ const user = userEvent.setup();+ renderSection();+ await screen.findByText("PostHog");+ await user.click(within(row("team", "posthog")).getByRole("button", { name: "Ask an admin" }));+ expect(api.requestTeamApp).toHaveBeenCalledWith("posthog", "a1");+ await waitFor(() => expect(row("team", "posthog")).toHaveTextContent("Requested · admins notified"));+ expect(within(row("team", "posthog")).getByRole("button", { name: "Withdraw" })).toBeVisible();+ expect(toast.success).toHaveBeenCalled();+ });++ it("offers admins the team account instead of a request", async () => {+ overview.can_manage = true;+ const user = userEvent.setup();+ renderSection();+ await screen.findByText("PostHog");+ await user.click(within(row("team", "posthog")).getByRole("button", { name: "Connect" }));+ expect(await screen.findByRole("dialog", { name: "Connect PostHog" })).toHaveTextContent("A team account the whole workspace shares");+ });++ it("is read-only for someone who cannot edit the agent", async () => {+ renderSection({ canEdit: false });+ await screen.findByText("Google Calendar");+ expect(screen.queryByRole("button", { name: "Manage" })).not.toBeInTheDocument();+ expect(screen.queryByRole("button", { name: "Add" })).not.toBeInTheDocument();+ expect(within(row("personal", "googlecalendar")).getByRole("button", { name: "Connect" })).toBeVisible();+ });++ it("offers Add from the empty state", async () => {+ apps = [];+ renderSection();+ expect(await screen.findByText("This agent doesn't use any apps yet.")).toBeVisible();+ expect(screen.getAllByRole("button", { name: "Add" })).toHaveLength(2);+ });++ it("opens advanced settings from Manage", async () => {+ const user = userEvent.setup();+ const { onManage } = renderSection();+ await screen.findByText("Gmail");+ await user.click(screen.getByRole("button", { name: "Manage" }));+ expect(onManage).toHaveBeenCalledTimes(1);+ });+});++describe("AddAgentAppDialog", () => {+ it("lists the catalog apps not on the agent and adds one, keeping the others", async () => {+ const user = userEvent.setup();+ renderSection();+ await screen.findByText("Gmail");+ await user.click(screen.getByRole("button", { name: "Add" }));+ const dialog = await screen.findByRole("dialog", { name: "Add an app to Ops Assistant" });+ expect(within(dialog).getByPlaceholderText("Search 2 apps")).toBeVisible();+ expect(within(dialog).queryByText("Gmail")).not.toBeInTheDocument();+ expect(within(dialog).queryByText("Hidden")).not.toBeInTheDocument();+ expect(within(dialog).getByText("Linear").closest("li")).toHaveTextContent("Issues · Not connected");++ await user.click(within(dialog).getByRole("button", { name: "Add Linear" }));+ await waitFor(() => expect(api.updateAgentApps).toHaveBeenCalledWith("a1", {+ apps: [+ { toolkit_slug: "gmail", account_scope: "personal", level: "write" },+ { toolkit_slug: "googlecalendar", account_scope: "personal", level: "write" },+ { toolkit_slug: "sentry", account_scope: "team", level: "read" },+ { toolkit_slug: "posthog", account_scope: "team", level: "write" },+ { toolkit_slug: "linear", account_scope: "personal", level: "write" },+ ],+ }));+ await waitFor(() => expect(screen.queryByRole("dialog")).not.toBeInTheDocument());+ expect(toast.success).toHaveBeenCalledWith("Added Linear to Ops Assistant.");+ });++ it("gives an admin's add the team account when the app is usually a team app", async () => {+ overview.can_manage = true;+ const user = userEvent.setup();+ renderSection();+ await screen.findByText("Gmail");+ await user.click(screen.getByRole("button", { name: "Add" }));+ const dialog = await screen.findByRole("dialog");+ expect(within(dialog).getByText("Slack").closest("li")).toHaveTextContent("Usually a team account · Team account connected");+ await user.click(within(dialog).getByRole("button", { name: "Add Slack" }));+ await waitFor(() => expect(api.updateAgentApps).toHaveBeenCalledWith("a1", {+ apps: expect.arrayContaining([{ toolkit_slug: "slack", account_scope: "team", level: "write" }]),+ }));+ });++ it("stays open with an error when saving fails", async () => {+ vi.mocked(api.updateAgentApps).mockRejectedValueOnce(new Error("offline"));+ const user = userEvent.setup();+ renderSection();+ await screen.findByText("Gmail");+ await user.click(screen.getByRole("button", { name: "Add" }));+ const dialog = await screen.findByRole("dialog");+ await user.click(within(dialog).getByRole("button", { name: "Add Linear" }));+ await waitFor(() => expect(toast.error).toHaveBeenCalledWith("offline"));+ expect(screen.getByRole("dialog")).toBeVisible();+ });+});diff --git a/packages/views/agents/components/agent-apps-section.tsx b/packages/views/agents/components/agent-apps-section.tsxnew file mode 100644index 0000000000..8e439873fe--- /dev/null+++ b/packages/views/agents/components/agent-apps-section.tsx@@ -0,0 +1,147 @@+"use client";++import { useState } from "react";+import { Plug, Plus, Settings2 } from "@multica/ui/icons";+import { Button } from "@multica/ui/components/ui/button";+import type { Agent, AppAccountScope, AppConnection } from "@multica/core/types";+import { ConnectAppDialog } from "../../common/connect-app-dialog";+import { AccountOwner, AccountRow } from "../../apps/components/account-row";+import { AppAccountDialog } from "../../apps/components/app-account-dialog";+import { DisconnectAccountDialog } from "../../apps/components/disconnect-account-dialog";+import {+ ObjectSection,+ ObjectSectionAction,+ ObjectSectionEmpty,+} from "../../layout/object-page";+import { useT } from "../../i18n";+import { AddAgentAppDialog } from "./add-agent-app-dialog";+import { agentAppsSectionId } from "./agent-app-status";+import { useAgentApps, type AgentAppRow } from "./use-agent-apps";++type RowTarget = { scope: AppAccountScope; row: AgentAppRow };++/**+ * The apps the agent works in, whose account each acts as, and where that+ * account stands for the viewer. Everyone sees it; only editors change the+ * list, while anyone can connect their own account or ask an admin for a+ * team one.+ */+export function AgentAppsSection({+ agent,+ canEdit,+ onManage,+}: {+ agent: Agent;+ canEdit: boolean;+ onManage: () => void;+}) {+ const { t } = useT("agents");+ const { rows, overview, isLoading, isError } = useAgentApps(agent.id);+ const [adding, setAdding] = useState(false);+ const [connect, setConnect] = useState<RowTarget | null>(null);+ const [activity, setActivity] = useState<RowTarget | null>(null);+ const [disconnecting, setDisconnecting] = useState<(RowTarget & { connection: AppConnection }) | null>(null);++ return (+ <div id={agentAppsSectionId(agent.id)} tabIndex={-1} className="scroll-mt-6 outline-none">+ <ObjectSection+ title={t(($) => $.apps_section.title)}+ count={isLoading || isError ? undefined : rows.length}+ action={+ canEdit ? (+ <>+ <ObjectSectionAction icon={Settings2} onClick={onManage}>+ {t(($) => $.sections.manage)}+ </ObjectSectionAction>+ <ObjectSectionAction icon={Plus} onClick={() => setAdding(true)} disabled={isLoading || isError}>+ {t(($) => $.sections.add)}+ </ObjectSectionAction>+ </>+ ) : null+ }+ >+ {isLoading ? (+ <p className="text-body text-muted-foreground">{t(($) => $.tab_body.connected_apps.loading)}</p>+ ) : isError || !overview ? (+ <p className="text-body text-destructive">{t(($) => $.tab_body.connected_apps.load_failed)}</p>+ ) : rows.length === 0 ? (+ <ObjectSectionEmpty+ icon={Plug}+ description={t(($) => $.apps_section.empty)}+ action={+ canEdit ? (+ <Button size="xs" variant="outline" onClick={() => setAdding(true)}>+ <Plus />+ {t(($) => $.sections.add)}+ </Button>+ ) : undefined+ }+ />+ ) : (+ <div className="divide-y overflow-hidden rounded-lg border bg-card">+ {rows.map((row) => {+ const scope = row.app.account_scope;+ return (+ <AccountRow+ key={row.app.toolkit_slug}+ className="px-3 py-2"+ scope={scope}+ slug={row.app.toolkit_slug}+ name={row.name}+ logo={row.logo}+ showLogo+ overview={overview}+ agentId={agent.id}+ title={row.name}+ subtitle={+ <AccountOwner+ scope={scope}+ label={scope === "team" ? t(($) => $.apps_section.acts_as_team) : t(($) => $.apps_section.acts_as_starter)}+ />+ }+ on={{+ connect: () => setConnect({ scope, row }),+ activity: () => setActivity({ scope, row }),+ disconnect: (_, connection) => setDisconnecting({ scope, row, connection }),+ }}+ />+ );+ })}+ </div>+ )}+ </ObjectSection>++ {canEdit && <AddAgentAppDialog agent={agent} open={adding} onOpenChange={setAdding} />}+ {connect && (+ <ConnectAppDialog+ open+ onOpenChange={(open) => {+ if (!open) setConnect(null);+ }}+ scope={connect.scope}+ slug={connect.row.app.toolkit_slug}+ name={connect.row.name}+ logo={connect.row.logo}+ />+ )}+ {activity && (+ <AppAccountDialog+ scope={activity.scope}+ slug={activity.row.app.toolkit_slug}+ name={activity.row.name}+ onClose={() => setActivity(null)}+ />+ )}+ {disconnecting && (+ <DisconnectAccountDialog+ scope={disconnecting.scope}+ connectionId={disconnecting.connection.id}+ slug={disconnecting.row.app.toolkit_slug}+ name={disconnecting.row.name}+ logo={disconnecting.row.logo}+ onClose={() => setDisconnecting(null)}+ />+ )}+ </div>+ );+}diff --git a/packages/views/agents/components/agent-detail-page.test.tsx b/packages/views/agents/components/agent-detail-page.test.tsxindex 7f25e223e3..6651dbe6b3 100644--- a/packages/views/agents/components/agent-detail-page.test.tsx+++ b/packages/views/agents/components/agent-detail-page.test.tsx@@ -11,6 +11,8 @@ import {} from "@testing-library/react";import { QueryClient, QueryClientProvider } from "@tanstack/react-query";import { ApiError } from "@multica/core/api";+import { configStore } from "@multica/core/config";+import { COMPOSIO_MCP_APPS_FLAG } from "@multica/core/feature-flags";import type { Agent } from "@multica/core/types";import { I18nProvider } from "@multica/core/i18n/react";import { RESOURCES } from "../../locales";@@ -69,6 +71,13 @@ vi.mock("./agent-channels-section", () => ({AgentChannelLinks: () => <div>channel-links</div>,AgentChannelsSection: () => <div id="messaging-channels">channels-section</div>,}));+vi.mock("./agent-apps-section", () => ({+ AgentAppsSection: ({ onManage }: { onManage: () => void }) => (+ <button type="button" onClick={onManage}>+ manage apps+ </button>+ ),+}));vi.mock("./agent-skills-section", () => ({AgentSkillsSection: ({ onManage }: { onManage: () => void }) => (<button type="button" onClick={onManage}>@@ -326,6 +335,7 @@ beforeEach(() => {mockArchiveAgent.mockResolvedValue(undefined);mockCancelAgentTasks.mockResolvedValue({ cancelled: 2 });mockCopyText.mockResolvedValue(true);+ configStore.getState().setFeatureFlags({ [COMPOSIO_MCP_APPS_FLAG]: false });});describe("AgentDetailPage direct-detail fallback", () => {@@ -562,6 +572,31 @@ describe("AgentDetailPage layout", () => {expect(screen.getByText("instructions-section")).toBeInTheDocument();});+ it("shows Apps between Instructions and Skills only while Connected Apps is on", async () => {+ const { unmount } = renderPage();+ await screen.findByRole("button", { name: "manage skills" });+ expect(screen.queryByRole("button", { name: "manage apps" })).not.toBeInTheDocument();+ unmount();++ configStore.getState().setFeatureFlags({ [COMPOSIO_MCP_APPS_FLAG]: true });+ renderPage();+ const apps = await screen.findByRole("button", { name: "manage apps" });+ const instructions = screen.getByText("instructions-section");+ const skills = screen.getByRole("button", { name: "manage skills" });+ expect(instructions.compareDocumentPosition(apps) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();+ expect(apps.compareDocumentPosition(skills) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();+ });++ it("hides Apps on a Qoder Cloud Agents runtime", async () => {+ configStore.getState().setFeatureFlags({ [COMPOSIO_MCP_APPS_FLAG]: true });+ runtimesRef.current = [{ id: "runtime-1", provider: "qoder_cloud" }];+ renderPage();+ await screen.findByRole("button", { name: "Assign work" });+ await waitFor(() =>+ expect(screen.queryByRole("button", { name: "manage apps" })).not.toBeInTheDocument(),+ );+ });+it("assigns work through the quick-create modal", async () => {renderPage();fireEvent.click(await screen.findByRole("button", { name: "Assign work" }));@@ -630,6 +665,16 @@ describe("AgentDetailPage deep links", () => {expect(replace).toHaveBeenLastCalledWith("/acme/agents/agent-1");});+ it("opens the Apps settings from the Apps section", async () => {+ configStore.getState().setFeatureFlags({ [COMPOSIO_MCP_APPS_FLAG]: true });+ const { replace } = renderPage();+ fireEvent.click(await screen.findByRole("button", { name: "manage apps" }));+ expect(screen.getByTestId("advanced-settings")).toHaveTextContent(+ "advanced:composio_mcp",+ );+ expect(replace).toHaveBeenLastCalledWith("/acme/agents/agent-1?view=composio_mcp");+ });+it("opens Access settings from the properties panel", async () => {renderPage();fireEvent.click(await screen.findByRole("button", { name: "edit access" }));diff --git a/packages/views/agents/components/agent-detail-page.tsx b/packages/views/agents/components/agent-detail-page.tsxindex e45f398f5b..f9cdc63610 100644--- a/packages/views/agents/components/agent-detail-page.tsx+++ b/packages/views/agents/components/agent-detail-page.tsx@@ -28,6 +28,8 @@ import {} from "@multica/core/agents";import { api, ApiError } from "@multica/core/api";import { useAuthStore } from "@multica/core/auth";+import { useFeatureEnabled } from "@multica/core/config";+import { COMPOSIO_MCP_APPS_FLAG } from "@multica/core/feature-flags";import { useWorkspaceId } from "@multica/core/hooks";import { refreshFeaturesOnLockedError } from "@multica/core/billing";import { useModalStore } from "@multica/core/modals";@@ -88,6 +90,7 @@ import {isAdvancedSection,type AdvancedSection,} from "./agent-advanced-settings";+import { AgentAppsSection } from "./agent-apps-section";import { AgentInstructionsSection } from "./agent-instructions-section";import { AgentPropertiesPanel } from "./agent-properties-panel";import { describeCancelImpact } from "./agent-row-actions";@@ -125,6 +128,7 @@ export function AgentDetailPage({ agentId }: AgentDetailPageProps) {const qc = useQueryClient();const paidFeatureError = usePaidFeatureErrorMessage();const currentUser = useAuthStore((s) => s.user);+ const composioAppsEnabled = useFeatureEnabled(COMPOSIO_MCP_APPS_FLAG, false);const {data: agents = [],@@ -709,13 +713,22 @@ export function AgentDetailPage({ agentId }: AgentDetailPageProps) {onUpdate={handleUpdate}/>- {/* Qoder agents take their skills from Qoder Cloud Agents. */}+ {/* Qoder agents take their skills and apps from Qoder Cloud Agents. */}{runtime?.provider === "qoder_cloud" ? null : (- <AgentSkillsSection- agent={agent}- canEdit={canEdit.allowed}- onManage={() => openAdvanced("skills")}- />+ <>+ {composioAppsEnabled && (+ <AgentAppsSection+ agent={agent}+ canEdit={canEdit.allowed}+ onManage={() => openAdvanced("composio_mcp")}+ />+ )}+ <AgentSkillsSection+ agent={agent}+ canEdit={canEdit.allowed}+ onManage={() => openAdvanced("skills")}+ />+ </>)}</div></ObjectPage>diff --git a/packages/views/agents/components/agent-properties-panel.test.tsx b/packages/views/agents/components/agent-properties-panel.test.tsxindex 855f9a3404..a3cad83cc4 100644--- a/packages/views/agents/components/agent-properties-panel.test.tsx+++ b/packages/views/agents/components/agent-properties-panel.test.tsx@@ -4,6 +4,8 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { QueryClient, QueryClientProvider } from "@tanstack/react-query";import { cleanup, fireEvent, screen } from "@testing-library/react";import type { AgentActivity } from "@multica/core/agents";+import { configStore } from "@multica/core/config";+import { COMPOSIO_MCP_APPS_FLAG } from "@multica/core/feature-flags";import type { Agent, AgentRuntime, MemberWithUser } from "@multica/core/types";import { renderWithI18n } from "../../test/i18n";@@ -19,11 +21,17 @@ const activityRef = vi.hoisted(() => ({current: new Map<string, unknown>(),}));const mockInitiateListModels = vi.hoisted(() => vi.fn());+const appsApi = vi.hoisted(() => ({+ listAgentApps: vi.fn(),+ getAppsOverview: vi.fn(),+ listAppCatalog: vi.fn(),+}));vi.mock("@multica/core/api", () => ({api: {initiateListModels: (...args: unknown[]) => mockInitiateListModels(...args),getListModelsResult: vi.fn(),+ ...appsApi,},}));vi.mock("@multica/core/hooks", () => ({@@ -143,6 +151,7 @@ beforeEach(() => {pickers.model = null;activityRef.current = new Map();mockInitiateListModels.mockReset();+ configStore.getState().setFeatureFlags({ [COMPOSIO_MCP_APPS_FLAG]: false });});afterEach(cleanup);@@ -248,3 +257,81 @@ describe("AgentPropertiesPanel", () => {expect(screen.queryByText(/% success/)).not.toBeInTheDocument();});});++describe("AgentPropertiesPanel Apps line", () => {+ const account = (slug: string, status = "active") => ({+ id: `c-${slug}`,+ toolkit_slug: slug,+ status,+ connected_at: "",+ last_used_at: null,+ });++ function withApps(scopes: Record<string, "team" | "personal">, personal: ReturnType<typeof account>[]) {+ configStore.getState().setFeatureFlags({ [COMPOSIO_MCP_APPS_FLAG]: true });+ appsApi.listAgentApps.mockResolvedValue({+ apps: Object.entries(scopes).map(([toolkit_slug, account_scope]) => ({+ agent_id: "agent-1",+ toolkit_slug,+ account_scope,+ level: "write",+ })),+ });+ appsApi.getAppsOverview.mockResolvedValue({+ catalog_mode: "all",+ can_manage: false,+ team: [],+ personal,+ agent_apps: [],+ });+ appsApi.listAppCatalog.mockResolvedValue({ catalog_mode: "all", apps: [] });+ }++ it("is absent while Connected Apps is off", () => {+ renderPanel(claude);++ expect(screen.queryByText("Apps")).not.toBeInTheDocument();+ expect(appsApi.listAgentApps).not.toHaveBeenCalled();+ });++ it("leads with the apps that still need the viewer's account", async () => {+ withApps(+ { gmail: "personal", googlecalendar: "personal", notion: "personal", posthog: "team" },+ [account("gmail"), account("notion", "expired")],+ );+ renderPanel(claude);++ expect(+ await screen.findByRole("button", { name: "Apps: 2 need your account. Show apps" }),+ ).toHaveClass("text-warning");+ });++ it("counts the apps when the viewer has every account they need", async () => {+ withApps({ gmail: "personal", posthog: "team" }, [account("gmail")]);+ renderPanel(claude);++ expect(await screen.findByText("2 apps")).toBeInTheDocument();+ });++ it("reads None without apps and scrolls to the Apps section", async () => {+ withApps({}, []);+ const section = document.createElement("div");+ section.id = "agent-apps-agent-1";+ section.tabIndex = -1;+ section.scrollIntoView = vi.fn();+ document.body.append(section);+ renderPanel(claude);++ fireEvent.click(await screen.findByRole("button", { name: "Apps: None. Show apps" }));+ expect(section.scrollIntoView).toHaveBeenCalled();+ expect(section).toHaveFocus();+ section.remove();+ });++ it("is not offered on a Qoder runtime", () => {+ withApps({ gmail: "personal" }, []);+ renderPanel(qoder);++ expect(screen.queryByText("Apps")).not.toBeInTheDocument();+ });+});diff --git a/packages/views/agents/components/agent-properties-panel.tsx b/packages/views/agents/components/agent-properties-panel.tsxindex 775ca4d6a9..50d83a94dc 100644--- a/packages/views/agents/components/agent-properties-panel.tsx+++ b/packages/views/agents/components/agent-properties-panel.tsx@@ -15,12 +15,15 @@ import {summarizeActivityWindow,useWorkspaceActivityMap,} from "@multica/core/agents";+import { useFeatureEnabled } from "@multica/core/config";+import { COMPOSIO_MCP_APPS_FLAG } from "@multica/core/feature-flags";import { useWorkspaceId } from "@multica/core/hooks";import { providerDisplayName } from "@multica/core/runtimes";import { ActorAvatar } from "../../common/actor-avatar";import { ObjectPanelSection, ObjectProperty } from "../../layout/object-page";import { ProviderLogo } from "../../runtimes/components/provider-logo";import { useLocale, useT } from "../../i18n";+import { AgentAppsProperty } from "./agent-apps-property";import { AgentPresenceIndicator } from "./agent-presence-indicator";import { CHIP_CLASS } from "./inspector/chip";import { ModelPicker } from "./inspector/model-picker";@@ -82,6 +85,7 @@ export function AgentPropertiesPanel({changeRuntime,} = useExecutionControls({ agent, runtime, runtimes, currentUserId, update });+ const appsEnabled = useFeatureEnabled(COMPOSIO_MCP_APPS_FLAG, false) && !qoderRuntime;const { byAgent: activityMap } = useWorkspaceActivityMap(wsId);const week = summarizeActivityWindow(activityMap.get(agent.id), 7);@@ -189,6 +193,8 @@ export function AgentPropertiesPanel({</button></ObjectProperty>+ {appsEnabled && <AgentAppsProperty agent={agent} />}+<ObjectProperty label={t(($) => $.panel.runs_7d)}><Value><span className="tabular-nums">{week.totalRuns}</span>diff --git a/packages/views/agents/components/tabs/agent-apps-tab.test.tsx b/packages/views/agents/components/tabs/agent-apps-tab.test.tsxindex f10654fde9..68c1c91b89 100644--- a/packages/views/agents/components/tabs/agent-apps-tab.test.tsx+++ b/packages/views/agents/components/tabs/agent-apps-tab.test.tsx@@ -22,9 +22,12 @@ vi.mock("@multica/core/api", async (importOriginal) => ({}));vi.mock("sonner", () => ({ toast: { error: vi.fn(), success: vi.fn() } }));vi.mock("@multica/core/hooks", () => ({ useWorkspaceId: () => "ws-1" }));-vi.mock("@multica/core/paths", () => ({ useWorkspacePaths: () => ({ settings: () => "/ws/settings" }) }));+vi.mock("@multica/core/paths", () => ({ useWorkspacePaths: () => ({ settings: () => "/ws/settings", apps: () => "/ws/apps" }) }));+vi.mock("@multica/core/workspace/hooks", () => ({ useActorName: () => ({ getActorName: () => "Agent" }) }));vi.mock("../../../navigation", () => ({AppLink: ({ href, children }: { href: string; children: ReactNode }) => <a href={href}>{children}</a>,+ useNavigation: () => ({ pathname: "/ws/agents/a1", searchParams: new URLSearchParams(), hash: "" }),+ currentPath: () => "/ws/agents/a1",}));const apps: AgentApp[] = [@@ -74,7 +77,7 @@ describe("AgentAppsTab", () => {overview.personal = [{ id: "expired-calendar", toolkit_slug: "googlecalendar", status: "expired", connected_at: "", last_used_at: null }];renderApps();await screen.findByText("Gmail");- expect(screen.getByText(/You haven't connected this app/)).toBeVisible();+ expect(screen.getByText(/Not connected/)).toBeVisible();expect(screen.getByRole("switch", { name: "Enable Gmail" })).toBeChecked();expect(screen.getByRole("switch", { name: "Enable Notion" })).not.toBeChecked();expect(screen.getByText("Notion").closest("li")?.querySelector("img")).toHaveAttribute("src", expect.stringContaining("notion"));@@ -160,14 +163,24 @@ describe("AgentAppsTab", () => {expect(api.updateAgentApps).toHaveBeenCalledTimes(1);});- it("does not let a member enable a team-only app", async () => {+ it("adds a team-only app for a member as a personal-account app", async () => {overview.can_manage = false;const user = userEvent.setup();renderApps();- const toggle = await screen.findByRole("switch", { name: "Enable Notion" });- expect(toggle).toHaveAttribute("aria-disabled", "true");- await user.click(toggle);- expect(api.updateAgentApps).not.toHaveBeenCalled();+ await user.click(await screen.findByRole("switch", { name: "Enable 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("connects a missing account through the pre-connect notice", async () => {+ const user = userEvent.setup();+ renderApps();+ await user.click(await screen.findByRole("button", { name: "Connect yours" }));+ expect(await screen.findByRole("dialog", { name: "Connect Gmail" })).toBeVisible();});it("retains saved apps missing from the catalog and allows removing them", async () => {@@ -272,15 +285,15 @@ describe("AgentAppsTab on a plan without team app accounts (MUL-9491)", () => {overview.personal.push({ id: `my-${slug}`, toolkit_slug: slug, status: "active", connected_at: "", last_used_at: null });};- it("does not give an agent a team-only app and shows the upgrade notice", async () => {+ it("gives a team-only app the triggerer's account, not the team account, and shows the upgrade notice", async () => {lock();const user = userEvent.setup();renderApps();expect(await screen.findByText("Not included in this workspace's plan.")).toBeVisible();- const toggle = screen.getByRole("switch", { name: "Enable Notion" });- expect(toggle).toHaveAttribute("aria-disabled", "true");- await user.click(toggle);- expect(api.updateAgentApps).not.toHaveBeenCalled();+ await user.click(screen.getByRole("switch", { name: "Enable Notion" }));+ await waitFor(() => expect(api.updateAgentApps).toHaveBeenCalledWith("a1", {+ apps: expect.arrayContaining([{ toolkit_slug: "notion", account_scope: "personal", level: "write" }]),+ }));});it("enables a dual-account app on the triggerer's account and cannot move it to the team account", async () => {diff --git a/packages/views/agents/components/tabs/agent-apps-tab.tsx b/packages/views/agents/components/tabs/agent-apps-tab.tsxindex 4c10555942..c7f4cd952c 100644--- a/packages/views/agents/components/tabs/agent-apps-tab.tsx+++ b/packages/views/agents/components/tabs/agent-apps-tab.tsx@@ -1,11 +1,12 @@"use client";-import { useMemo } from "react";+import { useMemo, useState } from "react";import { useQuery, useQueryClient } from "@tanstack/react-query";import { Radio } from "@base-ui/react/radio";import { RadioGroup } from "@base-ui/react/radio-group";import { toast } from "sonner";import { AlertTriangle, Loader2, Lock, Plug, User, Users } from "@multica/ui/icons";+import { Button } from "@multica/ui/components/ui/button";import { Switch } from "@multica/ui/components/ui/switch";import { useWorkspaceId } from "@multica/core/hooks";import {@@ -24,12 +25,16 @@ import type {AppAccountScope,AppCatalogEntry,} from "@multica/core/types";+import { appAccountStatus } from "../../../common/app-status";import { ComposioToolkitLogo } from "../../../common/composio-toolkit-logo";+import { ConnectAppDialog } from "../../../common/connect-app-dialog";import { SavedAppRestriction } from "../../../common/saved-app-restriction";import { AppLink } from "../../../navigation";import { PaidFeatureNotice, usePaidFeatureErrorMessage } from "../../../billing";import { useT } from "../../../i18n";import { ObjectSectionEmpty } from "../../../layout/object-page";+import { scopeForNewApp } from "../agent-app-status";+import { useAppStatusLabel } from "../use-agent-apps";const SCOPES: readonly AppAccountScope[] = ["team", "personal"];@@ -47,6 +52,8 @@ export function AgentAppsTab({ agent }: { agent: Agent }) {const restore = useRestoreAppAccess();const qc = useQueryClient();const paidFeatureError = usePaidFeatureErrorMessage();+ const statusLabel = useAppStatusLabel();+ const [connect, setConnect] = useState<{ scope: AppAccountScope; slug: string; name: string; logo?: string } | null>(null);const canManageTeam = overview.data?.can_manage ?? false;const apps = useMemo(() => appsQuery.data ?? [], [appsQuery.data]);@@ -143,22 +150,15 @@ export function AgentAppsTab({ agent }: { agent: Agent }) {const hasPersonal = connected.has(`personal:${slug}`);const availableScopes = SCOPES.filter((scope) => connected.has(`${scope}:${slug}`));const canUseTeam = canManageTeam && (canAddTeam || app?.account_scope === "team");- const defaultScope: AppAccountScope = hasTeam && canManageTeam && canAddTeam && (entry?.recommended_scope === "team" || !hasPersonal)- ? "team" : "personal";+ const defaultScope = scopeForNewApp(overview.data, slug, entry?.recommended_scope, canAddTeam);const scope = app?.account_scope ?? defaultScope;- const isConnected = connected.has(`${scope}:${slug}`);+ const accountStatus = appAccountStatus(overview.data, scope, slug);+ const isConnected = accountStatus === "connected";const lockedTeam = scope === "team" && !canManageTeam;- const canEnable = catalog.isSuccess && !!entry && entry.allowed !== false && (hasPersonal || (hasTeam && canManageTeam && canAddTeam));+ const canEnable = catalog.isSuccess && !!entry && entry.allowed !== false;const canRaiseLevel = scope !== "team" || canAddTeam;+ const canConnect = !!app && !isConnected && (scope === "personal" || (canManageTeam && (canAddTeam || accountStatus === "needs_reconnecting")));const AccountIcon = scope === "team" ? Users : User;- const status =- scope === "team"- ? isConnected- ? t(($) => $.tab_body.connected_apps.team_connected)- : t(($) => $.tab_body.connected_apps.team_missing)- : isConnected- ? t(($) => $.tab_body.connected_apps.personal_connected)- : t(($) => $.tab_body.connected_apps.personal_missing);return (<li key={slug} className="space-y-2 p-3"><div className="flex flex-wrap items-center gap-3">@@ -175,7 +175,7 @@ export function AgentAppsTab({ agent }: { agent: Agent }) {{app ? (<><AccountIcon className="mt-0.5 size-3 shrink-0" />- <span>{scope === "personal" && <>{scopeLabel(scope)} · </>}{status}</span>+ <span>{scopeLabel(scope)} · {statusLabel(accountStatus)}</span></>) : t(($) => $.tab_body.connected_apps.available_accounts, {accounts: availableScopes.map((value) => value === "personal"@@ -189,6 +189,19 @@ export function AgentAppsTab({ agent }: { agent: Agent }) {</p>)}</div>+ {canConnect && (+ <Button+ size="xs"+ variant={scope === "personal" && accountStatus === "not_connected" ? "default" : "outline"}+ onClick={() => setConnect({ scope, slug, name, logo: entry?.logo })}+ >+ {accountStatus === "needs_reconnecting"+ ? t(($) => $.apps_section.reconnect)+ : scope === "team"+ ? t(($) => $.apps_section.connect_team)+ : t(($) => $.apps_section.connect_yours)}+ </Button>+ )}{app && hasTeam && hasPersonal && (<RadioGroupclassName="inline-flex h-7 shrink-0 items-center rounded-lg bg-muted p-[3px]"@@ -217,7 +230,7 @@ export function AgentAppsTab({ agent }: { agent: Agent }) {checked={!!app}disabled={update.isPending || (app ? lockedTeam : !canEnable)}aria-label={t(($) => $.tab_body.connected_apps.enable, { app: name })}- title={!canManageTeam && (lockedTeam || (!app && hasTeam && !hasPersonal)) ? t(($) => $.tab_body.connected_apps.team_admin_only) : undefined}+ title={lockedTeam ? t(($) => $.tab_body.connected_apps.team_admin_only) : undefined}onCheckedChange={(checked) => {if (checked && canEnable) save([...apps, { agent_id: agent.id, toolkit_slug: slug, account_scope: defaultScope, level: "write" }]);else if (!checked && app && !lockedTeam) save(apps.filter((item) => item.toolkit_slug !== slug));@@ -254,7 +267,7 @@ export function AgentAppsTab({ agent }: { agent: Agent }) {<div className="flex flex-wrap items-center justify-between gap-3"><p className="text-caption text-muted-foreground">{t(($) => $.tab_body.connected_apps.connect_hint)}</p><AppLink- href={`${paths.settings()}?tab=apps`}+ href={`${paths.apps()}?tab=accounts`}className="inline-flex items-center gap-1.5 text-caption font-medium text-primary hover:underline"><Plug className="size-3" />@@ -262,6 +275,19 @@ export function AgentAppsTab({ agent }: { agent: Agent }) {</AppLink></div>+ {connect && (+ <ConnectAppDialog+ open+ onOpenChange={(open) => {+ if (!open) setConnect(null);+ }}+ scope={connect.scope}+ slug={connect.slug}+ name={connect.name}+ logo={connect.logo}+ />+ )}+{update.isPending && (<p className="flex items-center gap-1.5 text-caption text-muted-foreground"><Loader2 className="size-3 animate-spin" />diff --git a/packages/views/agents/components/use-agent-apps.ts b/packages/views/agents/components/use-agent-apps.tsnew file mode 100644index 0000000000..fc2eb7a146--- /dev/null+++ b/packages/views/agents/components/use-agent-apps.ts@@ -0,0 +1,57 @@+"use client";++import { useMemo } from "react";+import { useQuery } from "@tanstack/react-query";+import { useWorkspaceId } from "@multica/core/hooks";+import {+ agentAppsOptions,+ appCatalogOptions,+ appsOverviewOptions,+} from "@multica/core/connected-apps";+import type { AgentApp, AppCatalogEntry } from "@multica/core/types";+import { appAccountStatus, type AppAccountStatus } from "../../common/app-status";+import { useT } from "../../i18n";++export interface AgentAppRow {+ app: AgentApp;+ name: string;+ logo?: string;+ status: AppAccountStatus;+}++/** The agent's apps with where each stands for the viewer. */+export function useAgentApps(agentId: string, { enabled = true }: { enabled?: boolean } = {}) {+ const wsId = useWorkspaceId();+ const appsQuery = useQuery({ ...agentAppsOptions(wsId, agentId), enabled });+ const overview = useQuery({ ...appsOverviewOptions(wsId), enabled });+ const catalog = useQuery({ ...appCatalogOptions(wsId), enabled });++ const rows = useMemo<AgentAppRow[]>(() => {+ const bySlug = new Map<string, AppCatalogEntry>();+ for (const entry of catalog.data?.apps ?? []) bySlug.set(entry.slug, entry);+ return (appsQuery.data ?? []).map((app) => {+ const entry = bySlug.get(app.toolkit_slug);+ return {+ app,+ name: entry?.name || app.toolkit_slug,+ logo: entry?.logo,+ status: appAccountStatus(overview.data, app.account_scope, app.toolkit_slug),+ };+ });+ }, [appsQuery.data, catalog.data, overview.data]);++ return {+ rows,+ apps: appsQuery.data,+ overview: overview.data,+ catalog: catalog.data?.apps,+ isLoading: appsQuery.isLoading || overview.isLoading,+ isError: appsQuery.isError || overview.isError,+ };+}++/** Where an app stands, in the status vocabulary every Apps surface shares. */+export function useAppStatusLabel() {+ const { t } = useT("settings");+ return (status: AppAccountStatus) => t(($) => $.connected_apps.status[status]);+}diff --git a/packages/views/apps/components/account-menu.tsx b/packages/views/apps/components/account-menu.tsxnew file mode 100644index 0000000000..de2fb8b3d3--- /dev/null+++ b/packages/views/apps/components/account-menu.tsx@@ -0,0 +1,43 @@+"use client";++import { Activity, MoreHorizontal, Unplug } from "@multica/ui/icons";+import { IconButton } from "@multica/ui/components/common/icon-button";+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuSeparator,+ DropdownMenuTrigger,+} from "@multica/ui/components/ui/dropdown-menu";+import { useT } from "../../i18n";++/** The "…" menu of a connected account: its activity, and disconnecting it. */+export function AccountMenu({+ label,+ onActivity,+ onDisconnect,+}: {+ label: string;+ onActivity: () => void;+ onDisconnect: () => void;+}) {+ const { t } = useT("settings");+ return (+ <DropdownMenu>+ <DropdownMenuTrigger render={<IconButton variant="ghost" size="icon-sm" label={label} />}>+ <MoreHorizontal />+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end" className="w-auto">+ <DropdownMenuItem onClick={onActivity}>+ <Activity />+ {t(($) => $.connected_apps.activity)}+ </DropdownMenuItem>+ <DropdownMenuSeparator />+ <DropdownMenuItem variant="destructive" onClick={onDisconnect}>+ <Unplug />+ {t(($) => $.connected_apps.disconnect)}+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ );+}diff --git a/packages/views/apps/components/account-row.tsx b/packages/views/apps/components/account-row.tsxnew file mode 100644index 0000000000..9faa212f2e--- /dev/null+++ b/packages/views/apps/components/account-row.tsx@@ -0,0 +1,202 @@+"use client";++import type { ReactNode } from "react";+import { toast } from "sonner";+import { Building2, UserRound } from "@multica/ui/icons";+import { Button } from "@multica/ui/components/ui/button";+import { cn } from "@multica/ui/lib/utils";+import { useAuthStore } from "@multica/core/auth";+import { useActorName } from "@multica/core/workspace/hooks";+import {+ useDismissTeamAppRequests,+ useRequestTeamApp,+ useRestoreAppAccess,+} from "@multica/core/connected-apps";+import type { AppAccountScope, AppConnection, AppsOverview } from "@multica/core/types";+import {+ accountAction,+ accountFor,+ appAccountStatus,+ teamRequestFor,+ viewerTeamAsk,+} from "../../common/app-status";+import { ComposioToolkitLogo } from "../../common/composio-toolkit-logo";+import { SavedAppRestriction } from "../../common/saved-app-restriction";+import { useTeamAppAccess } from "../../common/use-team-app-access";+import { UpgradeToAddLink } from "../../billing";+import { useT } from "../../i18n";+import { AccountMenu } from "./account-menu";+import { AppStatusLabel } from "./app-status-label";++function errorMessage(e: unknown, fallback: string) {+ return e instanceof Error && e.message ? e.message : fallback;+}++/** "Team account" / "Your account" (or `label`), with the owner's icon. */+export function AccountOwner({ scope, label, detail }: { scope: AppAccountScope; label?: string; detail?: ReactNode }) {+ const { t } = useT("settings");+ const Icon = scope === "team" ? Building2 : UserRound;+ return (+ <span className="flex min-w-0 items-center gap-1 text-caption text-muted-foreground">+ <Icon aria-hidden="true" className="size-3 shrink-0" />+ <span className="shrink-0">+ {label ?? (scope === "team" ? t(($) => $.connected_apps.owner.team) : t(($) => $.connected_apps.owner.personal))}+ </span>+ {detail ? <span className="truncate">· {detail}</span> : null}+ </span>+ );+}++export interface AccountRowHandlers {+ connect: (scope: AppAccountScope) => void;+ activity?: (scope: AppAccountScope) => void;+ disconnect?: (scope: AppAccountScope, connection: AppConnection) => void;+}++/**+ * One account of one app, the same everywhere it is listed: whose it is,+ * where it stands, and the one thing the viewer can do about it. Who may do+ * what follows from the owner and the viewer's role (see `accountAction`).+ */+export function AccountRow({+ scope,+ slug,+ name,+ logo,+ showLogo = false,+ overview,+ title,+ subtitle,+ agentId,+ on,+ className,+}: {+ scope: AppAccountScope;+ slug: string;+ name: string;+ logo?: string;+ /** Lists of apps show the app's logo; the app's own page does not. */+ showLogo?: boolean;+ overview: AppsOverview;+ title: ReactNode;+ subtitle: ReactNode;+ /** The agent a member's ask is for. */+ agentId?: string;+ on: AccountRowHandlers;+ className?: string;+}) {+ const { t } = useT("settings");+ const { getActorName } = useActorName();+ const viewerId = useAuthStore((s) => s.user?.id ?? null);+ const restore = useRestoreAppAccess();+ const requestTeam = useRequestTeamApp();+ const dismiss = useDismissTeamAppRequests();+ const teamAccess = useTeamAppAccess(overview);+ const canManage = overview.can_manage;+ const account = accountFor(overview, scope, slug);+ const status = appAccountStatus(overview, scope, slug);+ const request = scope === "team" ? teamRequestFor(overview, slug) : undefined;+ const ask = scope === "team" ? viewerTeamAsk(overview, slug, viewerId) : null;+ const action = accountAction({+ scope,+ status,+ canManage,+ needsUpgrade: scope === "team" && teamAccess.needsUpgrade(slug),+ viewerAsk: ask,+ });++ let detail: string | undefined;+ if (status === "requested" && request) {+ detail = canManage+ ? [+ ...request.agent_ids.map((id) => getActorName("agent", id)),+ ...(request.asked_by ?? request.requested_by).map((id) => getActorName("member", id)),+ ].join(", ")+ : t(($) => $.connected_apps.account_row.admins_notified);+ }++ const askAdmin = () =>+ requestTeam.mutateAsync({ slug, agentId }).then(+ () => toast.success(t(($) => $.connected_apps.hub.toast_requested, { app: name })),+ (e: unknown) => toast.error(errorMessage(e, t(($) => $.connected_apps.toast_failed))),+ );+ const dismissRequests = () =>+ dismiss.mutateAsync(slug).then(+ () =>+ toast.success(+ canManage+ ? t(($) => $.connected_apps.account_row.toast_declined)+ : t(($) => $.connected_apps.account_row.toast_withdrawn),+ ),+ (e: unknown) => toast.error(errorMessage(e, t(($) => $.connected_apps.toast_failed))),+ );++ let button: ReactNode = null;+ switch (action) {+ case "connect":+ case "reconnect":+ button = (+ <Button size="xs" variant={status === "requested" || action === "reconnect" ? "default" : "outline"} onClick={() => on.connect(scope)}>+ {action === "reconnect" ? t(($) => $.connected_apps.hub.reconnect) : t(($) => $.connected_apps.hub.connect)}+ </Button>+ );+ break;+ case "upgrade":+ button = <UpgradeToAddLink />;+ break;+ case "ask_admin":+ button = (+ <Button size="xs" variant="outline" disabled={requestTeam.isPending} onClick={askAdmin}>+ {t(($) => $.connected_apps.hub.ask_admin)}+ </Button>+ );+ break;+ case "withdraw":+ button = (+ <Button size="xs" variant="ghost" disabled={dismiss.isPending} onClick={dismissRequests}>+ {t(($) => $.connected_apps.account_row.withdraw)}+ </Button>+ );+ break;+ }+ const canOpenMenu = !!account && (scope === "personal" || canManage);++ return (+ <div className={cn("space-y-2 px-4 py-3", className)} data-account-row={`${scope}:${slug}`}>+ <div className="flex items-center gap-3">+ {showLogo && <ComposioToolkitLogo slug={slug} name={name} fallbackLogo={logo} className="size-8 shrink-0" />}+ <div className="min-w-0 flex-1 space-y-0.5">+ <div className="truncate text-body font-medium">{title}</div>+ {subtitle}+ </div>+ <div className="hidden min-w-0 max-w-[45%] shrink text-caption sm:flex">+ <AppStatusLabel status={status} detail={detail} />+ </div>+ <div className="flex shrink-0 items-center gap-1">+ {canManage && status === "requested" && (+ <Button size="xs" variant="ghost" disabled={dismiss.isPending} onClick={dismissRequests}>+ {t(($) => $.connected_apps.account_row.decline)}+ </Button>+ )}+ {button}+ {canOpenMenu && on.activity && on.disconnect && (+ <AccountMenu+ label={t(($) => $.connected_apps.app_page.account_actions, { account: name })}+ onActivity={() => on.activity?.(scope)}+ onDisconnect={() => on.disconnect?.(scope, account)}+ />+ )}+ </div>+ </div>+ <div className="text-caption sm:hidden">+ <AppStatusLabel status={status} detail={detail} />+ </div>+ {account?.actions_blocked && (+ <SavedAppRestriction+ kind="account"+ onRestore={scope === "personal" || canManage ? () => restore.mutateAsync({ slug, scope }) : undefined}+ />+ )}+ </div>+ );+}diff --git a/packages/views/apps/components/accounts-list.tsx b/packages/views/apps/components/accounts-list.tsxnew file mode 100644index 0000000000..76fdea325b--- /dev/null+++ b/packages/views/apps/components/accounts-list.tsx@@ -0,0 +1,183 @@+"use client";++import { useState } from "react";+import { useQuery } from "@tanstack/react-query";+import { useWorkspaceId } from "@multica/core/hooks";+import { useActorName } from "@multica/core/workspace/hooks";+import { myPendingAppRequestsOptions } from "@multica/core/connected-apps";+import type { AppAccountScope, AppCatalogEntry, AppConnection, AppRequest, AppsOverview } from "@multica/core/types";+import { appAccountStatus, teamRequestFor, type AppAccountStatus } from "../../common/app-status";+import { ConnectAppDialog } from "../../common/connect-app-dialog";+import { useT } from "../../i18n";+import { AccountOwner, AccountRow, type AccountRowHandlers } from "./account-row";+import { AppAccountDialog } from "./app-account-dialog";+import { DisconnectAccountDialog } from "./disconnect-account-dialog";++type AppRef = { slug: string; name: string; logo?: string };++export type AccountRows = Record<AppAccountScope, AppRef[]> & { waiting: AppRequest[] };++// Rows that need someone to act come first.+const ORDER: Record<AppAccountStatus, number> = {+ needs_reconnecting: 0,+ requested: 1,+ not_connected: 2,+ connected: 3,+};++/**+ * The apps involved in one owner's accounts: those connected, those agents+ * use through that owner, and, for the team, those someone is waiting for;+ * for the viewer, those an agent is waiting on them to connect.+ */+function accountSlugs(overview: AppsOverview, scope: AppAccountScope, waiting: AppRequest[]): string[] {+ const slugs = new Set<string>();+ for (const c of overview[scope]) if (c.status !== "revoked") slugs.add(c.toolkit_slug);+ for (const a of overview.agent_apps) if (a.account_scope === scope) slugs.add(a.toolkit_slug);+ if (scope === "team") for (const r of overview.team_requests ?? []) slugs.add(r.toolkit_slug);+ else for (const r of waiting) slugs.add(r.toolkit_slug);+ return [...slugs];+}++/** The team's and the viewer's account rows, needs-action first. */+export function useAccountRows(overview: AppsOverview | undefined, catalog: AppCatalogEntry[]): AccountRows {+ const wsId = useWorkspaceId();+ const requests = useQuery(myPendingAppRequestsOptions(wsId));+ const waiting = (requests.data ?? []).filter(+ (r) => r.kind === "connect" && r.status === "pending" && r.account_scope === "personal",+ );+ const entries = new Map(catalog.map((a) => [a.slug, a]));+ const rows = (scope: AppAccountScope): AppRef[] => {+ if (!overview) return [];+ return accountSlugs(overview, scope, waiting)+ .map((slug) => {+ const entry = entries.get(slug);+ return { app: { slug, name: entry?.name || slug, logo: entry?.logo }, status: appAccountStatus(overview, scope, slug) };+ })+ .sort((a, b) => ORDER[a.status] - ORDER[b.status] || a.app.name.localeCompare(b.app.name))+ .map(({ app }) => app);+ };+ return { team: rows("team"), personal: rows("personal"), waiting };+}++/** The accounts agents in this workspace act as: the team's and the viewer's. */+export function AccountsList({+ overview,+ rows,+ matches,+}: {+ overview: AppsOverview;+ rows: AccountRows;+ matches: (name: string) => boolean;+}) {+ const { t } = useT("settings");+ const usage = useUsage(overview, rows.waiting);+ const [connecting, setConnecting] = useState<{ scope: AppAccountScope; app: AppRef } | null>(null);+ const [activity, setActivity] = useState<{ scope: AppAccountScope; app: AppRef } | null>(null);+ const [disconnecting, setDisconnecting] = useState<{ scope: AppAccountScope; connection: AppConnection; app: AppRef } | null>(null);++ const handlersFor = (app: AppRef): AccountRowHandlers => ({+ connect: (scope) => setConnecting({ scope, app }),+ activity: (scope) => setActivity({ scope, app }),+ disconnect: (scope, connection) => setDisconnecting({ scope, connection, app }),+ });++ const group = (scope: AppAccountScope) => {+ const list = rows[scope].filter((app) => matches(app.name) || matches(app.slug));+ const title = scope === "team"+ ? t(($) => $.connected_apps.accounts_page.team_title)+ : t(($) => $.connected_apps.accounts_page.yours_title);+ const description = scope === "personal"+ ? t(($) => $.connected_apps.accounts_page.yours_description)+ : overview.can_manage+ ? t(($) => $.connected_apps.accounts_page.team_description_admin)+ : t(($) => $.connected_apps.accounts_page.team_description_member);+ return (+ <section aria-label={title} className="space-y-3">+ <div className="space-y-0.5">+ <h3 className="text-body font-semibold">{title}</h3>+ <p className="text-caption text-muted-foreground">{description}</p>+ </div>+ {list.length === 0 ? (+ <p className="rounded-lg border border-dashed px-4 py-6 text-center text-caption text-muted-foreground">+ {scope === "team"+ ? t(($) => $.connected_apps.accounts_page.team_empty)+ : t(($) => $.connected_apps.accounts_page.empty)}+ </p>+ ) : (+ <div className="divide-y overflow-hidden rounded-lg border bg-card">+ {list.map((app) => (+ <AccountRow+ key={app.slug}+ scope={scope}+ slug={app.slug}+ name={app.name}+ logo={app.logo}+ showLogo+ overview={overview}+ title={app.name}+ subtitle={<AccountOwner scope={scope} detail={usage(scope, app.slug)} />}+ on={handlersFor(app)}+ />+ ))}+ </div>+ )}+ </section>+ );+ };++ return (+ <div className="space-y-8">+ {group("team")}+ {group("personal")}++ {connecting && (+ <ConnectAppDialog+ open+ onOpenChange={(open) => { if (!open) setConnecting(null); }}+ scope={connecting.scope}+ slug={connecting.app.slug}+ name={connecting.app.name}+ logo={connecting.app.logo}+ />+ )}+ {activity && (+ <AppAccountDialog+ scope={activity.scope}+ slug={activity.app.slug}+ name={activity.app.name}+ onClose={() => setActivity(null)}+ />+ )}+ {disconnecting && (+ <DisconnectAccountDialog+ scope={disconnecting.scope}+ connectionId={disconnecting.connection.id}+ slug={disconnecting.app.slug}+ name={disconnecting.app.name}+ logo={disconnecting.app.logo}+ onClose={() => setDisconnecting(null)}+ />+ )}+ </div>+ );+}++/** Who relies on the account: the agents acting as it, or who waits for it. */+function useUsage(overview: AppsOverview, waiting: AppRequest[]) {+ const { t } = useT("settings");+ const { getActorName } = useActorName();+ const names = (ids: string[]) => ids.map((id) => getActorName("agent", id)).join(", ");+ return (scope: AppAccountScope, slug: string): string | undefined => {+ const agentIds = [...new Set(overview.agent_apps.filter((a) => a.toolkit_slug === slug && a.account_scope === scope).map((a) => a.agent_id))];+ const waitingAgents = scope === "team"+ ? (teamRequestFor(overview, slug)?.agent_ids ?? [])+ : waiting.filter((r) => r.toolkit_slug === slug).map((r) => r.agent_id);+ const needing = [...new Set(waitingAgents)].filter(Boolean);+ if (needing.length > 0 && appAccountStatus(overview, scope, slug) !== "connected") {+ return t(($) => $.connected_apps.accounts_page.needed_by, { agents: names(needing) });+ }+ if (agentIds.length === 0) return undefined;+ return t(($) => $.connected_apps.accounts_page.used_by, { agents: names(agentIds) });+ };+}diff --git a/packages/views/settings/components/app-account-dialog.test.tsx b/packages/views/apps/components/app-account-dialog.test.tsxsimilarity index 100%rename from packages/views/settings/components/app-account-dialog.test.tsxrename to packages/views/apps/components/app-account-dialog.test.tsxdiff --git a/packages/views/settings/components/app-account-dialog.tsx b/packages/views/apps/components/app-account-dialog.tsxsimilarity index 100%rename from packages/views/settings/components/app-account-dialog.tsxrename to packages/views/apps/components/app-account-dialog.tsxdiff --git a/packages/views/apps/components/app-accounts-card.tsx b/packages/views/apps/components/app-accounts-card.tsxnew file mode 100644index 0000000000..7466339006--- /dev/null+++ b/packages/views/apps/components/app-accounts-card.tsx@@ -0,0 +1,93 @@+"use client";++import { useState } from "react";+import { useCurrentWorkspace } from "@multica/core/paths";+import type { AppAccountScope, AppConnection, AppsOverview } from "@multica/core/types";+import { ConnectAppDialog } from "../../common/connect-app-dialog";+import { ObjectSection, ObjectSectionCard } from "../../layout/object-page";+import { useT } from "../../i18n";+import { AccountRow, type AccountRowHandlers } from "./account-row";+import { AppAccountDialog } from "./app-account-dialog";+import { DisconnectAccountDialog } from "./disconnect-account-dialog";++/** The workspace's team account and the viewer's own account for this app. */+export function AppAccountsSection({+ slug,+ name,+ logo,+ overview,+}: {+ slug: string;+ name: string;+ logo?: string;+ overview: AppsOverview;+}) {+ const { t } = useT("settings");+ const workspace = useCurrentWorkspace()?.name ?? t(($) => $.page.workspace_fallback);+ const [connecting, setConnecting] = useState<AppAccountScope | null>(null);+ const [activity, setActivity] = useState<AppAccountScope | null>(null);+ const [disconnecting, setDisconnecting] = useState<{ scope: AppAccountScope; connection: AppConnection } | null>(null);+ const on: AccountRowHandlers = {+ connect: setConnecting,+ activity: setActivity,+ disconnect: (scope, connection) => setDisconnecting({ scope, connection }),+ };++ return (+ <ObjectSection title={t(($) => $.connected_apps.app_page.accounts_title)}>+ <p className="-mt-1 text-caption text-muted-foreground">+ {t(($) => $.connected_apps.app_page.accounts_description, { app: name, workspace })}+ </p>+ <ObjectSectionCard>+ <AccountRow+ scope="team"+ slug={slug}+ name={name}+ overview={overview}+ title={t(($) => $.connected_apps.owner.team)}+ subtitle={+ <p className="truncate text-caption text-muted-foreground">+ {t(($) => $.connected_apps.app_page.team_account_hint, { workspace })}+ </p>+ }+ on={on}+ />+ <AccountRow+ scope="personal"+ slug={slug}+ name={name}+ overview={overview}+ title={t(($) => $.connected_apps.owner.personal)}+ subtitle={+ <p className="truncate text-caption text-muted-foreground">+ {t(($) => $.connected_apps.app_page.your_account_hint)}+ </p>+ }+ on={on}+ />+ </ObjectSectionCard>++ {connecting && (+ <ConnectAppDialog+ open+ onOpenChange={(open) => { if (!open) setConnecting(null); }}+ scope={connecting}+ slug={slug}+ name={name}+ logo={logo}+ />+ )}+ {activity && <AppAccountDialog scope={activity} slug={slug} name={name} onClose={() => setActivity(null)} />}+ {disconnecting && (+ <DisconnectAccountDialog+ scope={disconnecting.scope}+ connectionId={disconnecting.connection.id}+ slug={slug}+ name={name}+ logo={logo}+ onClose={() => setDisconnecting(null)}+ />+ )}+ </ObjectSection>+ );+}diff --git a/packages/views/apps/components/app-activity-card.tsx b/packages/views/apps/components/app-activity-card.tsxnew file mode 100644index 0000000000..27800ad255--- /dev/null+++ b/packages/views/apps/components/app-activity-card.tsx@@ -0,0 +1,88 @@+"use client";++import { useQuery } from "@tanstack/react-query";+import { useWorkspaceId } from "@multica/core/hooks";+import { issueRouteRef, useWorkspacePaths } from "@multica/core/paths";+import { useActorName } from "@multica/core/workspace/hooks";+import { appActivityOptions } from "@multica/core/connected-apps";+import { issueDetailOptions } from "@multica/core/issues/queries";+import type { AppAccountScope, AppToolCall } from "@multica/core/types";+import { toolLabel } from "../../issues/components/app-call-chips";+import { AppLink } from "../../navigation";+import { useT, useTimeAgo } from "../../i18n";+import { ObjectSection, ObjectSectionCard, ObjectSectionEmpty } from "../../layout/object-page";++const LIMIT = 10;++type ScopedCall = AppToolCall & { scope: AppAccountScope };++/**+ * The latest calls agents made to this app, through the team account (only+ * admins can read it) and through the viewer's own.+ */+export function AppActivityCard({ slug, name, canManage }: { slug: string; name: string; canManage: boolean }) {+ const { t } = useT("settings");+ const wsId = useWorkspaceId();+ const team = useQuery({ ...appActivityOptions(wsId, slug, "team"), enabled: canManage });+ const personal = useQuery(appActivityOptions(wsId, slug, "personal"));+ const loading = personal.isLoading || (canManage && team.isLoading);+ const calls: ScopedCall[] = [+ ...(canManage ? team.data ?? [] : []).map((c) => ({ ...c, scope: "team" as const })),+ ...(personal.data ?? []).map((c) => ({ ...c, scope: "personal" as const })),+ ]+ .sort((a, b) => b.created_at.localeCompare(a.created_at))+ .slice(0, LIMIT);++ return (+ <ObjectSection title={t(($) => $.connected_apps.app_page.activity_title)}>+ {loading ? (+ <ObjectSectionEmpty description={t(($) => $.connected_apps.loading)} />+ ) : personal.isError || team.isError ? (+ <ObjectSectionEmpty description={t(($) => $.connected_apps.detail.activity_failed)} />+ ) : calls.length === 0 ? (+ <ObjectSectionEmpty description={t(($) => $.connected_apps.app_page.activity_empty, { app: name })} />+ ) : (+ <ObjectSectionCard>+ {calls.map((call) => <ActivityRow key={`${call.scope}:${call.id}`} call={call} slug={slug} />)}+ </ObjectSectionCard>+ )}+ </ObjectSection>+ );+}++function ActivityRow({ call, slug }: { call: ScopedCall; slug: string }) {+ const { t } = useT("settings");+ const timeAgo = useTimeAgo();+ const { getActorName } = useActorName();+ const failed = call.outcome === "error" || call.outcome === "blocked";+ return (+ <div className="flex items-baseline gap-3 px-3 py-2 text-body">+ <span className="min-w-0 flex-1 truncate">+ <span className="font-medium">{getActorName("agent", call.agent_id)}</span>{" "}+ <span className={failed ? "text-destructive" : "text-muted-foreground"}>+ {toolLabel(slug, call.tool_slug)}+ </span>+ </span>+ <span className="shrink-0 text-caption text-muted-foreground">+ {call.scope === "team"+ ? t(($) => $.connected_apps.app_page.as_team)+ : t(($) => $.connected_apps.app_page.as_you)}+ {" · "}+ {call.issue_id ? <IssueRef issueId={call.issue_id} /> : t(($) => $.connected_apps.app_page.in_chat)}+ {" · "}+ {timeAgo(call.created_at)}+ </span>+ </div>+ );+}++function IssueRef({ issueId }: { issueId: string }) {+ const wsId = useWorkspaceId();+ const paths = useWorkspacePaths();+ const issue = useQuery(issueDetailOptions(wsId, issueId));+ return (+ <AppLink href={paths.issueDetail(issueRouteRef({ id: issueId, identifier: issue.data?.identifier }))} className="hover:text-foreground hover:underline">+ {issue.data?.identifier ?? "…"}+ </AppLink>+ );+}diff --git a/packages/views/apps/components/app-agents-card.tsx b/packages/views/apps/components/app-agents-card.tsxnew file mode 100644index 0000000000..aa78b6ba52--- /dev/null+++ b/packages/views/apps/components/app-agents-card.tsx@@ -0,0 +1,175 @@+"use client";++import { useState } from "react";+import { useQuery, useQueryClient } from "@tanstack/react-query";+import { toast } from "sonner";+import {+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from "@multica/ui/components/ui/select";+import { Switch } from "@multica/ui/components/ui/switch";+import { useWorkspaceId } from "@multica/core/hooks";+import { canEditAgent, useCurrentMember } from "@multica/core/permissions";+import { connectedAppsKeys, useUpdateAgentApps } from "@multica/core/connected-apps";+import { refreshFeaturesOnLockedError } from "@multica/core/billing";+import { agentListOptions } from "@multica/core/workspace/queries";+import type { Agent, AppAccountScope, AppCatalogEntry, AppsOverview } from "@multica/core/types";+import { ActorAvatar } from "../../common/actor-avatar";+import { useT } from "../../i18n";+import { agentAppsWith } from "../lib/agent-apps";+import { scopeForNewApp } from "../../agents/components/agent-app-status";+import { useTeamAppAccess } from "../../common/use-team-app-access";+import { usePaidFeatureErrorMessage } from "../../billing";+import { appAccountStatus } from "../../common/app-status";+import { AppStatusLabel } from "./app-status-label";+import { ObjectSection, ObjectSectionCard, ObjectSectionEmpty } from "../../layout/object-page";++/** Every agent in the workspace, whether it uses this app, and whose account. */+export function AppAgentsCard({+ slug,+ name,+ entry,+ overview,+}: {+ slug: string;+ name: string;+ entry: AppCatalogEntry | undefined;+ overview: AppsOverview;+}) {+ const { t } = useT("settings");+ const wsId = useWorkspaceId();+ const agents = useQuery(agentListOptions(wsId));+ const viewer = useCurrentMember(wsId);+ const live = (agents.data ?? [])+ .filter((a) => !a.archived_at)+ .sort((a, b) => a.name.localeCompare(b.name));++ return (+ <ObjectSection title={t(($) => $.connected_apps.app_page.agents_title)} count={agents.data ? live.length : undefined}>+ <p className="-mt-1 text-caption text-muted-foreground">{t(($) => $.connected_apps.app_page.agents_description)}</p>+ {agents.isLoading ? (+ <ObjectSectionEmpty description={t(($) => $.connected_apps.loading)} />+ ) : live.length === 0 ? (+ <ObjectSectionEmpty description={t(($) => $.connected_apps.app_page.agents_empty)} />+ ) : (+ <ObjectSectionCard>+ {live.map((agent) => (+ <AgentAppRow+ key={agent.id}+ agent={agent}+ slug={slug}+ appName={name}+ entry={entry}+ overview={overview}+ canEdit={canEditAgent(agent, viewer).allowed}+ />+ ))}+ </ObjectSectionCard>+ )}+ </ObjectSection>+ );+}++function AgentAppRow({+ agent,+ slug,+ appName,+ entry,+ overview,+ canEdit,+}: {+ agent: Agent;+ slug: string;+ appName: string;+ entry: AppCatalogEntry | undefined;+ overview: AppsOverview;+ canEdit: boolean;+}) {+ const { t } = useT("settings");+ const wsId = useWorkspaceId();+ const qc = useQueryClient();+ const update = useUpdateAgentApps(agent.id);+ const teamAccess = useTeamAppAccess(overview);+ const paidFeatureError = usePaidFeatureErrorMessage();+ const [saving, setSaving] = useState(false);+ const current = overview.agent_apps.find((a) => a.agent_id === agent.id && a.toolkit_slug === slug);+ const teamLocked = current?.account_scope === "team" && !overview.can_manage;+ const disabled = !canEdit || saving || teamLocked;+ const status = current ? appAccountStatus(overview, current.account_scope, slug) : null;+ const readiness = !current || !status+ ? undefined+ : current.account_scope === "team"+ ? status === "connected"+ ? t(($) => $.connected_apps.app_page.ready_team)+ : t(($) => $.connected_apps.app_page.needs_team)+ : status === "connected"+ ? t(($) => $.connected_apps.app_page.ready_yours)+ : t(($) => $.connected_apps.app_page.needs_yours);+ const sourceItems = {+ team: t(($) => $.connected_apps.app_page.source_team),+ personal: t(($) => $.connected_apps.app_page.source_personal),+ };++ // The row reads the overview, so it stays busy until the refetch lands+ // instead of flicking back to the old value in between.+ const save = (scope: AppAccountScope | null) => {+ setSaving(true);+ update+ .mutateAsync(agentAppsWith(overview, agent.id, slug, scope))+ .then(() => qc.invalidateQueries({ queryKey: connectedAppsKeys.overview(wsId) }))+ .catch((e: unknown) => {+ refreshFeaturesOnLockedError(qc, wsId, e);+ toast.error(paidFeatureError(e, e instanceof Error && e.message ? e.message : t(($) => $.connected_apps.app_page.save_failed)));+ })+ .finally(() => setSaving(false));+ };++ return (+ <div className="flex items-center gap-3 px-3 py-2" title={teamLocked ? t(($) => $.connected_apps.app_page.team_admin_only) : undefined}>+ <ActorAvatar actorType="agent" actorId={agent.id} size="sm" />+ <span className="w-36 min-w-0 shrink-0 truncate text-body font-medium">{agent.name}</span>+ <div className="min-w-0 flex-1">+ {current ? (+ <Select+ items={sourceItems}+ value={current.account_scope}+ onValueChange={(value) => value && value !== current.account_scope && save(value as AppAccountScope)}+ disabled={disabled}+ >+ <SelectTrigger+ size="sm"+ className="max-w-full"+ aria-label={t(($) => $.connected_apps.app_page.source_label, { agent: agent.name, app: appName })}+ >+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ <SelectItem value="team" disabled={!overview.can_manage || !teamAccess.canAdd}>+ {sourceItems.team}+ </SelectItem>+ <SelectItem value="personal" disabled={teamLocked}>+ {sourceItems.personal}+ </SelectItem>+ </SelectContent>+ </Select>+ ) : (+ <span className="text-caption text-muted-foreground">+ {t(($) => $.connected_apps.app_page.not_using, { app: appName })}+ </span>+ )}+ </div>+ {status && readiness && (+ <AppStatusLabel status={status} label={readiness} className="hidden max-w-48 shrink-0 text-caption md:inline-flex" />+ )}+ <Switch+ checked={!!current}+ disabled={disabled}+ onCheckedChange={(on) => save(on ? scopeForNewApp(overview, slug, entry?.recommended_scope, teamAccess.canAdd) : null)}+ aria-label={t(($) => $.connected_apps.app_page.enable, { agent: agent.name, app: appName })}+ />+ </div>+ );+}diff --git a/packages/views/apps/components/app-capabilities-card.tsx b/packages/views/apps/components/app-capabilities-card.tsxnew file mode 100644index 0000000000..f209df4458--- /dev/null+++ b/packages/views/apps/components/app-capabilities-card.tsx@@ -0,0 +1,30 @@+"use client";++import { Check } from "@multica/ui/icons";+import { useT } from "../../i18n";+import { ObjectPanelSection } from "../../layout/object-page";++const CLASSES = ["read", "write", "send", "delete", "share"] as const;++/** The kinds of action an agent with this app can take. */+export function AppCapabilitiesCard() {+ const { t } = useT("settings");+ return (+ <ObjectPanelSection title={t(($) => $.connected_apps.app_page.capabilities_title)}>+ <ul className="space-y-1.5">+ {CLASSES.map((cls) => (+ <li key={cls} className="flex items-start gap-2 text-caption">+ <Check aria-hidden="true" className="mt-0.5 size-3.5 shrink-0 text-success" />+ <span>+ <span className="font-medium">{t(($) => $.connected_apps.classes[cls].label)}</span>+ <span className="text-muted-foreground"> · {t(($) => $.connected_apps.classes[cls].description)}</span>+ </span>+ </li>+ ))}+ </ul>+ <p className="pt-2 text-caption text-muted-foreground">+ {t(($) => $.connected_apps.app_page.capabilities_note)}+ </p>+ </ObjectPanelSection>+ );+}diff --git a/packages/views/apps/components/app-card.tsx b/packages/views/apps/components/app-card.tsxnew file mode 100644index 0000000000..ef171215ed--- /dev/null+++ b/packages/views/apps/components/app-card.tsx@@ -0,0 +1,47 @@+"use client";++import type { ReactNode } from "react";+import { ComposioToolkitLogo } from "../../common/composio-toolkit-logo";+import { AppLink } from "../../navigation";++/**+ * One app in the directory. The name is the card's link and covers the whole+ * card; `action` sits above it so its button keeps its own click.+ */+export function AppCard({+ slug,+ name,+ logo,+ href,+ subtitle,+ action,+ children,+}: {+ slug: string;+ name: string;+ logo?: string;+ href: string;+ subtitle?: ReactNode;+ action?: ReactNode;+ children?: ReactNode;+}) {+ return (+ <li className="relative flex min-w-0 flex-col gap-2 rounded-lg border border-surface-border bg-surface p-3 transition-colors hover:bg-surface-hover">+ <div className="flex min-w-0 items-start gap-3">+ <ComposioToolkitLogo slug={slug} name={name} fallbackLogo={logo} />+ <div className="min-w-0 flex-1">+ <AppLink+ href={href}+ newTabTitle={name}+ className="block truncate text-body font-medium outline-none after:absolute after:inset-0 after:rounded-lg focus-visible:after:ring-2 focus-visible:after:ring-ring"+ >+ {name}+ </AppLink>+ {subtitle ? <p className="truncate text-caption text-muted-foreground">{subtitle}</p> : null}+ </div>+ {action ? <div className="relative z-10 shrink-0">{action}</div> : null}+ </div>+ {children ? <div className="min-w-0 space-y-1 text-caption text-muted-foreground">{children}</div> : null}+ </li>+ );+}diff --git a/packages/views/apps/components/app-detail-page.test.tsx b/packages/views/apps/components/app-detail-page.test.tsxnew file mode 100644index 0000000000..8471cabee5--- /dev/null+++ b/packages/views/apps/components/app-detail-page.test.tsx@@ -0,0 +1,193 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { cleanup, 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 type { AppsOverview, MemberRole } from "@multica/core/types";+import { NavigationProvider, type NavigationAdapter } from "../../navigation";+import { renderWithI18n } from "../../test/i18n";+import { AppDetailPage } from "./app-detail-page";++vi.mock("@multica/core/api", () => ({ api: {+ getAppsOverview: vi.fn(), listAppCatalog: vi.fn(), listAgents: vi.fn(), updateAgentApps: vi.fn(),+ listAppActivity: vi.fn(), getIssue: vi.fn(), requestTeamApp: vi.fn(), dismissTeamAppRequests: vi.fn(),+ connectApp: vi.fn(),+} }));+vi.mock("@multica/core/hooks", () => ({ useWorkspaceId: () => "ws-1" }));+vi.mock("@multica/core/paths", async (importOriginal) => ({+ ...(await importOriginal<object>()),+ useWorkspacePaths: () => ({+ apps: () => "/acme/apps",+ issueDetail: (id: string) => `/acme/issues/${id}`,+ }),+}));+vi.mock("@multica/core/workspace/hooks", () => ({+ useActorName: () => ({ getActorName: (_type: string, id: string) => `Name ${id}` }),+}));+const viewer = vi.hoisted(() => ({ role: "member" as MemberRole }));+vi.mock("@multica/core/permissions", async (importOriginal) => ({+ ...(await importOriginal<typeof import("@multica/core/permissions")>()),+ useCurrentMember: () => ({ userId: "me", role: viewer.role, member: null, isLoading: false }),+}));+vi.mock("@multica/core/auth", () => {+ const state = { user: { id: "me" } };+ return { useAuthStore: (selector: (s: typeof state) => unknown) => selector(state) };+});+vi.mock("../../common/use-composio-available", () => ({ useComposioAvailable: () => true }));+vi.mock("../../common/actor-avatar", () => ({ ActorAvatar: () => null }));++let overview: AppsOverview;++beforeEach(() => {+ viewer.role = "member";+ overview = {+ catalog_mode: "all", can_manage: false, personal: [],+ team: [{ id: "t-notion", toolkit_slug: "notion", status: "active", connected_at: "", last_used_at: null }],+ agent_apps: [+ { agent_id: "mine", toolkit_slug: "gmail", account_scope: "personal", level: "read" },+ { agent_id: "mine", toolkit_slug: "notion", account_scope: "personal", level: "write" },+ { agent_id: "shared", toolkit_slug: "notion", account_scope: "team", level: "write" },+ ],+ };+ vi.mocked(api.getAppsOverview).mockImplementation(async () => overview);+ vi.mocked(api.listAppCatalog).mockResolvedValue({ catalog_mode: "all", apps: [+ { slug: "notion", name: "Notion", category: "Docs", curated: true },+ ] });+ vi.mocked(api.listAgents).mockResolvedValue([+ { id: "mine", name: "Mine", owner_id: "me", archived_at: null },+ { id: "shared", name: "Shared", owner_id: "me", archived_at: null },+ { id: "other", name: "Other", owner_id: "u2", archived_at: null },+ { id: "gone", name: "Gone", owner_id: "me", archived_at: "2026-01-01" },+ ] as never);+ vi.mocked(api.listAppActivity).mockImplementation(async (_slug, scope) => ({+ calls: scope === "personal"+ ? [{ id: "c1", agent_id: "mine", issue_id: "i1", chat_session_id: null, triggered_by: "me",+ tool_slug: "NOTION_CREATE_PAGE", action_class: "write", outcome: "ok", error: null,+ created_at: "2026-11-17T10:00:00Z" }]+ : [{ id: "c2", agent_id: "shared", issue_id: null, chat_session_id: "s1", triggered_by: "u2",+ tool_slug: "NOTION_SEARCH", action_class: "read", outcome: "ok", error: null,+ created_at: "2026-11-17T11:00:00Z" }],+ }) as never);+ vi.mocked(api.getIssue).mockResolvedValue({ id: "i1", identifier: "MUL-7" } as never);+ vi.mocked(api.updateAgentApps).mockImplementation(async (agentId, body) => {+ overview = {+ ...overview,+ agent_apps: [+ ...overview.agent_apps.filter((a) => a.agent_id !== agentId),+ ...body.apps.map((a) => ({ agent_id: agentId, toolkit_slug: a.toolkit_slug, account_scope: a.account_scope, level: a.level ?? "write" })),+ ],+ };+ return { apps: [] } as never;+ });+});+afterEach(() => {+ cleanup();+ vi.clearAllMocks();+});++function renderPage() {+ const adapter: NavigationAdapter = {+ push: vi.fn(), replace: vi.fn(), back: vi.fn(), pathname: "/acme/apps/notion",+ searchParams: new URLSearchParams(), hash: "", getShareableUrl: (p) => p,+ };+ const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });+ return renderWithI18n(+ <QueryClientProvider client={client}>+ <NavigationProvider value={adapter}>+ <AppDetailPage toolkitSlug="notion" />+ </NavigationProvider>+ </QueryClientProvider>,+ );+}++const agentSwitch = (agent: string) => screen.getByRole("switch", { name: `Let ${agent} use Notion` });++describe("AppDetailPage", () => {+ it("lists live agents with whose account each uses", async () => {+ renderPage();+ await waitFor(() => expect(agentSwitch("Mine")).toBeChecked());+ expect(agentSwitch("Shared")).toBeChecked();+ expect(agentSwitch("Other")).not.toBeChecked();+ expect(screen.queryByText("Gone")).not.toBeInTheDocument();+ expect(screen.getByText("Not using Notion")).toBeInTheDocument();+ });++ it("saves an agent's whole app list when it stops using the app", async () => {+ const user = userEvent.setup();+ renderPage();+ await waitFor(() => expect(agentSwitch("Mine")).not.toHaveAttribute("aria-disabled", "true"));+ await user.click(agentSwitch("Mine"));+ await waitFor(() => expect(api.updateAgentApps).toHaveBeenCalledWith("mine", {+ apps: [{ toolkit_slug: "gmail", account_scope: "personal", level: "read" }],+ }));+ await waitFor(() => expect(agentSwitch("Mine")).not.toBeChecked());+ });++ it("gives a member's agent the triggerer's account when enabled", async () => {+ overview.agent_apps = overview.agent_apps.filter((a) => a.agent_id !== "mine" || a.toolkit_slug !== "notion");+ const user = userEvent.setup();+ renderPage();+ await waitFor(() => expect(agentSwitch("Mine")).not.toHaveAttribute("aria-disabled", "true"));+ await user.click(agentSwitch("Mine"));+ await waitFor(() => expect(api.updateAgentApps).toHaveBeenCalledWith("mine", {+ apps: [+ { toolkit_slug: "gmail", account_scope: "personal", level: "read" },+ { toolkit_slug: "notion", account_scope: "personal", level: "write" },+ ],+ }));+ });++ it("keeps members off team-account agents and agents they can't edit", async () => {+ renderPage();+ await waitFor(() => expect(agentSwitch("Mine")).not.toHaveAttribute("aria-disabled", "true"));+ expect(agentSwitch("Shared")).toHaveAttribute("aria-disabled", "true");+ expect(agentSwitch("Other")).toHaveAttribute("aria-disabled", "true");+ });++ it("lets an admin change any agent", async () => {+ viewer.role = "admin";+ overview.can_manage = true;+ renderPage();+ await waitFor(() => expect(agentSwitch("Shared")).not.toHaveAttribute("aria-disabled", "true"));+ expect(agentSwitch("Other")).not.toHaveAttribute("aria-disabled", "true");+ });++ it("shows members only their own activity, and admins the team's too", async () => {+ const first = renderPage();+ expect(await screen.findByText("Create page")).toBeInTheDocument();+ await waitFor(() => expect(screen.getByRole("link", { name: "MUL-7" })).toHaveAttribute("href", "/acme/issues/MUL-7"));+ expect(screen.queryByText("Search")).not.toBeInTheDocument();+ expect(api.listAppActivity).toHaveBeenCalledTimes(1);+ first.unmount();++ overview.can_manage = true;+ renderPage();+ expect(await screen.findByText("Search")).toBeInTheDocument();+ const rows = screen.getAllByText(/^(Search|Create page)$/).map((el) => el.textContent);+ expect(rows).toEqual(["Search", "Create page"]);+ });++ it("offers a member to ask for a team account the workspace lacks", async () => {+ overview.team = [];+ vi.mocked(api.requestTeamApp).mockResolvedValue(undefined as never);+ const user = userEvent.setup();+ renderPage();+ await user.click(await screen.findByRole("button", { name: "Ask an admin" }));+ await waitFor(() => expect(api.requestTeamApp).toHaveBeenCalledWith("notion", undefined));+ });++ it("shows admins who asked for the team account and lets them decline it", async () => {+ overview = {+ ...overview, can_manage: true, team: [],+ team_requests: [{ toolkit_slug: "notion", requested_by: ["u2", "u3"], agent_ids: [], last_requested_at: "" }],+ };+ vi.mocked(api.dismissTeamAppRequests).mockResolvedValue(undefined as never);+ const user = userEvent.setup();+ renderPage();+ await screen.findAllByText("Requested · Name u2, Name u3");+ const team = document.querySelector('[data-account-row="team:notion"]') as HTMLElement;+ expect(within(team).getByRole("button", { name: "Connect" })).toBeInTheDocument();+ await user.click(within(team).getByRole("button", { name: "Decline" }));+ await waitFor(() => expect(api.dismissTeamAppRequests).toHaveBeenCalledWith("notion"));+ });+});diff --git a/packages/views/apps/components/app-detail-page.tsx b/packages/views/apps/components/app-detail-page.tsxnew file mode 100644index 0000000000..986956e59b--- /dev/null+++ b/packages/views/apps/components/app-detail-page.tsx@@ -0,0 +1,103 @@+"use client";++import { useQuery } from "@tanstack/react-query";+import { AlertCircle, Plug } from "@multica/ui/icons";+import { Button } from "@multica/ui/components/ui/button";+import { Skeleton } from "@multica/ui/components/ui/skeleton";+import { useWorkspaceId } from "@multica/core/hooks";+import { useWorkspacePaths } from "@multica/core/paths";+import { appCatalogOptions, appsOverviewOptions } from "@multica/core/connected-apps";+import { ComposioToolkitLogo } from "../../common/composio-toolkit-logo";+import { useComposioAvailable } from "../../common/use-composio-available";+import { CollectionPageState } from "../../layout/collection-page";+import { OBJECT_PAGE_BODY, ObjectIdentity, ObjectPage } from "../../layout/object-page";+import { useT } from "../../i18n";+import { useAppConnectReturn } from "../hooks/use-app-connect-return";+import { AppAccountsSection } from "./app-accounts-card";+import { AppActivityCard } from "./app-activity-card";+import { AppAgentsCard } from "./app-agents-card";+import { AppCapabilitiesCard } from "./app-capabilities-card";++const LAYOUT_ID = "multica_app_detail_layout";++/** One app: its accounts, which agents use it and as whom, and what they did. */+export function AppDetailPage({ toolkitSlug }: { toolkitSlug: string }) {+ const { t } = useT("settings");+ const { t: tl } = useT("layout");+ const wsId = useWorkspaceId();+ const paths = useWorkspacePaths();+ const available = useComposioAvailable();+ const overview = useQuery({ ...appsOverviewOptions(wsId), enabled: available });+ const catalog = useQuery({ ...appCatalogOptions(wsId), enabled: available });+ useAppConnectReturn();++ const entry = catalog.data?.apps.find((a) => a.slug === toolkitSlug);+ const name = entry?.name ?? toolkitSlug;+ const listSegment = { href: paths.apps(), label: tl(($) => $.nav.apps) };+ const leaf = overview.data || catalog.data+ ? <span className="truncate text-foreground">{name}</span>+ : <Skeleton className="h-4 w-32" />;++ if (!available) {+ return (+ <ObjectPage type="app" layoutId={LAYOUT_ID} segments={[listSegment]} leaf={leaf}>+ <CollectionPageState icon={Plug} title={t(($) => $.connected_apps.hub.unavailable)} />+ </ObjectPage>+ );+ }++ if (overview.isError) {+ return (+ <ObjectPage type="app" layoutId={LAYOUT_ID} segments={[listSegment]} leaf={leaf}>+ <CollectionPageState+ role="alert"+ tone="destructive"+ icon={AlertCircle}+ title={t(($) => $.connected_apps.load_failed)}+ actions={+ <Button variant="outline" size="sm" onClick={() => overview.refetch()}>+ {t(($) => $.connected_apps.hub.retry)}+ </Button>+ }+ />+ </ObjectPage>+ );+ }++ const data = overview.data;+ return (+ <ObjectPage+ type="app"+ layoutId={LAYOUT_ID}+ segments={[listSegment]}+ leaf={leaf}+ panel={+ data ? <AppCapabilitiesCard /> : undefined+ }+ >+ <div className={`${OBJECT_PAGE_BODY} space-y-8`}>+ <ObjectIdentity+ media={+ <ComposioToolkitLogo+ slug={toolkitSlug}+ name={name}+ fallbackLogo={entry?.logo}+ className="size-12 rounded-xl"+ />+ }+ title={name}+ description={entry?.category}+ />+ {data ? (+ <>+ <AppAccountsSection slug={toolkitSlug} name={name} logo={entry?.logo} overview={data} />+ <AppAgentsCard slug={toolkitSlug} name={name} entry={entry} overview={data} />+ <AppActivityCard slug={toolkitSlug} name={name} canManage={data.can_manage} />+ </>+ ) : (+ <p className="text-body text-muted-foreground">{t(($) => $.connected_apps.loading)}</p>+ )}+ </div>+ </ObjectPage>+ );+}diff --git a/packages/views/apps/components/app-status-label.tsx b/packages/views/apps/components/app-status-label.tsxnew file mode 100644index 0000000000..dcca0c4382--- /dev/null+++ b/packages/views/apps/components/app-status-label.tsx@@ -0,0 +1,54 @@+"use client";++import { AlertTriangle, Clock } from "@multica/ui/icons";+import { cn } from "@multica/ui/lib/utils";+import type { AppAccountStatus } from "../../common/app-status";+import { useT } from "../../i18n";++/** An account status in the shared vocabulary, with `detail` after it.+ * `label` rewords it for one context while keeping the status's look. */+export function AppStatusLabel({+ status,+ label: override,+ detail,+ className,+}: {+ status: AppAccountStatus;+ label?: string;+ detail?: string;+ className?: string;+}) {+ const { t } = useT("settings");+ const label = override ?? t(($) => $.connected_apps.status[status]);+ const text = <span className="truncate">{detail ? `${label} · ${detail}` : label}</span>;+ switch (status) {+ case "connected":+ return (+ <span className={cn("inline-flex min-w-0 items-center gap-1.5", className)}>+ <span aria-hidden="true" className="size-1.5 shrink-0 rounded-full bg-success" />+ {text}+ </span>+ );+ case "needs_reconnecting":+ return (+ <span className={cn("inline-flex min-w-0 items-center gap-1 text-warning", className)}>+ <AlertTriangle aria-hidden="true" className="size-3 shrink-0" />+ {text}+ </span>+ );+ case "requested":+ return (+ <span className={cn("inline-flex min-w-0 items-center gap-1 text-muted-foreground", className)}>+ <Clock aria-hidden="true" className="size-3 shrink-0" />+ {text}+ </span>+ );+ case "not_connected":+ return (+ <span className={cn("inline-flex min-w-0 items-center gap-1.5 text-muted-foreground", className)}>+ <span aria-hidden="true" className="size-1.5 shrink-0 rounded-full border border-muted-foreground" />+ {text}+ </span>+ );+ }+}diff --git a/packages/views/apps/components/apps-page.test.tsx b/packages/views/apps/components/apps-page.test.tsxnew file mode 100644index 0000000000..3599656776--- /dev/null+++ b/packages/views/apps/components/apps-page.test.tsx@@ -0,0 +1,302 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { useEffect, useState } from "react";+import { cleanup, fireEvent, 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 type { AppRequest, AppsOverview } from "@multica/core/types";+import { NavigationProvider, type NavigationAdapter } from "../../navigation";+import { renderWithI18n } from "../../test/i18n";+import { AppsPage } from "./apps-page";++vi.mock("@multica/core/api", () => ({ api: {+ getAppsOverview: vi.fn(), listAppCatalog: vi.fn(), listAgents: vi.fn(),+ updateAppSettings: vi.fn(), requestTeamApp: vi.fn(), connectApp: vi.fn(), listAppRequests: vi.fn(),+ getPersonalAppImpact: vi.fn(), getTeamAppImpact: vi.fn(), deleteComposioConnection: vi.fn(), dismissTeamAppRequests: vi.fn(),+} }));+vi.mock("@multica/core/hooks", () => ({ useWorkspaceId: () => "ws-1" }));+vi.mock("@multica/core/paths", () => ({+ useCurrentWorkspace: () => ({ id: "ws-1", name: "Acme", slug: "acme" }),+ useWorkspacePaths: () => ({ apps: () => "/acme/apps", appDetail: (slug: string) => `/acme/apps/${slug}` }),+}));+vi.mock("@multica/core/workspace/hooks", () => ({+ useActorName: () => ({ getActorName: (_type: string, id: string) => `Name ${id}` }),+}));+vi.mock("@multica/core/auth", () => {+ const state = { user: { id: "me" } };+ return { useAuthStore: (selector: (s: typeof state) => unknown) => selector(state) };+});+const composio = vi.hoisted(() => ({ available: true }));+vi.mock("../../common/use-composio-available", () => ({ useComposioAvailable: () => composio.available }));++let overview: AppsOverview;+const nav = { search: "" };+const replace = vi.fn();++beforeEach(() => {+ composio.available = true;+ nav.search = "";+ overview = {+ catalog_mode: "all", can_manage: false,+ team: [{ id: "t-notion", toolkit_slug: "notion", status: "active", connected_at: "", last_used_at: null }],+ personal: [],+ agent_apps: [+ { agent_id: "a1", toolkit_slug: "notion", account_scope: "team", level: "write" },+ { agent_id: "a1", toolkit_slug: "gmail", account_scope: "personal", level: "write" },+ { agent_id: "a2", toolkit_slug: "slack", account_scope: "team", level: "write" },+ ],+ };+ vi.mocked(api.getAppsOverview).mockImplementation(async () => overview);+ vi.mocked(api.listAppCatalog).mockResolvedValue({ catalog_mode: "all", apps: [+ { slug: "gmail", name: "Gmail", curated: true },+ { slug: "notion", name: "Notion", curated: true },+ { slug: "slack", name: "Slack", curated: true },+ { slug: "linear", name: "Linear", category: "Issues", curated: true },+ ] });+ vi.mocked(api.listAgents).mockResolvedValue([+ { id: "a1", name: "Support", archived_at: null },+ { id: "a2", name: "Triage", archived_at: null },+ ] as never);+ vi.mocked(api.requestTeamApp).mockResolvedValue(undefined as never);+ vi.mocked(api.listAppRequests).mockResolvedValue({ requests: [] } as never);+ vi.mocked(api.dismissTeamAppRequests).mockResolvedValue(undefined);+});+afterEach(() => {+ cleanup();+ vi.clearAllMocks();+});++// Re-renders with the new search on replace, like the web and desktop routers.+function RoutedAppsPage({ search }: { search: string }) {+ const [current, setCurrent] = useState(search);+ useEffect(() => setCurrent(search), [search]);+ const adapter: NavigationAdapter = {+ push: vi.fn(), back: vi.fn(), pathname: "/acme/apps",+ replace: (url) => {+ replace(url);+ setCurrent(url.split("?")[1] ?? "");+ },+ searchParams: new URLSearchParams(current), hash: "", getShareableUrl: (p) => p,+ };+ return (+ <NavigationProvider value={adapter}>+ <AppsPage />+ </NavigationProvider>+ );+}++function renderPage() {+ const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });+ const tree = (search: string) => (+ <QueryClientProvider client={client}>+ <RoutedAppsPage search={search} />+ </QueryClientProvider>+ );+ const view = renderWithI18n(tree(nav.search));+ return { ...view, navigate: (search: string) => view.rerender(tree(search)) };+}++describe("AppsPage", () => {+ it("groups apps in use, puts the ones needing attention first and counts them", async () => {+ renderPage();+ await waitFor(() =>+ expect(within(screen.getAllByRole("list")[0]!).getAllByRole("link").map((l) => l.textContent))+ .toEqual(["Gmail", "Slack", "Notion"]),+ );+ const list = screen.getAllByRole("list")[0];+ expect(screen.getByRole("tab", { name: /Needs attention/ })).toHaveTextContent("2");+ expect(within(list!).getByRole("link", { name: "Notion" })).toHaveAttribute("href", "/acme/apps/notion");+ expect(screen.getByRole("heading", { name: "Popular in Acme" })).toBeInTheDocument();+ expect(screen.getByRole("link", { name: "Linear" })).toBeInTheDocument();+ });++ it("asks an admin for a team account a member cannot connect", async () => {+ const user = userEvent.setup();+ renderPage();+ await user.click(await screen.findByRole("button", { name: "Ask an admin" }));+ await waitFor(() => expect(api.requestTeamApp).toHaveBeenCalledWith("slack", undefined));+ });++ it("opens the connect dialog instead of starting the flow", async () => {+ const user = userEvent.setup();+ renderPage();+ await user.click(await screen.findByRole("button", { name: "Connect" }));+ expect(api.connectApp).not.toHaveBeenCalled();+ expect(await screen.findByRole("dialog", { name: /Connect Gmail/ })).toBeVisible();+ });++ it("filters by search across every tab", async () => {+ const user = userEvent.setup();+ renderPage();+ await screen.findByRole("tab", { name: /In use/ });+ await user.click(screen.getByRole("tab", { name: /All apps/ }));+ await user.type(screen.getByRole("searchbox", { name: "Search apps" }), "iss");+ expect(within(screen.getAllByRole("list")[0]!).getAllByRole("link").map((l) => l.textContent)).toEqual(["Linear"]);+ });++ it("recovers an empty saved catalog only after an admin confirms", async () => {+ overview = { ...overview, catalog_mode: "custom", allowed_toolkits: [], can_manage: true };+ vi.mocked(api.updateAppSettings).mockImplementation(async () => {+ overview = { ...overview, catalog_mode: "all" };+ return { catalog_mode: "all", allowed_toolkits: [] };+ });+ const user = userEvent.setup();+ renderPage();+ 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 previous app list is hiding other apps.")).not.toBeInTheDocument());+ });++ it("shows members the saved catalog without a way to lift it", async () => {+ overview = { ...overview, catalog_mode: "custom", allowed_toolkits: [] };+ renderPage();+ expect(await screen.findByText("A previous app list is hiding other apps.")).toBeInTheDocument();+ expect(screen.queryByRole("button", { name: "Show all apps" })).not.toBeInTheDocument();+ });++ it("reports a hosted connect return once and drops its params", async () => {+ nav.search = "app_connected=gmail&keep=1";+ renderPage();+ await waitFor(() => expect(replace).toHaveBeenCalledWith("/acme/apps?keep=1"));+ });++ it("reloads accounts when the Desktop window is focused again", async () => {+ (window as { desktopAPI?: unknown }).desktopAPI = { pickDirectory: vi.fn() };+ try {+ renderPage();+ await screen.findByRole("tab", { name: /In use/ });+ expect(api.getAppsOverview).toHaveBeenCalledTimes(1);+ fireEvent.focus(window);+ await waitFor(() => expect(api.getAppsOverview).toHaveBeenCalledTimes(2));+ } finally {+ delete (window as { desktopAPI?: unknown }).desktopAPI;+ }+ });++ it("does not reload on focus on the web, where the flow returns to this tab", async () => {+ renderPage();+ await screen.findByRole("tab", { name: /In use/ });+ fireEvent.focus(window);+ await new Promise((resolve) => setTimeout(resolve, 20));+ expect(api.getAppsOverview).toHaveBeenCalledTimes(1);+ });++ it("says Apps are unavailable when the server has no Composio", () => {+ composio.available = false;+ renderPage();+ expect(screen.getByText("Apps aren't available on this server.")).toBeInTheDocument();+ expect(api.getAppsOverview).not.toHaveBeenCalled();+ });+});++function connectRequest(patch: Partial<AppRequest>): AppRequest {+ return {+ id: "r1", kind: "connect", status: "pending", agent_id: "a1", issue_id: "i1", chat_session_id: null,+ approver_user_id: "me", account_scope: "personal", toolkit_slug: "linear", tool_slug: "", action_class: "read",+ summary: "", error: null, reason: null, redacted: false, expires_at: "", decided_by: null, decided_at: null,+ created_at: "", ...patch,+ } as AppRequest;+}++describe("AppsPage › Accounts", () => {+ const row = (scope: "team" | "personal", slug: string) =>+ document.querySelector(`[data-account-row="${scope}:${slug}"]`) as HTMLElement;++ beforeEach(() => {+ nav.search = "tab=accounts";+ overview = {+ ...overview,+ team: [+ { id: "t-notion", toolkit_slug: "notion", status: "expired", connected_at: "", last_used_at: null },+ { id: "t-slack", toolkit_slug: "slack", status: "active", connected_at: "", last_used_at: null },+ ],+ team_requests: [{ toolkit_slug: "linear", requested_by: ["u2"], asked_by: ["u2"], agent_ids: ["a2"], last_requested_at: "" }],+ personal: [+ { id: "p-gmail", toolkit_slug: "gmail", status: "active", connected_at: "", last_used_at: null },+ { id: "p-old", toolkit_slug: "slack", status: "revoked", connected_at: "", last_used_at: null },+ ],+ };+ vi.mocked(api.listAppRequests).mockResolvedValue({ requests: [connectRequest({})] } as never);+ vi.mocked(api.getPersonalAppImpact).mockResolvedValue({+ agents: [{ id: "a1", name: "Support", workspace_id: "ws-1", workspace_name: "Acme", running: true }],+ });+ vi.mocked(api.deleteComposioConnection).mockResolvedValue(undefined as never);+ });++ it("opens from the URL with the team's accounts, then the viewer's, needs-action first", async () => {+ renderPage();+ const team = await screen.findByRole("region", { name: "Team accounts" });+ await within(team).findByText("Slack");+ expect(within(team).getAllByText(/^(Notion|Linear|Slack)$/).map((el) => el.textContent)).toEqual(["Notion", "Linear", "Slack"]);+ expect(screen.getByRole("tab", { name: /Accounts/ })).toHaveTextContent("5");+ expect(within(row("team", "notion")).getAllByText("Needs reconnecting").length).toBeGreaterThan(0);+ expect(within(row("team", "linear")).getAllByText(/Requested · admins notified/).length).toBeGreaterThan(0);+ expect(row("team", "linear")).toHaveTextContent("Name a2 needs it");+ // A member asks an admin; nothing connects an account apart from an app.+ expect(within(row("team", "notion")).getByRole("button", { name: "Ask an admin" })).toBeInTheDocument();+ expect(screen.queryByRole("button", { name: /Connect (team )?account/ })).not.toBeInTheDocument();++ const yours = screen.getByRole("region", { name: "Your accounts" });+ expect(row("personal", "gmail")).toHaveTextContent("used by Name a1");+ await waitFor(() => expect(row("personal", "linear")).toHaveTextContent("Name a1 needs it"));+ expect(within(row("personal", "linear")).getByRole("button", { name: "Connect" })).toBeInTheDocument();+ expect(within(yours).queryByText("Slack")).not.toBeInTheDocument();+ });++ it("gives an admin Connect and Decline on a requested team account", async () => {+ overview.can_manage = true;+ const user = userEvent.setup();+ renderPage();+ await screen.findByRole("region", { name: "Team accounts" }).then((team) => within(team).findByText("Linear"));+ expect(within(row("team", "linear")).getAllByText(/Requested · Name a2, Name u2/).length).toBeGreaterThan(0);+ expect(within(row("team", "notion")).getByRole("button", { name: "Reconnect" })).toBeInTheDocument();+ await user.click(within(row("team", "linear")).getByRole("button", { name: "Decline" }));+ await waitFor(() => expect(api.dismissTeamAppRequests).toHaveBeenCalledWith("linear"));+ });++ it("lets a member withdraw their own ask", async () => {+ overview.team_requests = [{ toolkit_slug: "linear", requested_by: ["me"], asked_by: ["me"], agent_ids: [], last_requested_at: "" }];+ const user = userEvent.setup();+ renderPage();+ await screen.findByRole("region", { name: "Team accounts" }).then((team) => within(team).findByText("Linear"));+ await user.click(within(row("team", "linear")).getByRole("button", { name: "Withdraw" }));+ await waitFor(() => expect(api.dismissTeamAppRequests).toHaveBeenCalledWith("linear"));+ });++ it("disconnects after listing the agents that lose the account", async () => {+ const user = userEvent.setup();+ renderPage();+ await screen.findByText("Gmail");+ await user.click(within(row("personal", "gmail")).getByRole("button", { name: "Gmail actions" }));+ await user.click(await screen.findByRole("menuitem", { name: "Disconnect" }));+ const dialog = await screen.findByRole("alertdialog", { name: "Disconnect Gmail?" });+ await waitFor(() => expect(within(dialog).getByText("Support")).toBeInTheDocument());+ await user.click(within(dialog).getByRole("button", { name: "Disconnect" }));+ await waitFor(() => expect(api.deleteComposioConnection).toHaveBeenCalledWith("p-gmail"));+ });++ it("filters accounts by search and keeps the tab in the URL", async () => {+ nav.search = "";+ const user = userEvent.setup();+ renderPage();+ await user.click(await screen.findByRole("tab", { name: /Accounts/ }));+ expect(replace).toHaveBeenLastCalledWith("/acme/apps?tab=accounts");+ await user.type(screen.getByRole("searchbox", { name: "Search apps" }), "not");+ const team = screen.getByRole("region", { name: "Team accounts" });+ expect(within(team).getByText("Notion")).toBeInTheDocument();+ expect(within(team).queryByText("Slack")).not.toBeInTheDocument();+ expect(within(screen.getByRole("region", { name: "Your accounts" })).getByText("You haven't connected any accounts in this workspace.")).toBeInTheDocument();+ });++ it("follows the URL when it changes outside the tabs, e.g. the sidebar link or Back", async () => {+ const { navigate } = renderPage();+ expect(await screen.findByRole("region", { name: "Team accounts" })).toBeInTheDocument();+ navigate("");+ await waitFor(() => expect(screen.getByRole("tab", { name: /In use/ })).toHaveAttribute("aria-selected", "true"));+ expect(screen.queryByRole("region", { name: "Team accounts" })).not.toBeInTheDocument();+ navigate("tab=accounts");+ expect(await screen.findByRole("region", { name: "Team accounts" })).toBeInTheDocument();+ });+});diff --git a/packages/views/apps/components/apps-page.tsx b/packages/views/apps/components/apps-page.tsxnew file mode 100644index 0000000000..48d019f9b6--- /dev/null+++ b/packages/views/apps/components/apps-page.tsx@@ -0,0 +1,252 @@+"use client";++import { useMemo, useState } from "react";+import { useQuery } from "@tanstack/react-query";+import { toast } from "sonner";+import { AlertCircle, Plug, Search } from "@multica/ui/icons";+import { Button } from "@multica/ui/components/ui/button";+import { Input } from "@multica/ui/components/ui/input";+import { Tabs, TabsList, TabsTrigger } from "@multica/ui/components/ui/tabs";+import { useAuthStore } from "@multica/core/auth";+import { useWorkspaceId } from "@multica/core/hooks";+import { useCurrentWorkspace } from "@multica/core/paths";+import {+ appCatalogOptions,+ appsOverviewOptions,+ useDismissTeamAppRequests,+ useRequestTeamApp,+ useRestoreAppAccess,+} from "@multica/core/connected-apps";+import { agentListOptions } from "@multica/core/workspace/queries";+import type { AppAccountScope } from "@multica/core/types";+import { ConnectAppDialog } from "../../common/connect-app-dialog";+import { SavedAppRestriction } from "../../common/saved-app-restriction";+import { useComposioAvailable } from "../../common/use-composio-available";+import { CollectionPageState } from "../../layout/collection-page";+import { PageHeader } from "../../layout/page-header";+import { useTeamAppAccess } from "../../common/use-team-app-access";+import { useT } from "../../i18n";+import { useNavigation } from "../../navigation";+import { useAppConnectReturn } from "../hooks/use-app-connect-return";+import { buildAppDirectory, matchesAppSearch, type DirectoryApp } from "../lib/directory";+import { AccountsList, useAccountRows } from "./accounts-list";+import { DirectoryCard, SetUpCard, type DirectoryCardHandlers } from "./directory-card";++const TABS = ["in_use", "attention", "accounts", "all"] as const;+type DirectoryTab = (typeof TABS)[number];++function parseTab(value: string | null): DirectoryTab {+ return (TABS as readonly string[]).includes(value ?? "") ? (value as DirectoryTab) : "in_use";+}++type ConnectTarget = { slug: string; name: string; logo?: string; scope: AppAccountScope };++/** The workspace's apps: what agents use, what needs someone, and the catalog. */+export function AppsPage() {+ const { t } = useT("settings");+ const { t: tl } = useT("layout");+ const available = useComposioAvailable();++ return (+ <div className="flex min-h-0 flex-1 flex-col">+ <PageHeader>+ <h1 className="flex min-w-0 flex-1 items-center gap-2 px-2 text-body font-medium">+ <Plug aria-hidden="true" className="size-4 shrink-0 text-muted-foreground" />+ <span className="truncate">{tl(($) => $.nav.apps)}</span>+ </h1>+ </PageHeader>+ {available ? (+ <AppsDirectory />+ ) : (+ <CollectionPageState icon={Plug} title={t(($) => $.connected_apps.hub.unavailable)} />+ )}+ </div>+ );+}++function AppsDirectory() {+ const { t } = useT("settings");+ const { t: tl } = useT("layout");+ const wsId = useWorkspaceId();+ const workspaceName = useCurrentWorkspace()?.name ?? t(($) => $.page.workspace_fallback);+ const viewerId = useAuthStore((s) => s.user?.id ?? null);+ const overview = useQuery(appsOverviewOptions(wsId));+ const teamAccess = useTeamAppAccess(overview.data);+ const catalog = useQuery(appCatalogOptions(wsId));+ const agents = useQuery(agentListOptions(wsId));+ const restore = useRestoreAppAccess();+ const requestTeam = useRequestTeamApp();+ const withdrawTeam = useDismissTeamAppRequests();+ const navigation = useNavigation();+ const tab = parseTab(navigation.searchParams.get("tab"));+ const [query, setQuery] = useState("");+ const [connecting, setConnecting] = useState<ConnectTarget | null>(null);+ const [asking, setAsking] = useState<string | null>(null);+ useAppConnectReturn();+ const accountRows = useAccountRows(overview.data, catalog.data?.apps ?? []);++ // The tab lives in the URL so a connect flow started here comes back to it.+ const setTab = (next: DirectoryTab) => {+ const params = new URLSearchParams(navigation.searchParams);+ if (next === "in_use") params.delete("tab");+ else params.set("tab", next);+ const search = params.toString();+ navigation.replace(`${navigation.pathname}${search ? `?${search}` : ""}`);+ };++ const directory = useMemo(() => {+ if (!overview.data) return null;+ const visibleAgents = agents.data+ ? new Set(agents.data.filter((a) => !a.archived_at).map((a) => a.id))+ : undefined;+ return buildAppDirectory({+ overview: overview.data,+ catalog: catalog.data?.apps ?? [],+ viewerId,+ agentIds: visibleAgents,+ });+ }, [overview.data, catalog.data, agents.data, viewerId]);++ const handlers: DirectoryCardHandlers = {+ asking,+ needsUpgrade: teamAccess.needsUpgrade,+ onConnect: (app, scope) => setConnecting({ slug: app.slug, name: app.name, logo: app.entry?.logo, scope }),+ onAsk: (app) => {+ setAsking(app.slug);+ requestTeam.mutateAsync({ slug: app.slug }).then(+ () => toast.success(t(($) => $.connected_apps.hub.toast_requested, { app: app.name })),+ (e: unknown) => toast.error(e instanceof Error && e.message ? e.message : t(($) => $.connected_apps.toast_failed)),+ ).finally(() => setAsking(null));+ },+ onWithdraw: (app) => {+ setAsking(app.slug);+ withdrawTeam.mutateAsync(app.slug).then(+ () => toast.success(t(($) => $.connected_apps.account_row.toast_withdrawn)),+ (e: unknown) => toast.error(e instanceof Error && e.message ? e.message : t(($) => $.connected_apps.toast_failed)),+ ).finally(() => setAsking(null));+ },+ };++ if (overview.isLoading) {+ return <p className="px-6 py-8 text-body text-muted-foreground">{t(($) => $.connected_apps.loading)}</p>;+ }+ if (overview.isError || !directory || !overview.data) {+ return (+ <CollectionPageState+ role="alert"+ tone="destructive"+ icon={AlertCircle}+ title={t(($) => $.connected_apps.load_failed)}+ actions={+ <Button variant="outline" size="sm" onClick={() => overview.refetch()}>+ {t(($) => $.connected_apps.hub.retry)}+ </Button>+ }+ />+ );+ }++ const lists: Record<Exclude<DirectoryTab, "accounts">, DirectoryApp[]> = {+ in_use: directory.inUse,+ attention: directory.attention,+ all: directory.all,+ };+ const shown = tab === "accounts" ? [] : lists[tab].filter((app) => matchesAppSearch(app, query));+ const needle = query.trim().toLowerCase();+ const matchesAccount = (name: string) => !needle || name.toLowerCase().includes(needle);+ const emptyText = query.trim()+ ? t(($) => $.connected_apps.hub.no_matches)+ : tab === "attention"+ ? t(($) => $.connected_apps.hub.empty_attention)+ : tab === "in_use"+ ? t(($) => $.connected_apps.hub.empty_in_use)+ : catalog.isLoading+ ? t(($) => $.connected_apps.loading)+ : t(($) => $.connected_apps.add.empty);+ const popular = tab === "in_use" && !query.trim() ? directory.popular : [];++ return (+ <div className="min-h-0 flex-1 overflow-y-auto">+ <div className="mx-auto w-full max-w-5xl space-y-6 px-6 py-8">+ <div className="space-y-1">+ <h2 className="text-title font-semibold">{tl(($) => $.nav.apps)}</h2>+ <p className="text-body text-muted-foreground">+ {t(($) => $.connected_apps.hub.description, { workspace: workspaceName })}+ </p>+ </div>++ {overview.data.catalog_mode !== "all" && (+ <SavedAppRestriction+ kind="catalog"+ onRestore={overview.data.can_manage ? () => restore.mutateAsync({ catalog: true }) : undefined}+ />+ )}++ <div className="flex flex-wrap items-center justify-between gap-3">+ <Tabs value={tab} onValueChange={(value) => setTab(value as DirectoryTab)}>+ <TabsList>+ <TabTrigger value="in_use" label={t(($) => $.connected_apps.hub.tabs.in_use)} count={directory.inUse.length} />+ <TabTrigger value="attention" label={t(($) => $.connected_apps.hub.tabs.attention)} count={directory.attention.length} />+ <TabTrigger value="accounts" label={t(($) => $.connected_apps.hub.tabs.accounts)} count={accountRows.team.length + accountRows.personal.length} />+ <TabTrigger value="all" label={t(($) => $.connected_apps.hub.tabs.all)} count={directory.all.length} />+ </TabsList>+ </Tabs>+ <div className="relative w-full sm:w-60">+ <Search aria-hidden="true" className="pointer-events-none absolute top-1/2 left-2.5 size-3.5 -translate-y-1/2 text-muted-foreground" />+ <Input+ type="search"+ value={query}+ onChange={(e) => setQuery(e.target.value)}+ placeholder={t(($) => $.connected_apps.hub.search)}+ aria-label={t(($) => $.connected_apps.hub.search)}+ className="pl-8"+ />+ </div>+ </div>++ {tab === "accounts" ? (+ <AccountsList overview={overview.data} rows={accountRows} matches={matchesAccount} />+ ) : shown.length > 0 ? (+ <ul className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">+ {shown.map((app) => <DirectoryCard key={app.slug} app={app} handlers={handlers} />)}+ </ul>+ ) : (+ <p className="rounded-lg border border-dashed px-4 py-6 text-center text-caption text-muted-foreground">+ {emptyText}+ </p>+ )}++ {popular.length > 0 && (+ <section className="space-y-3">+ <h3 className="text-body font-semibold">+ {t(($) => $.connected_apps.hub.popular, { workspace: workspaceName })}+ </h3>+ <ul className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">+ {popular.map((app) => <SetUpCard key={app.slug} app={app} />)}+ </ul>+ </section>+ )}+ </div>++ {connecting && (+ <ConnectAppDialog+ open+ onOpenChange={(open) => { if (!open) setConnecting(null); }}+ scope={connecting.scope}+ slug={connecting.slug}+ name={connecting.name}+ logo={connecting.logo}+ />+ )}+ </div>+ );+}++function TabTrigger({ value, label, count }: { value: DirectoryTab; label: string; count: number }) {+ return (+ <TabsTrigger value={value} className="px-2.5">+ {label}+ <span className="text-caption text-muted-foreground tabular-nums">{count}</span>+ </TabsTrigger>+ );+}diff --git a/packages/views/apps/components/directory-card.tsx b/packages/views/apps/components/directory-card.tsxnew file mode 100644index 0000000000..9c50b74a16--- /dev/null+++ b/packages/views/apps/components/directory-card.tsx@@ -0,0 +1,128 @@+"use client";++import { Loader2 } from "@multica/ui/icons";+import { Button, buttonVariants } from "@multica/ui/components/ui/button";+import { useWorkspacePaths } from "@multica/core/paths";+import { useActorName } from "@multica/core/workspace/hooks";+import type { AppAccountScope } from "@multica/core/types";+import { UpgradeToAddLink } from "../../billing";+import { useT } from "../../i18n";+import type { DirectoryApp } from "../lib/directory";+import { AppCard } from "./app-card";+import { AppStatusLabel } from "./app-status-label";++export interface DirectoryCardHandlers {+ onConnect: (app: DirectoryApp, scope: AppAccountScope) => void;+ onAsk: (app: DirectoryApp) => void;+ onWithdraw: (app: DirectoryApp) => void;+ /** Slug whose admin request is being sent or withdrawn. */+ asking: string | null;+ /** Whether a team account for this app is one the plan does not include. */+ needsUpgrade: (slug: string) => boolean;+}++/** An app in use: whose account it acts as, where that stands, and who uses it. */+export function DirectoryCard({ app, handlers }: { app: DirectoryApp; handlers: DirectoryCardHandlers }) {+ const { t } = useT("settings");+ const paths = useWorkspacePaths();+ const { getActorName } = useActorName();++ if (!app.inUse && !app.request) return <SetUpCard app={app} />;++ const scopeLine =+ app.scopes.length === 2+ ? t(($) => $.connected_apps.hub.scope_both)+ : app.scopes[0] === "team"+ ? t(($) => $.connected_apps.hub.scope_team)+ : t(($) => $.connected_apps.hub.scope_personal);+ const asked = app.request && app.status === "requested"+ ? t(($) => $.connected_apps.hub.members_asked, { count: app.request.requested_by.length })+ : undefined;+ const usage =+ app.agentIds.length > 0+ ? t(($) => $.connected_apps.hub.used_by, { agents: app.agentIds.map((id) => getActorName("agent", id)).join(", ") })+ : app.request && app.request.agent_ids.length > 0+ ? t(($) => $.connected_apps.hub.wanted_by, { agents: app.request.agent_ids.map((id) => getActorName("agent", id)).join(", ") })+ : app.request+ ? t(($) => $.connected_apps.hub.asked_by, { names: app.request.requested_by.map((id) => getActorName("member", id)).join(", ") })+ : null;++ return (+ <AppCard+ slug={app.slug}+ name={app.name}+ logo={app.entry?.logo}+ href={paths.appDetail(app.slug)}+ subtitle={scopeLine}+ action={<DirectoryAction app={app} handlers={handlers} />}+ >+ {app.status ? <p className="flex min-w-0"><AppStatusLabel status={app.status} detail={asked} /></p> : null}+ {usage ? <p className="truncate">{usage}</p> : null}+ </AppCard>+ );+}++export function SetUpCard({ app }: { app: DirectoryApp }) {+ const { t } = useT("settings");+ const paths = useWorkspacePaths();+ return (+ <AppCard+ slug={app.slug}+ name={app.name}+ logo={app.entry?.logo}+ href={paths.appDetail(app.slug)}+ subtitle={app.entry?.category}+ // The whole card already links to the app; this only labels it.+ action={+ <span aria-hidden="true" className={buttonVariants({ variant: "outline", size: "xs" })}>+ {t(($) => $.connected_apps.hub.set_up)}+ </span>+ }+ />+ );+}++function DirectoryAction({ app, handlers }: { app: DirectoryApp; handlers: DirectoryCardHandlers }) {+ const { t } = useT("settings");+ const action = app.action;+ if (!action || action.kind === "set_up") return null;+ if (action.kind === "connect") {+ if (action.scope === "team" && handlers.needsUpgrade(app.slug)) return <UpgradeToAddLink />;+ return (+ <Button+ size="xs"+ variant={action.reconnect ? "default" : "outline"}+ onClick={() => handlers.onConnect(app, action.scope)}+ >+ {action.reconnect ? t(($) => $.connected_apps.hub.reconnect) : t(($) => $.connected_apps.hub.connect)}+ </Button>+ );+ }+ const asking = handlers.asking === app.slug;+ if (action.kind === "withdraw") {+ return (+ <Button+ size="xs"+ variant="ghost"+ disabled={handlers.asking !== null}+ aria-busy={asking}+ onClick={() => handlers.onWithdraw(app)}+ >+ {asking && <Loader2 className="animate-spin" />}+ {t(($) => $.connected_apps.account_row.withdraw)}+ </Button>+ );+ }+ return (+ <Button+ size="xs"+ variant="outline"+ disabled={handlers.asking !== null}+ aria-busy={asking}+ onClick={() => handlers.onAsk(app)}+ >+ {asking && <Loader2 className="animate-spin" />}+ {t(($) => $.connected_apps.hub.ask_admin)}+ </Button>+ );+}diff --git a/packages/views/apps/components/disconnect-account-dialog.tsx b/packages/views/apps/components/disconnect-account-dialog.tsxnew file mode 100644index 0000000000..fdb3b9dbff--- /dev/null+++ b/packages/views/apps/components/disconnect-account-dialog.tsx@@ -0,0 +1,126 @@+"use client";++import { useQuery } from "@tanstack/react-query";+import { toast } from "sonner";+import { Loader2 } from "@multica/ui/icons";+import {+ AlertDialog,+ AlertDialogAction,+ AlertDialogCancel,+ AlertDialogContent,+ AlertDialogDescription,+ AlertDialogFooter,+ AlertDialogHeader,+ AlertDialogTitle,+} from "@multica/ui/components/ui/alert-dialog";+import { useWorkspaceId } from "@multica/core/hooks";+import {+ personalAppImpactOptions,+ teamAppImpactOptions,+ useDisconnectPersonalApp,+ useDisconnectTeamApp,+} from "@multica/core/connected-apps";+import type { AppAccountScope } from "@multica/core/types";+import { ComposioToolkitLogo } from "../../common/composio-toolkit-logo";+import { useT } from "../../i18n";+import { AccountOwner } from "./account-row";++interface ImpactAgent {+ id: string;+ name: string;+ running?: boolean;+}++/**+ * Disconnecting an account asks the same question for both owners: these+ * agents act as it, and their next step asks again — the admins for a team+ * account, you for yours.+ */+export function DisconnectAccountDialog({+ scope,+ connectionId,+ slug,+ name,+ logo,+ onClose,+}: {+ scope: AppAccountScope;+ connectionId: string;+ slug: string;+ name: string;+ logo?: string;+ onClose: () => void;+}) {+ const { t } = useT("settings");+ const wsId = useWorkspaceId();+ const team = scope === "team";+ const teamImpact = useQuery({ ...teamAppImpactOptions(wsId, slug), enabled: team });+ const personalImpact = useQuery({ ...personalAppImpactOptions(wsId, connectionId), enabled: !team });+ const disconnectTeam = useDisconnectTeamApp();+ const disconnectPersonal = useDisconnectPersonalApp();+ const impact = team ? teamImpact : personalImpact;+ const pending = team ? disconnectTeam.isPending : disconnectPersonal.isPending;+ const agents: ImpactAgent[] = team ? (teamImpact.data?.agents ?? []) : (personalImpact.data?.agents ?? []);+ const activeRuns = team ? (teamImpact.data?.active_tasks ?? 0) : 0;++ const confirm = () =>+ (team ? disconnectTeam : disconnectPersonal).mutateAsync(connectionId).then(+ () => {+ toast.success(t(($) => $.connected_apps.toast_disconnected));+ onClose();+ },+ () => toast.error(t(($) => $.connected_apps.toast_failed)),+ );++ return (+ <AlertDialog open onOpenChange={(open) => !open && !pending && onClose()}>+ <AlertDialogContent className="sm:max-w-md">+ <AlertDialogHeader>+ <div className="flex items-center gap-3">+ <ComposioToolkitLogo slug={slug} name={name} fallbackLogo={logo} className="size-8 shrink-0" />+ <div className="min-w-0 space-y-0.5 text-left">+ <AlertDialogTitle>{t(($) => $.connected_apps.disconnect_dialog.title, { app: name })}</AlertDialogTitle>+ <AccountOwner scope={scope} />+ </div>+ </div>+ <AlertDialogDescription>+ {team+ ? t(($) => $.connected_apps.disconnect_dialog.team_body, { app: name })+ : t(($) => $.connected_apps.disconnect_dialog.personal_body, { app: name })}+ </AlertDialogDescription>+ </AlertDialogHeader>+ {impact.isLoading ? (+ <Loader2 className="size-4 animate-spin text-muted-foreground" />+ ) : impact.isError ? (+ <p className="text-caption text-muted-foreground">{t(($) => $.connected_apps.disconnect_dialog.impact_failed)}</p>+ ) : agents.length === 0 ? (+ <p className="text-caption text-muted-foreground">{t(($) => $.connected_apps.disconnect_dialog.no_agents)}</p>+ ) : (+ <ul className="divide-y rounded-lg border" aria-label={t(($) => $.connected_apps.disconnect_dialog.agents)}>+ {agents.map((agent) => (+ <li key={agent.id} className="flex items-center gap-2 px-3 py-2 text-body">+ <span className="min-w-0 flex-1 truncate font-medium">{agent.name}</span>+ {agent.running && (+ <span className="shrink-0 text-caption text-warning">+ {t(($) => $.connected_apps.disconnect_dialog.running)}+ </span>+ )}+ </li>+ ))}+ </ul>+ )}+ {activeRuns > 0 && (+ <p className="text-caption text-warning">+ {t(($) => $.connected_apps.disconnect_dialog.active_runs, { count: activeRuns })}+ </p>+ )}+ <AlertDialogFooter>+ <AlertDialogCancel disabled={pending}>{t(($) => $.connected_apps.disconnect_dialog.cancel)}</AlertDialogCancel>+ <AlertDialogAction variant="destructive" disabled={pending} aria-busy={pending} onClick={confirm}>+ {t(($) => $.connected_apps.disconnect_dialog.confirm)}+ </AlertDialogAction>+ </AlertDialogFooter>+ </AlertDialogContent>+ </AlertDialog>+ );+}diff --git a/packages/views/apps/hooks/use-app-connect-return.ts b/packages/views/apps/hooks/use-app-connect-return.tsnew file mode 100644index 0000000000..858e756f2c--- /dev/null+++ b/packages/views/apps/hooks/use-app-connect-return.ts@@ -0,0 +1,75 @@+"use client";++import { useEffect, useRef } from "react";+import { useQueryClient } from "@tanstack/react-query";+import { toast } from "sonner";+import { useWorkspaceId } from "@multica/core/hooks";+import { FEATURE_LOCKED_CODE, workspaceFeatureKeys } from "@multica/core/billing";+import { connectedAppsKeys } from "@multica/core/connected-apps";+import { useT } from "../../i18n";+import { useNavigation } from "../../navigation";+import { isDesktopShell } from "../../platform";++const CONNECT_FAILED = "composio_connect_failed";++/**+ * The hosted connect flow comes back to the page that started it with+ * `?app_connected=<slug>` or `?app_connect_error=<slug>`; flows started+ * without a return path land with `?connected=<slug>` or+ * `?error=composio_connect_failed`. Report the result once, then drop the+ * params so a refresh does not repeat it. A team account the plan refused+ * also carries `app_connect_error_reason` / `reason=feature_locked`; it shows+ * the plan message and refetches the plan instead of asking for a retry.+ * `tab` rewrites the settings tab of+ * a retired link that was redirected here.+ *+ * Desktop finishes the flow in the system browser, so that return never+ * reaches the window; reload the accounts when it is focused again instead.+ */+export function useAppConnectReturn({ tab }: { tab?: string } = {}) {+ const { t } = useT("settings");+ const { t: tBilling } = useT("billing");+ const wsId = useWorkspaceId();+ const qc = useQueryClient();+ const navigation = useNavigation();+ const params = navigation.searchParams;+ const connected = params.get("app_connected") ?? params.get("connected");+ const failed = params.get("app_connect_error") ?? (params.get("error") === CONNECT_FAILED ? CONNECT_FAILED : null);+ const locked = (params.get("app_connect_error_reason") ?? params.get("reason")) === FEATURE_LOCKED_CODE;+ const consumed = useRef<string | null>(null);++ useEffect(() => {+ const key = connected ? `connected:${connected}` : failed ? `failed:${failed}` : null;+ if (!key || consumed.current === key) return;+ consumed.current = key;+ if (connected) {+ toast.success(t(($) => $.connected_apps.toast_connected));+ void qc.invalidateQueries({ queryKey: connectedAppsKeys.all(wsId) });+ } else if (locked) {+ toast.error(tBilling(($) => $.paid_feature.locked_error));+ void qc.invalidateQueries({ queryKey: workspaceFeatureKeys.all(wsId) });+ } else {+ toast.error(t(($) => $.connected_apps.toast_connect_failed));+ }+ const next = new URLSearchParams(params);+ for (const k of ["app_connected", "app_connect_error", "app_connect_error_reason", "connected", "scope", "integration"]) next.delete(k);+ if (next.get("error") === CONNECT_FAILED) {+ next.delete("error");+ next.delete("reason");+ }+ if (tab) next.set("tab", tab);+ const search = next.toString();+ navigation.replace(`${navigation.pathname}${search ? `?${search}` : ""}`);+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [connected, failed]);++ useEffect(() => {+ if (!isDesktopShell()) return;+ const refresh = () => {+ void qc.invalidateQueries({ queryKey: connectedAppsKeys.overview(wsId) });+ void qc.invalidateQueries({ queryKey: connectedAppsKeys.myPendingRequests(wsId) });+ };+ window.addEventListener("focus", refresh);+ return () => window.removeEventListener("focus", refresh);+ }, [qc, wsId]);+}diff --git a/packages/views/apps/index.ts b/packages/views/apps/index.tsnew file mode 100644index 0000000000..a4c9cf08d6--- /dev/null+++ b/packages/views/apps/index.ts@@ -0,0 +1,8 @@+export { AppsPage } from "./components/apps-page";+export { AppDetailPage } from "./components/app-detail-page";+export { AccountMenu } from "./components/account-menu";+export { AppAccountDialog } from "./components/app-account-dialog";+export { AppStatusLabel } from "./components/app-status-label";+export { DisconnectAccountDialog } from "./components/disconnect-account-dialog";+export { AccountRow } from "./components/account-row";+export { useAppConnectReturn } from "./hooks/use-app-connect-return";diff --git a/packages/views/apps/lib/agent-apps.ts b/packages/views/apps/lib/agent-apps.tsnew file mode 100644index 0000000000..0243bb1784--- /dev/null+++ b/packages/views/apps/lib/agent-apps.ts@@ -0,0 +1,27 @@+import type { AppAccountScope, AppsOverview, UpdateAgentAppsRequest } from "@multica/core/types";++/**+ * An agent's full app list with one app set to `scope`, or removed when+ * `scope` is null. Saving replaces the agent's whole list, so its other apps+ * and every level ride along unchanged.+ */+export function agentAppsWith(+ overview: AppsOverview,+ agentId: string,+ slug: string,+ scope: AppAccountScope | null,+): UpdateAgentAppsRequest {+ const current = overview.agent_apps.filter((a) => a.agent_id === agentId);+ const existing = current.find((a) => a.toolkit_slug === slug);+ const others = current.filter((a) => a.toolkit_slug !== slug);+ const apps = others.map((a) => ({+ toolkit_slug: a.toolkit_slug,+ account_scope: a.account_scope,+ level: a.level,+ }));+ if (scope) {+ apps.push({ toolkit_slug: slug, account_scope: scope, level: existing?.level ?? "write" });+ }+ return { apps };+}+diff --git a/packages/views/apps/lib/directory.test.ts b/packages/views/apps/lib/directory.test.tsnew file mode 100644index 0000000000..847ccffba9--- /dev/null+++ b/packages/views/apps/lib/directory.test.ts@@ -0,0 +1,190 @@+// @vitest-environment node+import { describe, expect, it } from "vitest";+import type { AppCatalogEntry, AppConnection, AppsOverview } from "@multica/core/types";+import { buildAppDirectory, matchesAppSearch } from "./directory";+import { agentAppsWith } from "./agent-apps";++function connection(slug: string, status: AppConnection["status"] = "active"): AppConnection {+ return { id: `${slug}-${status}`, toolkit_slug: slug, status, connected_at: "", last_used_at: null };+}++function overview(patch: Partial<AppsOverview> = {}): AppsOverview {+ return { catalog_mode: "all", can_manage: false, team: [], personal: [], agent_apps: [], ...patch };+}++const catalog: AppCatalogEntry[] = [+ { slug: "gmail", name: "Gmail", category: "Email", curated: true },+ { slug: "notion", name: "Notion", category: "Docs", curated: true },+ { slug: "slack", name: "Slack", category: "Chat", curated: true },+ { slug: "zendesk", name: "Zendesk", category: "Support", curated: false },+];++const build = (o: AppsOverview, extra: { viewerId?: string; agentIds?: Set<string> } = {}) =>+ buildAppDirectory({ overview: o, catalog, viewerId: extra.viewerId ?? "me", agentIds: extra.agentIds });++const slugs = (apps: { slug: string }[]) => apps.map((a) => a.slug);++describe("buildAppDirectory", () => {+ it("counts an app in use when it has an account or an agent uses it", () => {+ const dir = build(overview({+ team: [connection("notion")],+ personal: [connection("slack")],+ agent_apps: [{ agent_id: "a1", toolkit_slug: "gmail", account_scope: "personal", level: "write" }],+ }));+ expect(slugs(dir.inUse)).toEqual(["gmail", "notion", "slack"]);+ expect(slugs(dir.all)).toEqual(["gmail", "notion", "slack", "zendesk"]);+ expect(slugs(dir.popular)).toEqual([]);+ });++ it("flags an app agents use through an account that is missing or expired", () => {+ const dir = build(overview({+ team: [connection("notion", "expired")],+ agent_apps: [+ { agent_id: "a1", toolkit_slug: "gmail", account_scope: "personal", level: "write" },+ { agent_id: "a1", toolkit_slug: "slack", account_scope: "team", level: "write" },+ { agent_id: "a1", toolkit_slug: "notion", account_scope: "team", level: "write" },+ ],+ }));+ const byslug = Object.fromEntries(dir.all.map((a) => [a.slug, a]));+ expect(slugs(dir.attention)).toEqual(["gmail", "notion", "slack"]);+ expect(byslug.gmail).toMatchObject({+ status: "not_connected",+ action: { kind: "connect", scope: "personal", reconnect: false },+ });+ expect(byslug.slack).toMatchObject({ status: "not_connected", action: { kind: "ask_admin" } });+ // Members cannot reconnect a team account; they ask an admin to.+ expect(byslug.notion).toMatchObject({ status: "needs_reconnecting", action: { kind: "ask_admin" } });+ });++ it("lets an admin connect or reconnect the team account", () => {+ const dir = build(overview({+ can_manage: true,+ team: [connection("notion", "expired")],+ agent_apps: [{ agent_id: "a1", toolkit_slug: "slack", account_scope: "team", level: "write" }],+ }));+ const byslug = Object.fromEntries(dir.all.map((a) => [a.slug, a]));+ expect(byslug.slack!.action).toEqual({ kind: "connect", scope: "team", reconnect: false });+ expect(byslug.notion!.action).toEqual({ kind: "connect", scope: "team", reconnect: true });+ });++ it("shows the most pressing status across both accounts", () => {+ const dir = build(overview({+ team: [connection("gmail")],+ personal: [connection("gmail", "expired")],+ agent_apps: [{ agent_id: "a1", toolkit_slug: "gmail", account_scope: "team", level: "write" }],+ }));+ const gmail = dir.all.find((a) => a.slug === "gmail")!;+ expect(gmail.scopes).toEqual(["team", "personal"]);+ expect(gmail).toMatchObject({+ status: "needs_reconnecting",+ statusScope: "personal",+ needsAttention: true,+ action: { kind: "connect", scope: "personal", reconnect: true },+ });+ });++ it("lists apps that need attention first among those in use", () => {+ const dir = build(overview({+ team: [connection("gmail"), connection("notion")],+ agent_apps: [{ agent_id: "a1", toolkit_slug: "slack", account_scope: "team", level: "write" }],+ }));+ expect(slugs(dir.inUse)).toEqual(["slack", "gmail", "notion"]);+ });++ it("does not flag connected accounts", () => {+ const dir = build(overview({+ team: [connection("notion")],+ agent_apps: [{ agent_id: "a1", toolkit_slug: "notion", account_scope: "team", level: "write" }],+ }));+ expect(dir.attention).toEqual([]);+ expect(dir.inUse[0]).toMatchObject({ slug: "notion", status: "connected", action: null, agentIds: ["a1"] });+ });++ it("puts open team requests in front of admins only, and marks the viewer's own", () => {+ const requests = [{ toolkit_slug: "slack", requested_by: ["me", "u2"], asked_by: ["me", "u2"], agent_ids: [], last_requested_at: "" }];+ const member = build(overview({ team_requests: requests }));+ const slack = member.all.find((a) => a.slug === "slack")!;+ expect(slack).toMatchObject({ inUse: false, needsAttention: false, scopes: ["team"], action: { kind: "withdraw" } });+ expect(slugs(member.popular)).not.toContain("slack");++ const other = build(overview({ team_requests: requests }), { viewerId: "u3" });+ expect(other.all.find((a) => a.slug === "slack")!.action).toEqual({ kind: "ask_admin" });++ const admin = build(overview({ can_manage: true, team_requests: requests }));+ expect(slugs(admin.attention)).toEqual(["slack"]);+ expect(admin.attention[0]!.action).toEqual({ kind: "connect", scope: "team", reconnect: false });+ });++ it("ignores requests once the team account exists", () => {+ const dir = build(overview({+ can_manage: true,+ team: [connection("slack")],+ team_requests: [{ toolkit_slug: "slack", requested_by: ["u2"], agent_ids: [], last_requested_at: "" }],+ }));+ expect(dir.attention).toEqual([]);+ expect(dir.all.find((a) => a.slug === "slack")!.request).toBeUndefined();+ });++ it("leaves out archived agents and revoked accounts", () => {+ const dir = build(+ overview({+ personal: [connection("notion", "revoked")],+ agent_apps: [{ agent_id: "archived", toolkit_slug: "gmail", account_scope: "personal", level: "write" }],+ }),+ { agentIds: new Set(["a1"]) },+ );+ expect(dir.inUse).toEqual([]);+ expect(dir.attention).toEqual([]);+ });++ it("offers curated apps nobody uses as popular, and set-up for unused ones", () => {+ const dir = build(overview({ team: [connection("notion")] }));+ expect(slugs(dir.popular)).toEqual(["gmail", "slack"]);+ expect(dir.popular[0]!.action).toEqual({ kind: "set_up" });+ });++ it("lists accounts for apps the catalog no longer shows after the catalog", () => {+ const dir = build(overview({ team: [connection("legacy-crm")] }));+ expect(slugs(dir.all)).toEqual(["gmail", "notion", "slack", "zendesk", "legacy-crm"]);+ expect(dir.all.at(-1)!.name).toBe("legacy-crm");+ });+});++describe("matchesAppSearch", () => {+ const [gmail] = build(overview()).all;+ it.each([["", true], ["gm", true], ["GMAIL", true], ["email", true], ["notion", false]])(+ "matches %j: %s",+ (query, expected) => {+ expect(matchesAppSearch(gmail!, query)).toBe(expected);+ },+ );+});++describe("agentAppsWith", () => {+ const base = overview({+ agent_apps: [+ { agent_id: "a1", toolkit_slug: "gmail", account_scope: "personal", level: "read" },+ { agent_id: "a1", toolkit_slug: "notion", account_scope: "team", level: "write" },+ { agent_id: "a2", toolkit_slug: "slack", account_scope: "team", level: "write" },+ ],+ });++ it("keeps the agent's other apps and levels when one changes", () => {+ expect(agentAppsWith(base, "a1", "gmail", "team")).toEqual({+ apps: [+ { toolkit_slug: "notion", account_scope: "team", level: "write" },+ { toolkit_slug: "gmail", account_scope: "team", level: "read" },+ ],+ });+ });++ it("adds a new app with write access and removes one with null", () => {+ expect(agentAppsWith(base, "a2", "gmail", "personal").apps).toEqual([+ { toolkit_slug: "slack", account_scope: "team", level: "write" },+ { toolkit_slug: "gmail", account_scope: "personal", level: "write" },+ ]);+ expect(agentAppsWith(base, "a1", "notion", null).apps).toEqual([+ { toolkit_slug: "gmail", account_scope: "personal", level: "read" },+ ]);+ });+});diff --git a/packages/views/apps/lib/directory.ts b/packages/views/apps/lib/directory.tsnew file mode 100644index 0000000000..518100033a--- /dev/null+++ b/packages/views/apps/lib/directory.ts@@ -0,0 +1,191 @@+import type {+ AppAccountScope,+ AppCatalogEntry,+ AppTeamRequest,+ AppsOverview,+} from "@multica/core/types";+import {+ accountAction,+ accountFor,+ appAccountStatus,+ teamRequestFor,+ viewerTeamAsk,+ type AppAccountStatus,+} from "../../common/app-status";++/** The one thing a card offers. Connecting always goes through the connect+ * dialog; "set up" opens the app's page. */+export type AppCardAction =+ | { kind: "connect"; scope: AppAccountScope; reconnect: boolean }+ | { kind: "ask_admin" }+ | { kind: "withdraw" }+ | { kind: "set_up" };++export interface DirectoryApp {+ slug: string;+ name: string;+ entry?: AppCatalogEntry;+ /** Accounts the app involves: connected ones and the ones agents use. */+ scopes: AppAccountScope[];+ /** The status to show, the most pressing of `scopes`; null when unused. */+ status: AppAccountStatus | null;+ statusScope: AppAccountScope | null;+ agentIds: string[];+ /** Open team-account request, when the workspace has no team account. */+ request?: AppTeamRequest;+ inUse: boolean;+ needsAttention: boolean;+ action: AppCardAction | null;+}++export interface AppDirectory {+ inUse: DirectoryApp[];+ attention: DirectoryApp[];+ all: DirectoryApp[];+ /** Curated apps nobody uses yet. */+ popular: DirectoryApp[];+}++const SEVERITY: Record<AppAccountStatus, number> = {+ needs_reconnecting: 3,+ not_connected: 2,+ requested: 1,+ connected: 0,+};++const POPULAR_LIMIT = 6;++/**+ * Groups the workspace's apps for the Apps page. `agentIds` limits agent+ * usage to the agents the viewer can see (archived ones excluded).+ */+export function buildAppDirectory({+ overview,+ catalog,+ viewerId,+ agentIds,+}: {+ overview: AppsOverview;+ catalog: AppCatalogEntry[];+ viewerId: string | null;+ agentIds?: ReadonlySet<string>;+}): AppDirectory {+ const entries = new Map(catalog.map((entry) => [entry.slug, entry]));+ const slugs = new Set<string>(catalog.map((entry) => entry.slug));+ for (const c of [...overview.team, ...overview.personal]) {+ if (c.status !== "revoked") slugs.add(c.toolkit_slug);+ }+ const agentApps = overview.agent_apps.filter((a) => !agentIds || agentIds.has(a.agent_id));+ for (const a of agentApps) slugs.add(a.toolkit_slug);++ const apps = new Map(+ [...slugs].map((slug) => [+ slug,+ describeApp(slug, entries.get(slug), overview, agentApps, viewerId),+ ]),+ );+ const described = [...apps.values()];+ const byName = (a: DirectoryApp, b: DirectoryApp) => a.name.localeCompare(b.name);+ const inCatalog = catalog.map((entry) => apps.get(entry.slug)!);+ return {+ inUse: described+ .filter((app) => app.inUse)+ .sort((a, b) => Number(b.needsAttention) - Number(a.needsAttention) || byName(a, b)),+ attention: described.filter((app) => app.needsAttention).sort(byName),+ all: inCatalog.concat(described.filter((app) => !entries.has(app.slug)).sort(byName)),+ popular: inCatalog+ .filter((app) => app.entry?.curated && !app.inUse && !app.request)+ .slice(0, POPULAR_LIMIT),+ };+}++function describeApp(+ slug: string,+ entry: AppCatalogEntry | undefined,+ overview: AppsOverview,+ agentApps: AppsOverview["agent_apps"],+ viewerId: string | null,+): DirectoryApp {+ const uses = agentApps.filter((a) => a.toolkit_slug === slug);+ const usedScopes = new Set(uses.map((a) => a.account_scope));+ const request = teamRequestFor(overview, slug);+ const hasTeam = !!accountFor(overview, "team", slug);+ const hasPersonal = !!accountFor(overview, "personal", slug);+ const scopes: AppAccountScope[] = [];+ if (hasTeam || usedScopes.has("team") || (request && !hasTeam)) scopes.push("team");+ if (hasPersonal || usedScopes.has("personal")) scopes.push("personal");++ let status: AppAccountStatus | null = null;+ let statusScope: AppAccountScope | null = null;+ for (const scope of scopes) {+ const next = appAccountStatus(overview, scope, slug);+ if (status === null || SEVERITY[next] > SEVERITY[status]) {+ status = next;+ statusScope = scope;+ }+ }++ const blocked = (scope: AppAccountScope) =>+ usedScopes.has(scope) && appAccountStatus(overview, scope, slug) !== "connected";+ const needsAttention =+ blocked("team") ||+ blocked("personal") ||+ appAccountStatus(overview, "team", slug) === "needs_reconnecting" ||+ appAccountStatus(overview, "personal", slug) === "needs_reconnecting" ||+ (overview.can_manage && !!request && !hasTeam);++ return {+ slug,+ name: entry?.name || slug,+ entry,+ scopes,+ status,+ statusScope,+ agentIds: [...new Set(uses.map((a) => a.agent_id))],+ request: hasTeam ? undefined : request,+ inUse: hasTeam || hasPersonal || uses.length > 0,+ needsAttention,+ action: cardAction(slug, status, statusScope, overview, viewerId),+ };+}++function cardAction(+ slug: string,+ status: AppAccountStatus | null,+ scope: AppAccountScope | null,+ overview: AppsOverview,+ viewerId: string | null,+): AppCardAction | null {+ if (status === null || scope === null) return { kind: "set_up" };+ const action = accountAction({+ scope,+ status,+ canManage: overview.can_manage,+ // The card swaps Connect for the upgrade link itself.+ needsUpgrade: false,+ viewerAsk: scope === "team" ? viewerTeamAsk(overview, slug, viewerId) : null,+ });+ switch (action) {+ case "connect":+ case "upgrade":+ return { kind: "connect", scope, reconnect: false };+ case "reconnect":+ return { kind: "connect", scope, reconnect: true };+ case "ask_admin":+ return { kind: "ask_admin" };+ case "withdraw":+ return { kind: "withdraw" };+ case null:+ return null;+ }+}++export function matchesAppSearch(app: DirectoryApp, query: string): boolean {+ const q = query.trim().toLowerCase();+ if (!q) return true;+ return (+ app.name.toLowerCase().includes(q) ||+ app.slug.includes(q) ||+ (app.entry?.category ?? "").toLowerCase().includes(q)+ );+}diff --git a/packages/views/billing/index.ts b/packages/views/billing/index.tsindex ec6cdf4bfa..81eae775df 100644--- a/packages/views/billing/index.ts+++ b/packages/views/billing/index.ts@@ -2,6 +2,7 @@ export { BillingReturnPage } from "./billing-return-page";export { PaidFeatureNotice, usePaidFeatureErrorMessage } from "./paid-feature-notice";export { PaidFeatureUpgradeBadge, type UpgradeBadgeFeature } from "./paid-feature-upgrade-badge";export { TrialStatus } from "./trial-status";+export { UpgradeToAddLink } from "./upgrade-to-add-link";export { WorkspaceTrialNotices } from "./trial-notices";export {StorageLimitNotice,diff --git a/packages/views/billing/upgrade-to-add-link.tsx b/packages/views/billing/upgrade-to-add-link.tsxnew file mode 100644index 0000000000..c66a3d7628--- /dev/null+++ b/packages/views/billing/upgrade-to-add-link.tsx@@ -0,0 +1,17 @@+"use client";++import { buttonVariants } from "@multica/ui/components/ui/button";+import { useWorkspacePaths } from "@multica/core/paths";+import { useT } from "../i18n";+import { AppLink } from "../navigation";++/** Stands in for an add action the workspace's plan does not include. */+export function UpgradeToAddLink() {+ const { t } = useT("billing");+ const paths = useWorkspacePaths();+ return (+ <AppLink href={`${paths.settings()}?tab=billing`} className={buttonVariants({ size: "xs", variant: "outline" })}>+ {t(($) => $.paid_feature.upgrade_to_add)}+ </AppLink>+ );+}diff --git a/packages/views/common/app-requests-new-app.test.tsx b/packages/views/common/app-requests-new-app.test.tsxnew file mode 100644index 0000000000..d6daf60302--- /dev/null+++ b/packages/views/common/app-requests-new-app.test.tsx@@ -0,0 +1,125 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { cleanup, render, screen, waitFor } 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 { configStore } from "@multica/core/config";+import { COMPOSIO_MCP_APPS_FLAG } from "@multica/core/feature-flags";+import { I18nProvider } from "@multica/core/i18n/react";+import type { AppRequest, AppsOverview } from "@multica/core/types";+import { getTestResources } from "../test/i18n";+import { NavigationProvider, type NavigationAdapter } from "../navigation";+import { IssueAppRequests } from "./app-requests";++vi.mock("sonner", () => ({ toast: { success: vi.fn(), error: vi.fn() } }));+vi.mock("@multica/core/api", () => ({+ ApiError: class ApiError extends Error { status = 0; },+ api: {+ listAppRequests: vi.fn(), listAppCatalog: vi.fn(), getAppsOverview: vi.fn(),+ approveAppRequest: vi.fn(), rejectAppRequest: vi.fn(), connectApp: vi.fn(),+ },+}));+vi.mock("@multica/core/hooks", () => ({ useWorkspaceId: () => "ws-1" }));+vi.mock("@multica/core/workspace/hooks", () => ({+ useActorName: () => ({ getActorName: (type: string) => (type === "agent" ? "Ops Assistant" : "Dev") }),+}));+const viewer = vi.hoisted(() => ({ id: "me" }));+vi.mock("@multica/core/auth", () => {+ const state = () => ({ user: viewer });+ return { useAuthStore: Object.assign((sel: (s: ReturnType<typeof state>) => unknown) => sel(state()), { getState: state }) };+});++let request: AppRequest;+let overview: AppsOverview;++beforeEach(() => {+ configStore.getState().setFeatureFlags({ [COMPOSIO_MCP_APPS_FLAG]: true });+ viewer.id = "me";+ request = {+ id: "req-1", kind: "connect", status: "pending", agent_id: "a1", issue_id: "i1", chat_session_id: null,+ approver_user_id: "me", account_scope: "personal", toolkit_slug: "googlecalendar", tool_slug: "",+ action_class: "read", summary: "I need your Google Calendar to find a free slot.", error: null, reason: null,+ redacted: false, adds_app: true, expires_at: "2026-11-24T12:06:00Z", decided_by: null, decided_at: null,+ created_at: "2026-11-17T12:00:00Z",+ };+ overview = { catalog_mode: "all", can_manage: false, team: [], personal: [], agent_apps: [] };+ vi.mocked(api.listAppRequests).mockImplementation(async () => ({ requests: [request], next_before: null }));+ vi.mocked(api.listAppCatalog).mockResolvedValue({+ catalog_mode: "all",+ apps: [{ slug: "googlecalendar", name: "Google Calendar", curated: true }],+ });+ vi.mocked(api.getAppsOverview).mockImplementation(async () => overview);+ vi.mocked(api.approveAppRequest).mockResolvedValue(null);+});++afterEach(() => {+ cleanup();+ vi.clearAllMocks();+});++function renderCard() {+ const navigation: NavigationAdapter = {+ push: vi.fn(), replace: vi.fn(), back: vi.fn(),+ pathname: "/ws/issues/i1", searchParams: new URLSearchParams(), hash: "",+ getShareableUrl: (p) => p,+ };+ render(+ <QueryClientProvider client={new QueryClient({ defaultOptions: { queries: { retry: false } } })}>+ <I18nProvider locale="en" resources={getTestResources()}>+ <NavigationProvider value={navigation}>+ <IssueAppRequests issueId="i1" />+ </NavigationProvider>+ </I18nProvider>+ </QueryClientProvider>,+ );+}++describe("App request card for a new app", () => {+ it("asks to use the app by name and says answering adds it to the agent", async () => {+ renderCard();+ expect(await screen.findByText("Ops Assistant wants to use Google Calendar")).toBeVisible();+ expect(screen.getByText("New app for this agent")).toBeVisible();+ expect(screen.getByText("Answering adds Google Calendar to Ops Assistant for future runs.")).toBeVisible();+ expect(screen.getByRole("button", { name: "Decline" })).toBeVisible();+ expect(screen.queryByRole("button", { name: "I've connected it" })).not.toBeInTheDocument();+ });++ it("connects through the pre-connect notice when the approver has no account", async () => {+ const user = userEvent.setup();+ renderCard();+ await user.click(await screen.findByRole("button", { name: "Connect Google Calendar" }));+ expect(await screen.findByRole("dialog", { name: "Connect Google Calendar" })).toBeVisible();+ expect(api.connectApp).not.toHaveBeenCalled();+ expect(api.approveAppRequest).not.toHaveBeenCalled();+ });++ it("adds the app with the approver's existing account", async () => {+ overview.personal = [{ id: "c1", toolkit_slug: "googlecalendar", status: "active", connected_at: "", last_used_at: null }];+ const user = userEvent.setup();+ renderCard();+ await user.click(await screen.findByRole("button", { name: "Add Google Calendar to Ops Assistant" }));+ await waitFor(() => expect(api.approveAppRequest).toHaveBeenCalledWith("req-1", undefined));+ });++ it("shows others the request without the approver's actions", async () => {+ viewer.id = "someone-else";+ renderCard();+ expect(await screen.findByText("Ops Assistant wants to use Google Calendar")).toBeVisible();+ expect(screen.queryByRole("button")).not.toBeInTheDocument();+ expect(api.getAppsOverview).not.toHaveBeenCalled();+ });+});++describe("App request card for an app the agent already has", () => {+ it("keeps the connect-then-confirm flow, with the app's display name", async () => {+ request.adds_app = false;+ const user = userEvent.setup();+ renderCard();+ expect(await screen.findByText("Ops Assistant asks you to connect Google Calendar")).toBeVisible();+ expect(screen.queryByText("New app for this agent")).not.toBeInTheDocument();+ expect(screen.getByRole("button", { name: "I've connected it" })).toBeVisible();+ await user.click(screen.getByRole("button", { name: "Connect Google Calendar" }));+ expect(await screen.findByRole("dialog", { name: "Connect Google Calendar" })).toBeVisible();+ expect(api.connectApp).not.toHaveBeenCalled();+ });+});diff --git a/packages/views/common/app-requests.tsx b/packages/views/common/app-requests.tsxindex 7125e83e01..1bba967b1c 100644--- a/packages/views/common/app-requests.tsx+++ b/packages/views/common/app-requests.tsx@@ -3,7 +3,7 @@import { useEffect, useRef, useState } from "react";import { useQuery, useQueryClient } from "@tanstack/react-query";import { toast } from "sonner";-import { Loader2, Pencil, Plug, ShieldCheck } from "@multica/ui/icons";+import { Building2, Loader2, Pencil, Plug, ShieldCheck } from "@multica/ui/icons";import { Badge } from "@multica/ui/components/ui/badge";import { Button } from "@multica/ui/components/ui/button";import { Input } from "@multica/ui/components/ui/input";@@ -16,16 +16,21 @@ import { COMPOSIO_MCP_APPS_FLAG } from "@multica/core/feature-flags";import { useWorkspaceId } from "@multica/core/hooks";import { FEATURE_LOCKED_CODE, workspaceFeatureKeys } from "@multica/core/billing";import {+ appCatalogOptions,+ appsOverviewOptions,chatAppRequestsOptions,connectedAppsKeys,issueAppRequestsOptions,useDecideAppRequest,+ useDismissTeamAppRequests,} from "@multica/core/connected-apps";import { useActorName } from "@multica/core/workspace/hooks";import type { AppRequest } from "@multica/core/types";+import { useWorkspacePaths } from "@multica/core/paths";import { useLocale, useT } from "../i18n";-import { currentPath, useNavigation } from "../navigation";-import { isDesktopShell, openExternal } from "../platform";+import { AppLink, useNavigation } from "../navigation";+import { appAccountStatus } from "./app-status";+import { ConnectAppDialog } from "./connect-app-dialog";const CONNECTED_PARAM = "app_connected";const CONNECT_ERROR_PARAM = "app_connect_error";@@ -115,9 +120,101 @@ export function InboxAppRequest({ requestId, chatSessionId }: { requestId: strin});const request = data?.find((r) => r.id === requestId);if (!request) return null;+ if (isTeamConnect(request) && request.can_decide && request.status === "pending") {+ const waiting = (data ?? []).filter(+ (r) => isTeamConnect(r) && r.status === "pending" && r.toolkit_slug === request.toolkit_slug,+ );+ return <TeamAccountRequests slug={request.toolkit_slug} requests={waiting} />;+ }return <AppRequestList requests={[request]} showDecided />;}+function isTeamConnect(request: AppRequest) {+ return request.kind === "connect" && request.account_scope === "team";+}++/**+ * Everything waiting for one team account, as an admin sees it in the Inbox:+ * agents' runs and members' asks are one kind of request, so connecting the+ * account once answers them all.+ */+function TeamAccountRequests({ slug, requests }: { slug: string; requests: AppRequest[] }) {+ const { t } = useT("settings");+ const wsId = useWorkspaceId();+ const paths = useWorkspacePaths();+ const { getActorName } = useActorName();+ const catalog = useQuery(appCatalogOptions(wsId));+ const decline = useDismissTeamAppRequests();+ const [connectOpen, setConnectOpen] = useState(false);+ const entry = catalog.data?.apps.find((a) => a.slug === slug);+ const app = entry?.name || slug;+ const declineAll = () =>+ decline.mutateAsync(slug).then(+ () => toast.success(t(($) => $.connected_apps.account_row.toast_declined)),+ () => toast.error(t(($) => $.connected_apps.request.toast_failed)),+ );++ return (+ <section className="my-3 space-y-2 rounded-lg border border-brand/40 bg-brand/5 p-3" data-team-account-requests={slug}>+ <div className="flex items-start gap-2">+ <ShieldCheck className="mt-0.5 size-4 shrink-0 text-brand" />+ <div className="min-w-0 flex-1 space-y-1">+ <p className="text-body font-medium">{t(($) => $.connected_apps.team_requests.title, { app })}</p>+ <p className="flex items-center gap-1 text-caption text-muted-foreground">+ <Building2 className="size-3" aria-hidden="true" />+ {t(($) => $.connected_apps.owner.team)}+ </p>+ </div>+ </div>+ <ul className="divide-y rounded-md border bg-background">+ {requests.map((r) => {+ const run = !!r.agent_id && !!(r.issue_id || r.chat_session_id);+ return (+ <li key={r.id} className="flex items-center gap-2 px-3 py-2 text-body">+ <span className="min-w-0 flex-1 truncate">+ <span className="font-medium">+ {run ? getActorName("agent", r.agent_id) : getActorName("member", r.approver_user_id)}+ </span>+ {r.summary ? (+ <span className="text-muted-foreground">+ {t(($) => $.connected_apps.team_requests.summary, { summary: r.summary })}+ </span>+ ) : null}+ </span>+ <Badge variant="outline" className="shrink-0">+ {run ? t(($) => $.connected_apps.team_requests.run_waiting) : t(($) => $.connected_apps.team_requests.asked)}+ </Badge>+ </li>+ );+ })}+ </ul>+ <p className="text-caption text-muted-foreground">+ {t(($) => $.connected_apps.team_requests.resumes)}+ </p>+ <div className="flex flex-wrap items-center justify-end gap-2">+ <Button size="xs" variant="ghost" nativeButton={false} render={<AppLink href={paths.appDetail(slug)} />}>+ {t(($) => $.connected_apps.team_requests.open_app)}+ </Button>+ <Button size="xs" variant="ghost" disabled={decline.isPending} onClick={declineAll}>+ {t(($) => $.connected_apps.team_requests.decline_all)}+ </Button>+ <Button size="xs" onClick={() => setConnectOpen(true)}>+ <Plug />+ {t(($) => $.connected_apps.request.connect_team)}+ </Button>+ </div>+ <ConnectAppDialog+ open={connectOpen}+ onOpenChange={setConnectOpen}+ scope="team"+ slug={slug}+ name={app}+ logo={entry?.logo}+ />+ </section>+ );+}+function AppRequestList({requests,showDecided = false,@@ -206,8 +303,9 @@ function AppRequestCard({highlightToken?: number;}) {const { t } = useT("settings");+ const { t: ta } = useT("agents");const locale = useLocale();- const navigation = useNavigation();+ const wsId = useWorkspaceId();const ref = useRef<HTMLDivElement>(null);const [highlighted, setHighlighted] = useState(false);useEffect(() => {@@ -223,12 +321,22 @@ function AppRequestCard({const [draft, setDraft] = useState(() => prettyArgs(request.arguments));const [rejecting, setRejecting] = useState(false);const [reason, setReason] = useState("");- const [connecting, setConnecting] = useState(false);+ const [connectOpen, setConnectOpen] = useState(false);const agent = getActorName("agent", request.agent_id);const approver = getActorName("member", request.approver_user_id);- const app = request.toolkit_slug;const pending = request.status === "pending";+ const isConnect = request.kind === "connect";+ const team = isTeamConnect(request);+ // Older servers omit can_decide; the approver answered everything then.+ const canDecide = request.can_decide ?? isApprover;+ const memberAsk = team && !request.agent_id;+ const addsApp = isConnect && request.adds_app === true;+ const catalog = useQuery({ ...appCatalogOptions(wsId), enabled: isConnect });+ const overview = useQuery({ ...appsOverviewOptions(wsId), enabled: addsApp && pending && isApprover });+ const entry = catalog.data?.apps.find((a) => a.slug === request.toolkit_slug);+ const app = entry?.name || request.toolkit_slug;+ const hasAccount = appAccountStatus(overview.data, "personal", request.toolkit_slug) === "connected";const approve = () => {let args: Record<string, unknown> | undefined;@@ -258,22 +366,14 @@ function AppRequestCard({onError: () => toast.error(t(($) => $.connected_apps.request.toast_failed)),},);- const connect = async () => {- setConnecting(true);- try {- // The callback appends its own query, so the fragment stays behind.- const returnTo = currentPath({ ...navigation, hash: "" });- const { redirect_url } = await api.connectApp("personal", app, returnTo);- openExternal(redirect_url, { webTarget: "same-tab" });- // Desktop opens the hosted flow in the system browser and stays here;- // the card resolves through the request's realtime update.- if (isDesktopShell()) setConnecting(false);- } catch {- toast.error(t(($) => $.connected_apps.toast_failed));- setConnecting(false);- }- };-+ const withdraw = () =>+ decide.mutate(+ { id: request.id, decision: "reject" },+ {+ onSuccess: () => toast.success(t(($) => $.connected_apps.account_row.toast_withdrawn)),+ onError: () => toast.error(t(($) => $.connected_apps.request.toast_failed)),+ },+ );const statusLabel = (status: string) => {switch (status) {case "approved":@@ -300,16 +400,28 @@ function AppRequestCard({<ShieldCheck className="mt-0.5 size-4 shrink-0 text-brand" /><div className="min-w-0 flex-1 space-y-1"><p className="text-body font-medium">- {request.kind === "connect"- ? t(($) => $.connected_apps.request.title_connect, { agent, app })- : t(($) => $.connected_apps.request.title_action, { agent, tool: request.tool_slug })}+ {addsApp+ ? ta(($) => $.app_requests.title_adds_app, { agent, app })+ : memberAsk+ ? t(($) => $.connected_apps.request.title_member_ask, { name: approver, app })+ : team+ ? t(($) => $.connected_apps.request.title_connect_team, { agent, app })+ : isConnect+ ? t(($) => $.connected_apps.request.title_connect, { agent, app })+ : t(($) => $.connected_apps.request.title_action, { agent, tool: request.tool_slug })}</p><p className="flex flex-wrap items-center gap-1.5 text-caption text-muted-foreground">- <Badge variant="outline">{t(($) => $.connected_apps.scopes[request.account_scope])}</Badge>+ <Badge variant="outline">+ {addsApp+ ? ta(($) => $.app_requests.new_app)+ : request.account_scope === "personal" && isApprover+ ? t(($) => $.connected_apps.owner.personal)+ : t(($) => $.connected_apps.scopes[request.account_scope])}+ </Badge>{request.kind === "action" && <Badge variant="outline">{request.action_class}</Badge>}<span>{pending- ? `${t(($) => $.connected_apps.request.waiting_for, { name: approver })} · ${t(($) => $.connected_apps.request.expires, { when: new Date(request.expires_at).toLocaleString(locale, { month: "short", day: "numeric", hour: "2-digit", minute: "2-digit" }) })}`+ ? `${team ? t(($) => $.connected_apps.request.waiting_for_admin) : t(($) => $.connected_apps.request.waiting_for, { name: approver })} · ${t(($) => $.connected_apps.request.expires, { when: new Date(request.expires_at).toLocaleString(locale, { month: "short", day: "numeric", hour: "2-digit", minute: "2-digit" }) })}`: statusLabel(request.status)}</span></p>@@ -335,7 +447,31 @@ function AppRequestCard({</div></div>- {pending && isApprover && (+ {pending && team && (+ <div className="mt-3 flex flex-wrap items-center justify-end gap-2">+ <p className="mr-auto text-caption text-muted-foreground">+ {canDecide+ ? t(($) => $.connected_apps.request.team_note)+ : t(($) => $.connected_apps.request.admins_notified)}+ </p>+ {canDecide ? (+ <>+ <Button size="xs" variant="ghost" disabled={decide.isPending} onClick={reject}>+ {t(($) => $.connected_apps.request.reject)}+ </Button>+ <Button size="xs" onClick={() => setConnectOpen(true)}>+ <Plug />+ {t(($) => $.connected_apps.request.connect_team)}+ </Button>+ </>+ ) : isApprover ? (+ <Button size="xs" variant="ghost" disabled={decide.isPending} onClick={withdraw}>+ {t(($) => $.connected_apps.account_row.withdraw)}+ </Button>+ ) : null}+ </div>+ )}+ {pending && !team && isApprover && (<div className="mt-3 space-y-2">{rejecting && (<Input@@ -346,6 +482,11 @@ function AppRequestCard({/>)}<div className="flex flex-wrap items-center justify-end gap-2">+ {addsApp && (+ <p className="mr-auto text-caption text-muted-foreground">+ {ta(($) => $.app_requests.adds_app_note, { app, agent })}+ </p>+ )}{request.kind === "action" && !editing && !rejecting && (<Button size="xs" variant="ghost" onClick={() => setEditing(true)}><Pencil />@@ -354,16 +495,28 @@ function AppRequestCard({)}<Buttonsize="xs"- variant="outline"+ variant={addsApp ? "ghost" : "outline"}disabled={decide.isPending}onClick={() => (rejecting ? reject() : setRejecting(true))}>{t(($) => $.connected_apps.request.reject)}</Button>- {request.kind === "connect" ? (+ {addsApp ? (+ hasAccount ? (+ <Button size="xs" disabled={decide.isPending} onClick={approve}>+ {decide.isPending && <Loader2 className="animate-spin" />}+ {ta(($) => $.app_requests.add_to_agent, { app, agent })}+ </Button>+ ) : (+ <Button size="xs" onClick={() => setConnectOpen(true)}>+ <Plug />+ {t(($) => $.connected_apps.request.connect, { app })}+ </Button>+ )+ ) : isConnect ? (<>- <Button size="xs" variant="outline" disabled={connecting} onClick={connect}>- {connecting ? <Loader2 className="animate-spin" /> : <Plug />}+ <Button size="xs" variant="outline" onClick={() => setConnectOpen(true)}>+ <Plug />{t(($) => $.connected_apps.request.connect, { app })}</Button><Button size="xs" disabled={decide.isPending} onClick={approve}>@@ -381,6 +534,16 @@ function AppRequestCard({</div></div>)}+ {isConnect && (+ <ConnectAppDialog+ open={connectOpen}+ onOpenChange={setConnectOpen}+ scope={team ? "team" : "personal"}+ slug={request.toolkit_slug}+ name={app}+ logo={entry?.logo}+ />+ )}</div>);}diff --git a/packages/views/common/app-status.ts b/packages/views/common/app-status.tsnew file mode 100644index 0000000000..55b00ce330--- /dev/null+++ b/packages/views/common/app-status.ts@@ -0,0 +1,96 @@+import type { AppAccountScope, AppConnection, AppTeamRequest, AppsOverview } from "@multica/core/types";++/**+ * Where an account stands. Every Apps surface (the agent page, the app page,+ * the Apps directory, settings) labels accounts with these values, next to+ * whose account it is, so one state never reads two ways.+ */+export type AppAccountStatus =+ | "connected"+ | "not_connected"+ | "needs_reconnecting"+ | "requested";++/** The one action an account offers the viewer. */+export type AppAccountAction = "connect" | "reconnect" | "upgrade" | "ask_admin" | "withdraw";++/** The account an app on an agent would use for the viewer, if any. */+export function accountFor(+ overview: AppsOverview | undefined,+ scope: AppAccountScope,+ slug: string,+): AppConnection | undefined {+ const rows = scope === "team" ? overview?.team : overview?.personal;+ return rows?.find((c) => c.toolkit_slug === slug && c.status !== "revoked");+}++/** What is waiting for the team account of an app the workspace lacks. */+export function teamRequestFor(overview: AppsOverview | undefined, slug: string): AppTeamRequest | undefined {+ if (accountFor(overview, "team", slug)?.status === "active") return undefined;+ return overview?.team_requests?.find((r) => r.toolkit_slug === slug && r.requested_by.length > 0);+}++export function appAccountStatus(+ overview: AppsOverview | undefined,+ scope: AppAccountScope,+ slug: string,+): AppAccountStatus {+ const account = accountFor(overview, scope, slug);+ if (account?.status === "active") return "connected";+ if (account?.status === "expired") return "needs_reconnecting";+ if (scope === "team" && teamRequestFor(overview, slug)) return "requested";+ return "not_connected";+}++/** Whether the status needs someone to act before agents can use the app. */+export function needsAttention(status: AppAccountStatus): boolean {+ return status !== "connected";+}++/**+ * The action for an account, from whose it is, where it stands, and who is+ * looking: anyone connects their own; admins connect the team's (or upgrade+ * when the plan leaves team accounts out); members ask an admin, then can+ * withdraw the ask.+ */+export function accountAction({+ scope,+ status,+ canManage,+ needsUpgrade,+ viewerAsk,+}: {+ scope: AppAccountScope;+ status: AppAccountStatus;+ canManage: boolean;+ needsUpgrade: boolean;+ viewerAsk: ViewerTeamAsk;+}): AppAccountAction | null {+ if (status === "connected") return null;+ if (scope === "personal") return status === "needs_reconnecting" ? "reconnect" : "connect";+ if (canManage) {+ if (status === "needs_reconnecting") return "reconnect";+ return needsUpgrade ? "upgrade" : "connect";+ }+ if (viewerAsk === "asked") return "withdraw";+ // A run the viewer started already waits on it; the admins know.+ if (viewerAsk === "waiting") return null;+ return "ask_admin";+}++/**+ * How the viewer is waiting for an app's team account: they asked an admin+ * (and can withdraw it), or only a run they started waits on it.+ */+export type ViewerTeamAsk = "asked" | "waiting" | null;++export function viewerTeamAsk(+ overview: AppsOverview | undefined,+ slug: string,+ viewerId: string | null | undefined,+): ViewerTeamAsk {+ const request = teamRequestFor(overview, slug);+ if (!viewerId || !request) return null;+ if ((request.asked_by ?? request.requested_by).includes(viewerId)) return "asked";+ return request.requested_by.includes(viewerId) ? "waiting" : null;+}diff --git a/packages/views/common/connect-app-dialog.tsx b/packages/views/common/connect-app-dialog.tsxnew file mode 100644index 0000000000..bf248b8b05--- /dev/null+++ b/packages/views/common/connect-app-dialog.tsx@@ -0,0 +1,148 @@+"use client";++import { useState } from "react";+import { useQuery, useQueryClient } from "@tanstack/react-query";+import { toast } from "sonner";+import { ArrowUpRight, Bot, Check, Loader2, Lock, Users } from "@multica/ui/icons";+import { Button } from "@multica/ui/components/ui/button";+import {+ Dialog,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+} from "@multica/ui/components/ui/dialog";+import { api } from "@multica/core/api";+import { useWorkspaceId } from "@multica/core/hooks";+import { refreshFeaturesOnLockedError } from "@multica/core/billing";+import { appsOverviewOptions } from "@multica/core/connected-apps";+import { useActorName } from "@multica/core/workspace/hooks";+import type { AppAccountScope, AppActionClass } from "@multica/core/types";+import { ComposioToolkitLogo } from "./composio-toolkit-logo";+import { usePaidFeatureErrorMessage } from "../billing";+import { useT } from "../i18n";+import { currentPath, useNavigation } from "../navigation";+import { isDesktopShell, openExternal } from "../platform";++const CLASSES: readonly AppActionClass[] = ["read", "write", "send", "delete", "share"];++/**+ * Says what agents will be able to do with an account before the hosted+ * connect flow starts: agents act without asking, and who the account is+ * visible to. Every place that starts a connection goes through it.+ */+export function ConnectAppDialog({+ open,+ onOpenChange,+ scope,+ slug,+ name,+ logo,+ returnTo,+}: {+ open: boolean;+ onOpenChange: (open: boolean) => void;+ scope: AppAccountScope;+ slug: string;+ name: string;+ logo?: string;+ /** App path to come back to; defaults to the current page. */+ returnTo?: string;+}) {+ const { t } = useT("settings");+ const wsId = useWorkspaceId();+ const navigation = useNavigation();+ const { getActorName } = useActorName();+ const qc = useQueryClient();+ const paidFeatureError = usePaidFeatureErrorMessage();+ const overview = useQuery({ ...appsOverviewOptions(wsId), enabled: open });+ const [pending, setPending] = useState(false);++ const agentNames = (overview.data?.agent_apps ?? [])+ .filter((a) => a.toolkit_slug === slug && a.account_scope === scope)+ .map((a) => getActorName("agent", a.agent_id));++ const start = async () => {+ setPending(true);+ try {+ const target = returnTo ?? currentPath({ ...navigation, hash: "" });+ const { redirect_url } = await api.connectApp(scope, slug, target);+ openExternal(redirect_url, { webTarget: "same-tab" });+ // Desktop finishes the flow in the system browser and stays here.+ if (isDesktopShell()) {+ setPending(false);+ onOpenChange(false);+ }+ } catch (e) {+ refreshFeaturesOnLockedError(qc, wsId, e);+ toast.error(paidFeatureError(e, e instanceof Error && e.message ? e.message : t(($) => $.connected_apps.toast_failed)));+ setPending(false);+ }+ };++ return (+ <Dialog open={open} onOpenChange={(next) => !pending && onOpenChange(next)}>+ <DialogContent className="sm:max-w-lg">+ <DialogHeader>+ <DialogTitle className="flex items-center gap-2">+ <ComposioToolkitLogo slug={slug} name={name} fallbackLogo={logo} className="size-5" />+ {t(($) => $.connected_apps.disclosure.title, { app: name })}+ </DialogTitle>+ <DialogDescription>+ {scope === "team"+ ? t(($) => $.connected_apps.disclosure.team_subtitle)+ : t(($) => $.connected_apps.disclosure.personal_subtitle)}+ </DialogDescription>+ </DialogHeader>++ <div className="space-y-2 rounded-lg bg-muted/60 p-3">+ <p className="text-body font-medium">{t(($) => $.connected_apps.disclosure.without_asking)}</p>+ <ul className="space-y-1">+ {CLASSES.map((c) => (+ <li key={c} className="flex items-start gap-2 text-body">+ <Check className="mt-0.5 size-3.5 shrink-0 text-success" />+ <span>+ {t(($) => $.connected_apps.classes[c].label)}+ <span className="text-muted-foreground"> · {t(($) => $.connected_apps.classes[c].description)}</span>+ </span>+ </li>+ ))}+ </ul>+ <p className="text-caption text-muted-foreground">{t(($) => $.connected_apps.disclosure.logged)}</p>+ </div>++ <ul className="space-y-1.5 text-body">+ <li className="flex items-start gap-2">+ <Bot className="mt-0.5 size-3.5 shrink-0 text-muted-foreground" />+ <span>+ {agentNames.length > 0+ ? t(($) => $.connected_apps.disclosure.used_by, { agents: agentNames.join(", "), app: name })+ : t(($) => $.connected_apps.disclosure.used_by_none)}+ </span>+ </li>+ <li className="flex items-start gap-2">+ {scope === "team"+ ? <Users className="mt-0.5 size-3.5 shrink-0 text-muted-foreground" />+ : <Lock className="mt-0.5 size-3.5 shrink-0 text-muted-foreground" />}+ <span>+ {scope === "team"+ ? t(($) => $.connected_apps.disclosure.visibility_team)+ : t(($) => $.connected_apps.disclosure.visibility_personal)}+ </span>+ </li>+ </ul>++ <DialogFooter>+ <Button variant="ghost" disabled={pending} onClick={() => onOpenChange(false)}>+ {t(($) => $.connected_apps.disclosure.cancel)}+ </Button>+ <Button disabled={pending} onClick={start}>+ {pending ? <Loader2 className="animate-spin" /> : <ArrowUpRight />}+ {t(($) => $.connected_apps.disclosure.continue)}+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ );+}diff --git a/packages/views/settings/components/connected-apps-tab.test.tsx b/packages/views/common/use-composio-available.test.tsxsimilarity index 96%rename from packages/views/settings/components/connected-apps-tab.test.tsxrename to packages/views/common/use-composio-available.test.tsxindex 7fcbded821..930eaf9496 100644--- a/packages/views/settings/components/connected-apps-tab.test.tsx+++ b/packages/views/common/use-composio-available.test.tsx@@ -16,7 +16,7 @@ vi.mock("@tanstack/react-query", () => ({},}));-import { useComposioAvailable } from "./connected-apps-tab";+import { useComposioAvailable } from "./use-composio-available";beforeEach(() => {state.error = null;diff --git a/packages/views/common/use-composio-available.ts b/packages/views/common/use-composio-available.tsnew file mode 100644index 0000000000..c4767333eb--- /dev/null+++ b/packages/views/common/use-composio-available.ts@@ -0,0 +1,23 @@+"use client";++import { useQuery } from "@tanstack/react-query";+import { ApiError, errorCode } from "@multica/core/api";+import { composioToolkitsOptions } from "@multica/core/composio";+import { useFeatureEnabled } from "@multica/core/config";+import { COMPOSIO_MCP_APPS_FLAG } from "@multica/core/feature-flags";++/**+ * Whether Connected apps exist on this server. A pending or failed catalog+ * read still counts as available — only an explicit "Composio is not+ * configured on this server" hides the surfaces, so a transient error never+ * removes them.+ */+export function useComposioAvailable(): boolean {+ const enabled = useFeatureEnabled(COMPOSIO_MCP_APPS_FLAG, false);+ const toolkits = useQuery({ ...composioToolkitsOptions(), enabled });+ return (+ enabled &&+ errorCode(toolkits.error) !== "composio_not_configured" &&+ !(toolkits.error instanceof ApiError && toolkits.error.status === 503)+ );+}diff --git a/packages/views/common/use-team-app-access.ts b/packages/views/common/use-team-app-access.tsnew file mode 100644index 0000000000..f185af585a--- /dev/null+++ b/packages/views/common/use-team-app-access.ts@@ -0,0 +1,29 @@+"use client";++import { useWorkspaceId } from "@multica/core/hooks";+import { usePaidFeatureAccess } from "@multica/core/billing";+import type { AppsOverview } from "@multica/core/types";+import { accountFor } from "./app-status";++/**+ * The plan's `team_app_accounts` access for the Apps surfaces. Without it,+ * existing team accounts keep working and can be reauthorized or+ * disconnected; only a team account for a new app, or moving an agent onto+ * the team account, is refused.+ */+export function useTeamAppAccess(overview: AppsOverview | undefined) {+ const wsId = useWorkspaceId();+ const access = usePaidFeatureAccess(wsId, "team_app_accounts", {+ hasExistingConfig: (overview?.team ?? []).some((c) => c.status !== "revoked"),+ });+ const locked = access.state === "read_only" || access.state === "unavailable";+ return {+ ...access,+ /**+ * Whether connecting the team account for `slug` adds a new one the plan+ * is known not to include. Unknown while the plan loads, so Connect never+ * flickers to an upgrade prompt; the server decides either way.+ */+ needsUpgrade: (slug: string) => locked && !accountFor(overview, "team", slug),+ };+}diff --git a/packages/views/editor/utils/link-handler.ts b/packages/views/editor/utils/link-handler.tsindex b6b2599e2c..02229d58ea 100644--- a/packages/views/editor/utils/link-handler.ts+++ b/packages/views/editor/utils/link-handler.ts@@ -36,6 +36,7 @@ const WORKSPACE_ROUTE_SEGMENTS = new Set(["my-issues","runtimes","skills",+ "apps","settings",]);diff --git a/packages/views/layout/object-page.tsx b/packages/views/layout/object-page.tsxindex b9647f119e..b71f768782 100644--- a/packages/views/layout/object-page.tsx+++ b/packages/views/layout/object-page.tsx@@ -40,7 +40,7 @@ export const OBJECT_PAGE_BODY =const OBJECT_PAGE_SCROLL_KEY = "object";/** What an object page shows, as themes see it on `data-type`. */-export type ObjectPageType = "project" | "agent" | "squad" | "runtime" | "member" | "autopilot" | "skill";+export type ObjectPageType = "project" | "agent" | "squad" | "runtime" | "member" | "autopilot" | "skill" | "app";interface ObjectPageProps {type: ObjectPageType;diff --git a/packages/views/layout/panels/team-panel.tsx b/packages/views/layout/panels/team-panel.tsxindex 3341ce1ef7..7eda034d2e 100644--- a/packages/views/layout/panels/team-panel.tsx+++ b/packages/views/layout/panels/team-panel.tsx@@ -2,7 +2,7 @@import { useId, useMemo, useState, type ReactNode } from "react";import { useQuery } from "@tanstack/react-query";-import { ArrowUpRight, BarChart3, BookOpenText, Bot, MessageSquare, Monitor, Plus, User, UserPlus, Users } from "@multica/ui/icons";+import { ArrowUpRight, BarChart3, BookOpenText, Bot, MessageSquare, Monitor, Plug, Plus, User, UserPlus, Users } from "@multica/ui/icons";import { DropdownMenuItem } from "@multica/ui/components/ui/dropdown-menu";import { cn } from "@multica/ui/lib/utils";import { ActorAvatar } from "@multica/ui/components/common/actor-avatar";@@ -11,6 +11,7 @@ import { agentTaskSnapshotOptions, type AgentPresenceDetail } from "@multica/corimport { useAgentsViewStore } from "@multica/core/agents/stores";import { useAuthStore } from "@multica/core/auth";import { useChatStore } from "@multica/core/chat";+import { appsOverviewOptions } from "@multica/core/connected-apps";import { canAssignAgentToIssue } from "@multica/core/permissions";import { issueDetailOptions } from "@multica/core/issues/queries";import { useSidebarTreeStore } from "@multica/core/issues/stores/sidebar-tree-store";@@ -26,6 +27,8 @@ import { shouldOpenRowMenu, useRowMenu } from "../../common/point-menu";import { CollectionRowContext } from "../collection-list/row-context";import { availabilityConfig } from "../../agents/presence";import { useT } from "../../i18n";+import { buildAppDirectory } from "../../apps/lib/directory";+import { useComposioAvailable } from "../../common/use-composio-available";import { buildRuntimeMachines, runtimeMachineCounts } from "../../runtimes/components/runtime-machines";import {PanelBody,@@ -242,6 +245,29 @@ function WorkingAgentRow({);}+/** The Apps link, counting the apps that need someone to act. */+function AppsPanelLink({ wsId, agents }: { wsId: string; agents: Agent[] }) {+ const { t } = useT("layout");+ const p = useWorkspacePaths();+ const { pathname } = useNavigation();+ const viewerId = useAuthStore((s) => s.user?.id ?? null);+ const { data: overview } = useQuery({ ...appsOverviewOptions(wsId), enabled: !!wsId });+ const attention = useMemo(() => {+ if (!overview) return 0;+ const agentIds = new Set(agents.map((agent) => agent.id));+ return buildAppDirectory({ overview, catalog: [], viewerId, agentIds }).attention.length;+ }, [overview, agents, viewerId]);+ return (+ <PanelLink+ href={p.apps()}+ icon={<Plug />}+ label={t(($) => $.nav.apps)}+ active={isPathWithin(pathname, p.apps())}+ trailing={<PanelCount value={attention} />}+ />+ );+}+export function TeamPanel() {const { t } = useT("layout");const p = useWorkspacePaths();@@ -273,6 +299,7 @@ export function TeamPanel() {const { data: members = [] } = useQuery({ ...memberListOptions(wsId), enabled: !!wsId });const { data: skills = [] } = useQuery({ ...skillListOptions(wsId), enabled: !!wsId });const { data: runtimes = [] } = useQuery({ ...runtimeListOptions(wsId), enabled: !!wsId });+ const appsAvailable = useComposioAvailable();const machineCounts = useMemo(() => {const machines = buildRuntimeMachines(runtimes, { now: Date.now() }).filter((machine) => !machine.runtimes.every((runtime) => runtime.provider === "qoder_cloud"),@@ -426,6 +453,7 @@ export function TeamPanel() {active={isPathWithin(pathname, p.skills())}trailing={<PanelCount value={skills.length} />}/>+ {appsAvailable && <AppsPanelLink wsId={wsId} agents={agents} />}<PanelLinkhref={p.runtimes()}icon={<Monitor />}diff --git a/packages/views/layout/route-data-prefetch.tsx b/packages/views/layout/route-data-prefetch.tsxindex 15f3b8b85b..f9cad0e6a3 100644--- a/packages/views/layout/route-data-prefetch.tsx+++ b/packages/views/layout/route-data-prefetch.tsx@@ -9,6 +9,7 @@ import {} from "@multica/core/agents/queries";import { autopilotListOptions } from "@multica/core/autopilots/queries";import { chatSessionsOptions } from "@multica/core/chat/queries";+import { appCatalogOptions, appsOverviewOptions } from "@multica/core/connected-apps";import { inboxListOptions } from "@multica/core/inbox/queries";import { fetchIssueByRef, prefetchIssuePage } from "@multica/core/issues/queries";import { useAuthStore } from "@multica/core/auth";@@ -48,6 +49,11 @@ const ROUTES = {void qc.prefetchQuery(memberListOptions(wsId));void qc.prefetchQuery(runtimeListOptions(wsId));},+ apps: (qc, wsId) => {+ void qc.prefetchQuery(appsOverviewOptions(wsId));+ void qc.prefetchQuery(appCatalogOptions(wsId));+ void qc.prefetchQuery(agentListOptions(wsId));+ },squads: (qc, wsId) => {void qc.prefetchQuery(squadListOptions(wsId));void qc.prefetchQuery(agentListOptions(wsId));diff --git a/packages/views/layout/route-icon-components.tsx b/packages/views/layout/route-icon-components.tsxindex 84e4d497d7..7eb401acca 100644--- a/packages/views/layout/route-icon-components.tsx+++ b/packages/views/layout/route-icon-components.tsx@@ -12,6 +12,7 @@ import {Monitor,Server,BookOpenText,+ Plug,Settings,File,FileText,@@ -46,6 +47,7 @@ export const ROUTE_ICON_COMPONENTS: Record<RouteIconName, IconComponent> = {Monitor,Server,BookOpenText,+ Plug,Settings,File,FileText,diff --git a/packages/views/layout/tab-presentation.tsx b/packages/views/layout/tab-presentation.tsxindex 7bd99a4f6c..2143f36d45 100644--- a/packages/views/layout/tab-presentation.tsx+++ b/packages/views/layout/tab-presentation.tsx@@ -26,6 +26,7 @@ import {import { runtimeListOptions } from "@multica/core/runtimes/queries";import { runtimeDisplayLabel } from "@multica/core/runtimes";import { chatSessionsOptions } from "@multica/core/chat/queries";+import { appCatalogOptions } from "@multica/core/connected-apps";import {inboxListOptions,archivedInboxPagesOptions,@@ -73,6 +74,7 @@ const PENDING_RESOURCE_KEYS: ReadonlySet<TabLabelKey> = new Set<TabLabelKey>(["skill","doc","docFolder",+ "app","machine","runtime",]);@@ -156,6 +158,7 @@ function useTabEntityData(subject: TabSubject, wsId: string, fetch: boolean): Reconst squads = useQuery({ ...squadListOptions(wsId), enabled: false }).data;const runtimes = useQuery({ ...runtimeListOptions(wsId), enabled: false }).data;const sessions = useQuery({ ...chatSessionsOptions(wsId), enabled: false }).data;+ const appCatalog = useQuery({ ...appCatalogOptions(wsId), enabled: false }).data;const data: ResolvedTabEntityData = {};switch (subject.kind) {@@ -185,6 +188,11 @@ function useTabEntityData(subject: TabSubject, wsId: string, fetch: boolean): Recase "skill":if (skill) data.skill = { name: skill.name };break;+ case "app": {+ const name = appCatalog?.apps.find((a) => a.slug === subject.slug)?.name;+ if (name) data.app = { name };+ break;+ }case "actor": {const name =subject.actorType === "agent"diff --git a/packages/views/locales/en/agents.json b/packages/views/locales/en/agents.jsonindex f459cf332b..c2e64ac9a2 100644--- a/packages/views/locales/en/agents.json+++ b/packages/views/locales/en/agents.json@@ -223,7 +223,14 @@"status": "Status","runs_7d": "Runs (7d)","edit_access_aria": "Access: {{value}}. Change access",- "all_settings": "All settings"+ "all_settings": "All settings",+ "apps": "Apps",+ "apps_needs_account_one": "{{count}} needs your account",+ "apps_needs_account_other": "{{count}} need your account",+ "apps_count_one": "{{count}} app",+ "apps_count_other": "{{count}} apps",+ "apps_none": "None",+ "apps_aria": "Apps: {{value}}. Show apps"},"pickers": {"concurrency_range": "Max concurrent runs ({{min}}–{{max}})",@@ -808,13 +815,9 @@"load_failed": "Couldn't load this agent's apps.","empty": "No connected apps available.","level": "Account scope",- "team_connected": "Team account connected",- "team_missing": "Team account not connected",- "personal_connected": "Your account is connected",- "personal_missing": "You haven't connected this app","team_admin_only": "Only workspace admins can give an agent a team account.","team_shared_warning": "Anyone who can run this agent can use this team account through it.",- "manage_link": "Manage accounts in Settings → Connected apps",+ "manage_link": "Manage accounts in Apps → Accounts","save_failed_toast": "Couldn't save — please try again","team_help": "Shared workspace account, connected by admins.","personal_help": "Each run uses the account of whoever triggers it. They must connect their own account.",@@ -1100,5 +1103,36 @@"comment": "Fixed: pricing cards stack into one column under 375px. PR is open and tests pass.","step_read": "Read {{file}}"}+ },+ "apps_section": {+ "title": "Apps",+ "empty": "This agent doesn't use any apps yet.",+ "connect_yours": "Connect yours",+ "reconnect": "Reconnect",+ "connect_team": "Connect team account",+ "acts_as_team": "Acts as the team account",+ "acts_as_starter": "Acts as whoever starts the run"+ },+ "add_app_dialog": {+ "title": "Add an app to {{agent}}",+ "description": "A personal-account app uses the account of whoever starts the agent, so you can add it without an account of your own.",+ "search_one": "Search {{count}} app",+ "search_other": "Search {{count}} apps",+ "search_label": "Search apps",+ "curated": "Curated",+ "recommended_team": "Usually a team account",+ "recommended_personal": "Usually a personal account",+ "team_connected": "Team account connected",+ "add": "Add",+ "add_aria": "Add {{app}}",+ "empty": "No apps match.",+ "load_failed": "Couldn't load apps.",+ "added_toast": "Added {{app}} to {{agent}}."+ },+ "app_requests": {+ "title_adds_app": "{{agent}} wants to use {{app}}",+ "new_app": "New app for this agent",+ "adds_app_note": "Answering adds {{app}} to {{agent}} for future runs.",+ "add_to_agent": "Add {{app}} to {{agent}}"}}diff --git a/packages/views/locales/en/inbox.json b/packages/views/locales/en/inbox.jsonindex cc7d2bdb10..0b69eaa59e 100644--- a/packages/views/locales/en/inbox.json+++ b/packages/views/locales/en/inbox.json@@ -71,6 +71,7 @@"autopilot_quota_exceeded_body": "This workspace has reached its limit of {{limit}} autopilot runs for the current period. Further autopilot runs will not start until the allowance resets {{resetAt}}, or until the workspace upgrades or buys more runs.","project_owner_joined_body": "{{name}} is a workspace owner and added themselves to this private project. They can now see its issues, comments, and attachments.","open_project": "Open project",+ "open_app": "Open app","autopilot_quota_upgrade": "View options","archive": "Archive","unarchive": "Unarchive",diff --git a/packages/views/locales/en/layout.json b/packages/views/locales/en/layout.jsonindex 998dc9a9d5..385d3c1d2f 100644--- a/packages/views/locales/en/layout.json+++ b/packages/views/locales/en/layout.json@@ -11,6 +11,7 @@"usage": "Analytics","runtimes": "Runtimes","skills": "Skills",+ "apps": "Apps","settings": "Settings","views": "Views","docs": "Docs"@@ -23,6 +24,7 @@"member": "Member","squad": "Squad","skill": "Skill",+ "app": "App","machine": "Machine","runtime": "Runtime","attachment": "Attachment",diff --git a/packages/views/locales/en/settings.json b/packages/views/locales/en/settings.jsonindex bbad988ef1..b5a1232d5c 100644--- a/packages/views/locales/en/settings.json+++ b/packages/views/locales/en/settings.json@@ -601,7 +601,6 @@"billing": "Billing","code": "Code","channels": "Messaging",- "apps": "Connected apps","workflows": "Workflows","voice_input": "Voice input"},@@ -1759,6 +1758,7 @@"layout": {"scope": {"account": "Account · synced",+ "all_workspaces": "All your workspaces","device": "This device only","device_workspace": "This device · {{name}}","workspace": "{{name}} workspace",@@ -1849,22 +1849,8 @@"authorization_expired": "WeChat authorization expired. Scan again to reconnect."},"connected_apps": {- "description": "Accounts your agents use to access external apps. Allowed actions run immediately.","loading": "Loading apps...","load_failed": "Couldn't load apps.",- "team_title": "Team accounts",- "team_description": "Shared accounts the workspace owns, such as a support inbox or the company GitHub. Admins connect them; agents given the team account act as it.",- "team_empty": "No team accounts yet.",- "team_empty_member": "No team accounts yet. Ask a workspace admin to connect one.",- "personal_title": "My accounts",- "personal_description": "Your own accounts. When you trigger a run, agents use these for apps set to the triggerer's account.",- "personal_empty": "You haven't connected any accounts.",- "connected_by": "Connected by {{name}}",- "last_used": "Last used {{when}}",- "last_used_never": "Never used",- "used_by_one": "Used by {{count}} agent",- "used_by_other": "Used by {{count}} agents",- "expired": "Needs reconnecting","reconnect": "Reconnect","rules": "Rules","activity": "Activity",@@ -1880,35 +1866,7 @@"toast_disconnected": "Disconnected","toast_failed": "Something went wrong. Please try again.","add": {- "search": "Search apps...",- "empty": "No apps match.",- "curated": "Curated",- "recommended_team": "Usually a team account",- "recommended_personal": "Usually a personal account",- "connect_team": "Connect team account",- "connect_personal": "Connect my account",- "connecting": "Connecting...",- "connected": "Connected",- "connect": "Connect",- "team_description": "A shared workspace account. Choose which agents can use it on each agent’s Apps page.",- "personal_description": "Use your own connected account when you start a run."- },- "disconnect_team": {- "title": "Disconnect the team {{app}} account?",- "description": "Agents using the team account lose access right away.",- "agents": "Agents using it",- "no_agents": "No agent uses it.",- "active_tasks": "Runs in progress: {{count}}",- "active_autopilots": "Active autopilots: {{count}}",- "pending": "Confirmations that will be cancelled: {{count}}",- "cancel": "Cancel",- "confirm": "Disconnect"- },- "disconnect_personal": {- "title": "Disconnect your {{app}} account?",- "description": "Runs you trigger can no longer use it. You can reconnect later.",- "cancel": "Cancel",- "confirm": "Disconnect"+ "empty": "No apps match."},"detail": {"team_title": "{{app}} · team account",@@ -1996,7 +1954,13 @@"rate_limited": "This account reached its limit of calls per minute. Approve again in a minute.","rate_limited_some_one": "{{count}} request hit the per-minute limit. Approve it again in a minute.","rate_limited_some_other": "{{count}} requests hit the per-minute limit. Approve them again in a minute.",- "withdrawn": "You can no longer use this agent, so the request was withdrawn."+ "withdrawn": "You can no longer use this agent, so the request was withdrawn.",+ "title_connect_team": "{{agent}} needs a {{app}} account",+ "title_member_ask": "{{name}} asked for a team {{app}} account",+ "waiting_for_admin": "Waiting for an admin",+ "team_note": "Every agent that acts as the team account can use it.",+ "admins_notified": "Workspace admins were notified in Inbox.",+ "connect_team": "Connect for the team"},"tools": {"tab": "Tools",@@ -2032,6 +1996,126 @@"cancel": "Cancel","admin_required": "A workspace admin can restore access.","account_link": "This account has saved action restrictions. Restore access in Connected apps."+ },+ "status": {+ "connected": "Connected",+ "not_connected": "Not connected",+ "needs_reconnecting": "Needs reconnecting",+ "requested": "Requested"+ },+ "owner": {+ "team": "Team account",+ "personal": "Your account"+ },+ "account_row": {+ "admins_notified": "admins notified",+ "withdraw": "Withdraw",+ "decline": "Decline",+ "toast_declined": "Requests declined. Waiting agents continue without it.",+ "toast_withdrawn": "Request withdrawn"+ },+ "disclosure": {+ "title": "Connect {{app}}",+ "personal_subtitle": "Your own account. You'll sign in to the app on the next screen.",+ "team_subtitle": "A team account the whole workspace shares. You'll sign in to the app on the next screen.",+ "without_asking": "Agents can do this without asking each time",+ "logged": "Every call an agent makes is recorded on the issue or chat it ran for.",+ "used_by": "Agents using {{app}}: {{agents}}. They'll act as this account.",+ "used_by_none": "No agent uses this app yet. Add it to an agent from the agent's page.",+ "visibility_personal": "Only runs you start use it. It also works in your other workspaces.",+ "visibility_team": "Agents given the team account act as it, whoever starts the run.",+ "cancel": "Cancel",+ "continue": "Continue"+ },+ "hub": {+ "description": "Everything agents in {{workspace}} can work in, and whose account they use.",+ "tabs": {+ "in_use": "In use",+ "attention": "Needs attention",+ "accounts": "Accounts",+ "all": "All apps"+ },+ "search": "Search apps",+ "popular": "Popular in {{workspace}}",+ "scope_team": "Team account",+ "scope_personal": "Personal account",+ "scope_both": "Team and personal accounts",+ "used_by": "Used by {{agents}}",+ "wanted_by": "Wanted by {{agents}}",+ "asked_by": "Asked for by {{names}}",+ "members_asked_one": "{{count}} member asked",+ "members_asked_other": "{{count}} members asked",+ "set_up": "Set up",+ "connect": "Connect",+ "reconnect": "Reconnect",+ "ask_admin": "Ask an admin",+ "toast_requested": "Workspace admins were asked to connect {{app}}.",+ "empty_in_use": "No apps in use yet. Set one up to let agents work in it.",+ "empty_attention": "Nothing needs your attention.",+ "no_matches": "No apps match your search.",+ "unavailable": "Apps aren't available on this server.",+ "retry": "Try again"+ },+ "app_page": {+ "agents_title": "Agents",+ "agents_empty": "This workspace has no agents yet.",+ "source_label": "Account {{agent}} uses for {{app}}",+ "source_team": "Team account",+ "source_personal": "Whoever starts the run",+ "not_using": "Not using {{app}}",+ "enable": "Let {{agent}} use {{app}}",+ "team_admin_only": "Only workspace admins can change team account access.",+ "save_failed": "Couldn't update the agent.",+ "activity_title": "Recent activity",+ "activity_empty": "No agent has used {{app}} yet.",+ "as_team": "as team account",+ "as_you": "as you",+ "in_chat": "chat",+ "accounts_title": "Accounts",+ "account_actions": "{{account}} actions",+ "capabilities_title": "What agents can do",+ "capabilities_note": "Without asking each time.",+ "accounts_description": "Which {{app}} sign-ins agents can use in {{workspace}}.",+ "team_account_hint": "Shared by everyone in {{workspace}} · admins connect it",+ "your_account_hint": "Used only in runs you start",+ "agents_description": "Each agent picks whose account it acts as.",+ "ready_team": "Ready with the team account",+ "needs_team": "Needs the team account",+ "ready_yours": "Ready with your account",+ "needs_yours": "Needs your account"+ },+ "accounts_page": {+ "empty": "You haven't connected any accounts in this workspace.",+ "used_by": "used by {{agents}}",+ "team_title": "Team accounts",+ "team_description_admin": "Shared by everyone in the workspace. Only admins connect them.",+ "team_description_member": "Admins connect these. You can see them and ask for one.",+ "team_empty": "No team accounts yet.",+ "yours_title": "Your accounts",+ "yours_description": "Only you can use these; agents use them in runs you start.",+ "needed_by": "{{agents}} needs it"+ },+ "disconnect_dialog": {+ "title": "Disconnect {{app}}?",+ "team_body": "These agents act as this account. Their next {{app}} step will ask the admins instead of working.",+ "personal_body": "These agents use it in runs you start. The next run you start will ask you to connect it again.",+ "agents": "Agents that use it",+ "no_agents": "No agent uses it.",+ "running": "Run in progress — it stops",+ "active_runs_one": "{{count}} run in progress stops now.",+ "active_runs_other": "{{count}} runs in progress stop now.",+ "impact_failed": "Couldn't check which agents use it.",+ "cancel": "Cancel",+ "confirm": "Disconnect"+ },+ "team_requests": {+ "title": "{{app}} team account needed",+ "run_waiting": "Run waiting",+ "asked": "Asked",+ "summary": " · “{{summary}}”",+ "resumes": "Connecting it once answers every request here, and waiting runs pick up where they stopped.",+ "decline_all": "Decline all",+ "open_app": "Open app"}},"voice_input": {diff --git a/packages/views/locales/es/agents.json b/packages/views/locales/es/agents.jsonindex 1d8aeb1821..88658c8dd9 100644--- a/packages/views/locales/es/agents.json+++ b/packages/views/locales/es/agents.json@@ -790,13 +790,9 @@"load_failed": "No se pudieron cargar las aplicaciones de este agente.","empty": "No hay apps conectadas disponibles.","level": "Alcance de la cuenta",- "team_connected": "Cuenta del equipo conectada",- "team_missing": "Cuenta del equipo sin conectar",- "personal_connected": "Tu cuenta está conectada",- "personal_missing": "No has conectado esta aplicación","team_admin_only": "Solo los administradores del espacio de trabajo pueden dar a un agente acceso a una cuenta del equipo.","team_shared_warning": "Cualquiera que pueda ejecutar este agente podrá usar esta cuenta de equipo a través de él.",- "manage_link": "Gestionar cuentas en Ajustes → Aplicaciones conectadas",+ "manage_link": "Gestionar cuentas en Apps → Cuentas","save_failed_toast": "No se pudo guardar. Inténtalo de nuevo","team_help": "Cuenta compartida del espacio de trabajo, conectada por administradores.","personal_help": "Cada ejecución usa la cuenta de quien la inicia. Cada persona debe conectar su propia cuenta.",@@ -1075,7 +1071,14 @@"status": "Estado","runs_7d": "Ejecuciones (7 d)","edit_access_aria": "Acceso: {{value}}. Cambiar acceso",- "all_settings": "Todos los ajustes"+ "all_settings": "Todos los ajustes",+ "apps": "Apps",+ "apps_needs_account_one": "{{count}} necesita tu cuenta",+ "apps_needs_account_other": "{{count}} necesitan tu cuenta",+ "apps_count_one": "{{count}} aplicación",+ "apps_count_other": "{{count}} aplicaciones",+ "apps_none": "Ninguna",+ "apps_aria": "Apps: {{value}}. Mostrar apps"},"intro": {"title": "Incorpora a tu primer compañero de IA",@@ -1100,5 +1103,36 @@"comment": "Corregido: las tarjetas de precios se apilan en una columna por debajo de 375 px. El PR está abierto y los tests pasan.","step_read": "Leer {{file}}"}+ },+ "apps_section": {+ "title": "Apps",+ "empty": "Este agente aún no usa ninguna aplicación.",+ "connect_yours": "Conectar la tuya",+ "reconnect": "Volver a conectar",+ "connect_team": "Conectar cuenta del equipo",+ "acts_as_team": "Actúa con la cuenta del equipo",+ "acts_as_starter": "Actúa con la cuenta de quien inicia la ejecución"+ },+ "add_app_dialog": {+ "title": "Añadir una aplicación a {{agent}}",+ "description": "Una aplicación con cuenta personal usa la cuenta de quien inicia el agente, así que puedes añadirla sin tener tu propia cuenta.",+ "search_one": "Buscar entre {{count}} aplicación",+ "search_other": "Buscar entre {{count}} aplicaciones",+ "search_label": "Buscar aplicaciones",+ "curated": "Seleccionada",+ "recommended_team": "Suele usarse una cuenta del equipo",+ "recommended_personal": "Suele usarse una cuenta personal",+ "team_connected": "Cuenta del equipo conectada",+ "add": "Añadir",+ "add_aria": "Añadir {{app}}",+ "empty": "No hay aplicaciones que coincidan.",+ "load_failed": "No se pudieron cargar las aplicaciones.",+ "added_toast": "{{app}} se añadió a {{agent}}."+ },+ "app_requests": {+ "title_adds_app": "{{agent}} quiere usar {{app}}",+ "new_app": "Nueva aplicación para este agente",+ "adds_app_note": "Al responder, se añade {{app}} a {{agent}} para las próximas ejecuciones.",+ "add_to_agent": "Añadir {{app}} a {{agent}}"}}diff --git a/packages/views/locales/es/inbox.json b/packages/views/locales/es/inbox.jsonindex f12862eaba..8cf0bd824d 100644--- a/packages/views/locales/es/inbox.json+++ b/packages/views/locales/es/inbox.json@@ -71,6 +71,7 @@"autopilot_quota_exceeded_body": "Este espacio de trabajo alcanzó su límite de {{limit}} ejecuciones de autopilot del periodo actual. Las siguientes ejecuciones no se iniciarán hasta que la asignación se restablezca {{resetAt}}, o hasta que el espacio de trabajo mejore su plan o compre más ejecuciones.","project_owner_joined_body": "{{name}} es propietario del espacio de trabajo y se ha añadido a este proyecto privado. Ahora puede ver sus tareas, comentarios y archivos adjuntos.","open_project": "Abrir proyecto",+ "open_app": "Abrir app","autopilot_quota_upgrade": "Ver opciones","archive": "Archivar","unarchive": "Desarchivar",diff --git a/packages/views/locales/es/layout.json b/packages/views/locales/es/layout.jsonindex cc7b60554c..72edf8840d 100644--- a/packages/views/locales/es/layout.json+++ b/packages/views/locales/es/layout.json@@ -11,6 +11,7 @@"usage": "Analítica","runtimes": "Runtimes","skills": "Skills",+ "apps": "Apps","settings": "Ajustes","views": "Vistas","docs": "Documentos"@@ -23,6 +24,7 @@"member": "Miembro","squad": "Squad","skill": "Skill",+ "app": "App","machine": "Máquina","runtime": "Runtime","attachment": "Adjunto",diff --git a/packages/views/locales/es/settings.json b/packages/views/locales/es/settings.jsonindex 651e8fa9cd..b47773dd38 100644--- a/packages/views/locales/es/settings.json+++ b/packages/views/locales/es/settings.json@@ -599,7 +599,6 @@"plugins": "Plugins","mcp": "MCP","billing": "Facturación",- "apps": "Apps conectadas","channels": "Mensajería","code": "Código","workflows": "Flujos de trabajo",@@ -1801,6 +1800,7 @@},"scope": {"account": "Cuenta · sincronizado",+ "all_workspaces": "Todos tus espacios de trabajo","device": "Solo este dispositivo","device_workspace": "Este dispositivo · {{name}}","workspace": "Espacio de trabajo {{name}}",@@ -1849,22 +1849,8 @@"authorization_expired": "La autorización de WeChat ha caducado. Escanea de nuevo para reconectar."},"connected_apps": {- "description": "Cuentas que usan tus agentes para acceder a aplicaciones externas. Las acciones permitidas se ejecutan de inmediato.","loading": "Cargando aplicaciones…","load_failed": "No se pudieron cargar las aplicaciones.",- "team_title": "Cuentas del equipo",- "team_description": "Cuentas compartidas del espacio de trabajo, como el buzón de soporte o el GitHub de la empresa. Los administradores las conectan; los agentes que tienen acceso actúan con esa cuenta.",- "team_empty": "Aún no hay cuentas del equipo.",- "team_empty_member": "Aún no hay cuentas del equipo. Pide a un administrador del espacio de trabajo que conecte una.",- "personal_title": "Mis cuentas",- "personal_description": "Tus propias cuentas. Cuando inicias una ejecución, los agentes las usan en las aplicaciones configuradas con la cuenta de quien inicia la ejecución.",- "personal_empty": "No has conectado ninguna cuenta.",- "connected_by": "Conectada por {{name}}",- "last_used": "Último uso {{when}}",- "last_used_never": "Sin usar",- "used_by_one": "La usa {{count}} agente",- "used_by_other": "La usan {{count}} agentes",- "expired": "Necesita volver a conectarse","reconnect": "Volver a conectar","rules": "Reglas","activity": "Actividad",@@ -1880,35 +1866,7 @@"toast_disconnected": "Desconectada","toast_failed": "Algo salió mal. Inténtalo de nuevo.","add": {- "search": "Buscar aplicaciones…",- "empty": "No hay aplicaciones que coincidan.",- "curated": "Seleccionada",- "recommended_team": "Suele usarse una cuenta del equipo",- "recommended_personal": "Suele usarse una cuenta personal",- "connect_team": "Conectar cuenta de equipo",- "connect_personal": "Conectar mi cuenta",- "connecting": "Conectando…",- "connected": "Conectada",- "connect": "Conectar",- "team_description": "Conecta una cuenta compartida del espacio de trabajo. Decide qué agentes pueden usarla en la página Apps de cada agente.",- "personal_description": "Usa tu propia cuenta conectada cuando inicies una ejecución."- },- "disconnect_team": {- "title": "¿Desconectar la cuenta del equipo de {{app}}?",- "description": "Los agentes que usan la cuenta del equipo perderán el acceso de inmediato.",- "agents": "Agentes que la usan",- "no_agents": "Ningún agente la usa.",- "active_tasks": "Ejecuciones en curso: {{count}}",- "active_autopilots": "Automatizaciones activas: {{count}}",- "pending": "Confirmaciones que se cancelarán: {{count}}",- "cancel": "Cancelar",- "confirm": "Desconectar"- },- "disconnect_personal": {- "title": "¿Desconectar tu cuenta de {{app}}?",- "description": "Las ejecuciones que inicies ya no podrán usarla. Puedes volver a conectarla más adelante.",- "cancel": "Cancelar",- "confirm": "Desconectar"+ "empty": "No hay aplicaciones que coincidan."},"detail": {"team_title": "{{app}} · cuenta del equipo",@@ -1959,6 +1917,36 @@"team": "Cuenta del equipo","personal": "Cuenta de quien inicia"},+ "status": {+ "connected": "Conectada",+ "not_connected": "Sin conectar",+ "needs_reconnecting": "Hay que reconectarla",+ "requested": "Solicitada"+ },+ "owner": {+ "team": "Cuenta del equipo",+ "personal": "Tu cuenta"+ },+ "account_row": {+ "admins_notified": "administradores avisados",+ "withdraw": "Retirar",+ "decline": "Rechazar",+ "toast_declined": "Solicitudes rechazadas. Los agentes en espera siguen sin ella.",+ "toast_withdrawn": "Solicitud retirada"+ },+ "disclosure": {+ "title": "Conectar {{app}}",+ "personal_subtitle": "Tu propia cuenta. Iniciarás sesión en la aplicación en la siguiente pantalla.",+ "team_subtitle": "Una cuenta del equipo que comparte todo el espacio de trabajo. Iniciarás sesión en la aplicación en la siguiente pantalla.",+ "without_asking": "Los agentes pueden hacer esto sin preguntar cada vez",+ "logged": "Cada llamada de un agente queda registrada en la tarea o el chat para el que se ejecutó.",+ "used_by": "Agentes que usan {{app}}: {{agents}}. Actuarán como esta cuenta.",+ "used_by_none": "Ningún agente usa esta aplicación todavía. Añádela a un agente desde su página.",+ "visibility_personal": "Solo la usan las ejecuciones que inicias. También funciona en tus otros espacios de trabajo.",+ "visibility_team": "Los agentes con la cuenta del equipo actúan como ella, sin importar quién inicie la ejecución.",+ "cancel": "Cancelar",+ "continue": "Continuar"+ },"levels": {"read": "Solo lectura","confirm_writes": "Preguntar antes de escribir",@@ -1996,7 +1984,13 @@"rate_limited": "Esta cuenta alcanzó su límite de llamadas por minuto. Vuelve a aprobar la solicitud dentro de un minuto.","rate_limited_some_one": "{{count}} solicitud alcanzó el límite por minuto. Vuelve a aprobarla dentro de un minuto.","rate_limited_some_other": "{{count}} solicitudes alcanzaron el límite por minuto. Vuelve a aprobarlas dentro de un minuto.",- "withdrawn": "Ya no puedes usar este agente, por lo que se retiró la solicitud."+ "withdrawn": "Ya no puedes usar este agente, por lo que se retiró la solicitud.",+ "title_connect_team": "{{agent}} necesita una cuenta de {{app}}",+ "title_member_ask": "{{name}} pidió una cuenta del equipo de {{app}}",+ "waiting_for_admin": "Esperando a un administrador",+ "team_note": "Todos los agentes que actúan con la cuenta del equipo podrán usarla.",+ "admins_notified": "Se avisó a los administradores en la bandeja de entrada.",+ "connect_team": "Conectar para el equipo"},"tools": {"tab": "Herramientas",@@ -2032,6 +2026,96 @@"cancel": "Cancelar","admin_required": "Un administrador puede restablecer el acceso.","account_link": "Esta cuenta conserva restricciones. Restablece el acceso en Apps conectadas."+ },+ "hub": {+ "description": "Todas las aplicaciones con las que pueden trabajar los agentes de {{workspace}} y la cuenta que usan.",+ "tabs": {+ "in_use": "En uso",+ "attention": "Requieren atención",+ "accounts": "Cuentas",+ "all": "Todas las aplicaciones"+ },+ "search": "Buscar aplicaciones",+ "popular": "Populares en {{workspace}}",+ "scope_team": "Cuenta del equipo",+ "scope_personal": "Cuenta personal",+ "scope_both": "Cuentas del equipo y personales",+ "used_by": "La usan {{agents}}",+ "wanted_by": "La quieren {{agents}}",+ "asked_by": "Solicitada por {{names}}",+ "members_asked_one": "{{count}} miembro la solicitó",+ "members_asked_other": "{{count}} miembros la solicitaron",+ "set_up": "Configurar",+ "connect": "Conectar",+ "reconnect": "Volver a conectar",+ "ask_admin": "Pedir a un administrador",+ "toast_requested": "Se pidió a los administradores del espacio de trabajo que conecten {{app}}.",+ "empty_in_use": "Aún no hay aplicaciones en uso. Configura una para que los agentes trabajen con ella.",+ "empty_attention": "No hay nada que requiera tu atención.",+ "no_matches": "Ninguna aplicación coincide con tu búsqueda.",+ "unavailable": "Las aplicaciones no están disponibles en este servidor.",+ "retry": "Reintentar"+ },+ "app_page": {+ "agents_title": "Agentes",+ "agents_empty": "Este espacio de trabajo aún no tiene agentes.",+ "source_label": "Cuenta que {{agent}} usa para {{app}}",+ "source_team": "Cuenta del equipo",+ "source_personal": "Quien inicia la ejecución",+ "not_using": "No usa {{app}}",+ "enable": "Permitir que {{agent}} use {{app}}",+ "team_admin_only": "Solo los administradores del espacio de trabajo pueden cambiar el acceso a la cuenta del equipo.",+ "save_failed": "No se pudo actualizar el agente.",+ "activity_title": "Actividad reciente",+ "activity_empty": "Ningún agente ha usado {{app}} todavía.",+ "as_team": "como cuenta del equipo",+ "as_you": "como tú",+ "in_chat": "chat",+ "accounts_title": "Cuentas",+ "account_actions": "Acciones de {{account}}",+ "capabilities_title": "Qué pueden hacer los agentes",+ "capabilities_note": "Sin preguntar cada vez.",+ "accounts_description": "Qué cuentas de {{app}} pueden usar los agentes en {{workspace}}.",+ "team_account_hint": "Compartida por todos en {{workspace}} · la conectan los administradores",+ "your_account_hint": "Solo se usa en las ejecuciones que inicias tú",+ "agents_description": "Cada agente elige con qué cuenta actúa.",+ "ready_team": "Lista con la cuenta del equipo",+ "needs_team": "Necesita la cuenta del equipo",+ "ready_yours": "Lista con tu cuenta",+ "needs_yours": "Necesita tu cuenta"+ },+ "accounts_page": {+ "empty": "No has conectado ninguna cuenta en este espacio de trabajo.",+ "used_by": "la usa {{agents}}",+ "team_title": "Cuentas del equipo",+ "team_description_admin": "Las comparte todo el espacio de trabajo. Solo los administradores las conectan.",+ "team_description_member": "Las conectan los administradores. Puedes verlas y pedir una.",+ "team_empty": "Todavía no hay cuentas del equipo.",+ "yours_title": "Tus cuentas",+ "yours_description": "Solo tú puedes usarlas; los agentes las usan en las ejecuciones que inicias.",+ "needed_by": "{{agents}} la necesita"+ },+ "disconnect_dialog": {+ "title": "¿Desconectar {{app}}?",+ "team_body": "Estos agentes actúan con esta cuenta. En su próximo paso con {{app}} pedirán ayuda a los administradores en lugar de trabajar.",+ "personal_body": "Estos agentes la usan en las ejecuciones que inicias. La próxima vez que inicies una te pedirán que la vuelvas a conectar.",+ "agents": "Agentes que la usan",+ "no_agents": "Ningún agente la usa.",+ "running": "Ejecución en curso: se detiene",+ "active_runs_one": "Se detiene ahora {{count}} ejecución en curso.",+ "active_runs_other": "Se detienen ahora {{count}} ejecuciones en curso.",+ "impact_failed": "No se pudo comprobar qué agentes la usan.",+ "cancel": "Cancelar",+ "confirm": "Desconectar"+ },+ "team_requests": {+ "title": "Se necesita la cuenta del equipo de {{app}}",+ "run_waiting": "Ejecución en espera",+ "asked": "Pedida",+ "summary": " · «{{summary}}»",+ "resumes": "Conectarla una vez responde a todas estas solicitudes, y las ejecuciones en espera continúan donde se quedaron.",+ "decline_all": "Rechazar todas",+ "open_app": "Abrir app"}},"voice_input": {diff --git a/packages/views/locales/fr/agents.json b/packages/views/locales/fr/agents.jsonindex e933e3d69b..8e9c9918e9 100644--- a/packages/views/locales/fr/agents.json+++ b/packages/views/locales/fr/agents.json@@ -223,7 +223,14 @@"status": "Statut","runs_7d": "Exécutions (7 j)","edit_access_aria": "Accès : {{value}}. Modifier l'accès",- "all_settings": "Tous les paramètres"+ "all_settings": "Tous les paramètres",+ "apps": "Apps",+ "apps_needs_account_one": "{{count}} requiert votre compte",+ "apps_needs_account_other": "{{count}} requièrent votre compte",+ "apps_count_one": "{{count}} app",+ "apps_count_other": "{{count}} apps",+ "apps_none": "Aucune",+ "apps_aria": "Apps : {{value}}. Afficher les apps"},"pickers": {"concurrency_range": "Exécutions simultanées maximales ({{min}}–{{max}})",@@ -808,13 +815,9 @@"load_failed": "Impossible de charger les apps de cet agent.","empty": "Aucune app connectée disponible.","level": "Portée du compte",- "team_connected": "Compte d'équipe connecté",- "team_missing": "Compte d'équipe non connecté",- "personal_connected": "Votre compte est connecté",- "personal_missing": "Vous n'avez pas connecté cette app","team_admin_only": "Seuls les admins de l'espace peuvent donner un compte d'équipe à un agent.","team_shared_warning": "Toute personne pouvant exécuter cet agent peut utiliser ce compte d’équipe par son intermédiaire.",- "manage_link": "Gérer les comptes dans Paramètres → Applications connectées",+ "manage_link": "Gérer les comptes dans Apps → Comptes","save_failed_toast": "Échec de l'enregistrement, veuillez réessayer","team_help": "Compte partagé de l’espace de travail, connecté par les administrateurs.","personal_help": "Chaque exécution utilise le compte de la personne qui la déclenche. Chacun doit connecter son compte.",@@ -1100,5 +1103,36 @@"comment": "Corrigé : sous 375px, les cartes tarifs passent sur une colonne. PR ouverte, tests au vert.","step_read": "Lecture de {{file}}"}+ },+ "apps_section": {+ "title": "Apps",+ "empty": "Cet agent n'utilise encore aucune app.",+ "connect_yours": "Connecter le vôtre",+ "reconnect": "Reconnecter",+ "connect_team": "Connecter un compte d'équipe",+ "acts_as_team": "Agit avec le compte d'équipe",+ "acts_as_starter": "Agit avec le compte de la personne qui lance l'exécution"+ },+ "add_app_dialog": {+ "title": "Ajouter une app à {{agent}}",+ "description": "Une app avec compte personnel utilise le compte de la personne qui lance l'agent : vous pouvez donc l'ajouter sans avoir votre propre compte.",+ "search_one": "Rechercher parmi {{count}} app",+ "search_other": "Rechercher parmi {{count}} apps",+ "search_label": "Rechercher une app",+ "curated": "Sélection",+ "recommended_team": "Souvent un compte d'équipe",+ "recommended_personal": "Souvent un compte personnel",+ "team_connected": "Compte d'équipe connecté",+ "add": "Ajouter",+ "add_aria": "Ajouter {{app}}",+ "empty": "Aucune app ne correspond.",+ "load_failed": "Impossible de charger les apps.",+ "added_toast": "{{app}} ajoutée à {{agent}}."+ },+ "app_requests": {+ "title_adds_app": "{{agent}} veut utiliser {{app}}",+ "new_app": "Nouvelle app pour cet agent",+ "adds_app_note": "Répondre ajoute {{app}} à {{agent}} pour les prochaines exécutions.",+ "add_to_agent": "Ajouter {{app}} à {{agent}}"}}diff --git a/packages/views/locales/fr/inbox.json b/packages/views/locales/fr/inbox.jsonindex 062c1b4491..4c12b1bba1 100644--- a/packages/views/locales/fr/inbox.json+++ b/packages/views/locales/fr/inbox.json@@ -71,6 +71,7 @@"autopilot_quota_exceeded_body": "Cet espace de travail a atteint sa limite de {{limit}} exécutions d'autopilot pour la période en cours. Les exécutions suivantes ne démarreront pas avant la réinitialisation de l'allocation {{resetAt}}, ou avant que l'espace de travail change de forfait ou achète des exécutions.","project_owner_joined_body": "{{name}}, propriétaire de l’espace de travail, s’est ajouté à ce projet privé et peut désormais voir ses tâches, commentaires et pièces jointes.","open_project": "Ouvrir le projet",+ "open_app": "Ouvrir l'app","autopilot_quota_upgrade": "Voir les options","archive": "Archiver","unarchive": "Désarchiver",diff --git a/packages/views/locales/fr/layout.json b/packages/views/locales/fr/layout.jsonindex d84aed4ad3..214b371e6c 100644--- a/packages/views/locales/fr/layout.json+++ b/packages/views/locales/fr/layout.json@@ -11,6 +11,7 @@"usage": "Statistiques","runtimes": "Runtimes","skills": "Skills",+ "apps": "Apps","settings": "Paramètres","views": "Vues","docs": "Documents"@@ -23,6 +24,7 @@"member": "Membre","squad": "Squad","skill": "Skill",+ "app": "App","machine": "Machine","runtime": "Runtime","attachment": "Pièce jointe",diff --git a/packages/views/locales/fr/settings.json b/packages/views/locales/fr/settings.jsonindex 3d1243cca5..eb147f5b3e 100644--- a/packages/views/locales/fr/settings.json+++ b/packages/views/locales/fr/settings.json@@ -601,7 +601,6 @@"billing": "Facturation","code": "Code","channels": "Messagerie",- "apps": "Applications connectées","workflows": "Workflows","voice_input": "Saisie vocale"},@@ -1759,6 +1758,7 @@"layout": {"scope": {"account": "Compte · synchronisé",+ "all_workspaces": "Tous vos espaces de travail","device": "Cet appareil uniquement","device_workspace": "Cet appareil · {{name}}","workspace": "Espace {{name}}",@@ -1849,22 +1849,8 @@"authorization_expired": "L’autorisation WeChat a expiré. Scannez à nouveau pour vous reconnecter."},"connected_apps": {- "description": "Les comptes que vos agents utilisent pour accéder aux apps externes. Les actions autorisées sont exécutées immédiatement.","loading": "Chargement des apps…","load_failed": "Impossible de charger les apps.",- "team_title": "Comptes d'équipe",- "team_description": "Les comptes partagés de l'espace de travail, comme une boîte support ou le GitHub de l'entreprise. Les admins les connectent ; les agents qui reçoivent le compte d'équipe agissent en son nom.",- "team_empty": "Aucun compte d'équipe pour l'instant.",- "team_empty_member": "Aucun compte d'équipe pour l'instant. Demandez à un admin de l'espace d'en connecter un.",- "personal_title": "Mes comptes",- "personal_description": "Vos propres comptes. Quand vous lancez une exécution, les apps réglées sur le compte du déclencheur les utilisent.",- "personal_empty": "Vous n'avez connecté aucun compte.",- "connected_by": "Connecté par {{name}}",- "last_used": "Dernière utilisation {{when}}",- "last_used_never": "Jamais utilisé",- "used_by_one": "Utilisé par {{count}} agent",- "used_by_other": "Utilisé par {{count}} agents",- "expired": "À reconnecter","reconnect": "Reconnecter","rules": "Règles","activity": "Activité",@@ -1880,35 +1866,7 @@"toast_disconnected": "Déconnecté","toast_failed": "Une erreur est survenue. Veuillez réessayer.","add": {- "search": "Rechercher une app…",- "empty": "Aucune app ne correspond.",- "curated": "Sélection",- "recommended_team": "Souvent un compte d'équipe",- "recommended_personal": "Souvent un compte personnel",- "connect_team": "Connecter un compte d’équipe",- "connect_personal": "Connecter mon compte",- "connecting": "Connexion…",- "connected": "Connecté",- "connect": "Connecter",- "team_description": "Connectez un compte partagé de l’espace de travail. Autorisez son utilisation sur la page Apps de chaque agent.",- "personal_description": "Utilisez votre propre compte connecté lorsque vous lancez une exécution."- },- "disconnect_team": {- "title": "Déconnecter le compte {{app}} de l'équipe ?",- "description": "Les agents qui utilisent le compte d'équipe perdent l'accès immédiatement.",- "agents": "Agents qui l'utilisent",- "no_agents": "Aucun agent ne l'utilise.",- "active_tasks": "Exécutions en cours : {{count}}",- "active_autopilots": "Autopilotes actifs : {{count}}",- "pending": "Confirmations qui seront annulées : {{count}}",- "cancel": "Annuler",- "confirm": "Déconnecter"- },- "disconnect_personal": {- "title": "Déconnecter votre compte {{app}} ?",- "description": "Les exécutions que vous lancez ne pourront plus l'utiliser. Vous pourrez le reconnecter plus tard.",- "cancel": "Annuler",- "confirm": "Déconnecter"+ "empty": "Aucune app ne correspond."},"detail": {"team_title": "{{app}} · compte d'équipe",@@ -1959,6 +1917,36 @@"team": "Compte d'équipe","personal": "Compte du déclencheur"},+ "status": {+ "connected": "Connecté",+ "not_connected": "Non connecté",+ "needs_reconnecting": "À reconnecter",+ "requested": "Demandé"+ },+ "owner": {+ "team": "Compte d'équipe",+ "personal": "Votre compte"+ },+ "account_row": {+ "admins_notified": "admins prévenus",+ "withdraw": "Retirer",+ "decline": "Refuser",+ "toast_declined": "Demandes refusées. Les agents en attente continuent sans.",+ "toast_withdrawn": "Demande retirée"+ },+ "disclosure": {+ "title": "Connecter {{app}}",+ "personal_subtitle": "Votre compte personnel. Vous vous connecterez à l'app à l'écran suivant.",+ "team_subtitle": "Un compte d'équipe partagé par tout l'espace de travail. Vous vous connecterez à l'app à l'écran suivant.",+ "without_asking": "Les agents peuvent le faire sans demander à chaque fois",+ "logged": "Chaque appel d'un agent est enregistré sur la tâche ou la discussion pour laquelle il s'est exécuté.",+ "used_by": "Agents qui utilisent {{app}} : {{agents}}. Ils agiront avec ce compte.",+ "used_by_none": "Aucun agent n'utilise encore cette app. Ajoutez-la à un agent depuis sa page.",+ "visibility_personal": "Seules les exécutions que vous lancez l'utilisent. Il fonctionne aussi dans vos autres espaces de travail.",+ "visibility_team": "Les agents dotés du compte d'équipe agissent avec ce compte, quelle que soit la personne qui lance l'exécution.",+ "cancel": "Annuler",+ "continue": "Continuer"+ },"levels": {"read": "Lecture seule","confirm_writes": "Demander avant d'écrire",@@ -1996,7 +1984,13 @@"rate_limited": "Ce compte a atteint sa limite d'appels par minute. Approuvez à nouveau dans une minute.","rate_limited_some_one": "{{count}} demande a atteint la limite par minute. Approuvez-la à nouveau dans une minute.","rate_limited_some_other": "{{count}} demandes ont atteint la limite par minute. Approuvez-les à nouveau dans une minute.",- "withdrawn": "Vous ne pouvez plus utiliser cet agent ; la demande a été retirée."+ "withdrawn": "Vous ne pouvez plus utiliser cet agent ; la demande a été retirée.",+ "title_connect_team": "{{agent}} a besoin d'un compte {{app}}",+ "title_member_ask": "{{name}} a demandé un compte d'équipe {{app}}",+ "waiting_for_admin": "En attente d'un admin",+ "team_note": "Tous les agents qui agissent avec le compte d'équipe pourront l'utiliser.",+ "admins_notified": "Les admins de l'espace de travail ont été prévenus dans la boîte de réception.",+ "connect_team": "Connecter pour l'équipe"},"tools": {"tab": "Outils",@@ -2032,6 +2026,96 @@"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."+ },+ "hub": {+ "description": "Toutes les apps avec lesquelles les agents de {{workspace}} peuvent travailler, et le compte qu'ils utilisent.",+ "tabs": {+ "in_use": "Utilisées",+ "attention": "À traiter",+ "accounts": "Comptes",+ "all": "Toutes les apps"+ },+ "search": "Rechercher une app",+ "popular": "Populaires dans {{workspace}}",+ "scope_team": "Compte d'équipe",+ "scope_personal": "Compte personnel",+ "scope_both": "Comptes d'équipe et personnels",+ "used_by": "Utilisée par {{agents}}",+ "wanted_by": "Demandée par {{agents}}",+ "asked_by": "Demandée par {{names}}",+ "members_asked_one": "{{count}} membre l'a demandée",+ "members_asked_other": "{{count}} membres l'ont demandée",+ "set_up": "Configurer",+ "connect": "Connecter",+ "reconnect": "Reconnecter",+ "ask_admin": "Demander à un admin",+ "toast_requested": "Les admins de l'espace ont reçu une demande pour connecter {{app}}.",+ "empty_in_use": "Aucune app utilisée pour l'instant. Configurez-en une pour que les agents puissent l'utiliser.",+ "empty_attention": "Rien ne nécessite votre attention.",+ "no_matches": "Aucune app ne correspond à votre recherche.",+ "unavailable": "Les apps ne sont pas disponibles sur ce serveur.",+ "retry": "Réessayer"+ },+ "app_page": {+ "agents_title": "Agents",+ "agents_empty": "Cet espace de travail n'a pas encore d'agents.",+ "source_label": "Compte que {{agent}} utilise pour {{app}}",+ "source_team": "Compte d'équipe",+ "source_personal": "La personne qui lance l'exécution",+ "not_using": "N'utilise pas {{app}}",+ "enable": "Autoriser {{agent}} à utiliser {{app}}",+ "team_admin_only": "Seuls les admins de l'espace peuvent modifier l'accès au compte d'équipe.",+ "save_failed": "Impossible de mettre à jour l'agent.",+ "activity_title": "Activité récente",+ "activity_empty": "Aucun agent n'a encore utilisé {{app}}.",+ "as_team": "avec le compte d'équipe",+ "as_you": "en votre nom",+ "in_chat": "discussion",+ "accounts_title": "Comptes",+ "account_actions": "Actions : {{account}}",+ "capabilities_title": "Ce que les agents peuvent faire",+ "capabilities_note": "Sans demander à chaque fois.",+ "accounts_description": "Les comptes {{app}} que les agents peuvent utiliser dans {{workspace}}.",+ "team_account_hint": "Partagé par tout {{workspace}} · connecté par les admins",+ "your_account_hint": "Utilisé uniquement dans les exécutions que vous lancez",+ "agents_description": "Chaque agent choisit le compte avec lequel il agit.",+ "ready_team": "Prêt avec le compte d'équipe",+ "needs_team": "Il faut le compte d'équipe",+ "ready_yours": "Prêt avec votre compte",+ "needs_yours": "Il faut votre compte"+ },+ "accounts_page": {+ "empty": "Vous n'avez connecté aucun compte dans cet espace de travail.",+ "used_by": "utilisé par {{agents}}",+ "team_title": "Comptes d'équipe",+ "team_description_admin": "Partagés par tout l'espace de travail. Seuls les admins les connectent.",+ "team_description_member": "Les admins les connectent. Vous pouvez les voir et en demander un.",+ "team_empty": "Aucun compte d'équipe pour l'instant.",+ "yours_title": "Vos comptes",+ "yours_description": "Vous seul pouvez les utiliser ; les agents s'en servent dans les exécutions que vous lancez.",+ "needed_by": "{{agents}} en a besoin"+ },+ "disconnect_dialog": {+ "title": "Déconnecter {{app}} ?",+ "team_body": "Ces agents agissent avec ce compte. À leur prochaine étape dans {{app}}, ils solliciteront les admins au lieu de travailler.",+ "personal_body": "Ces agents l'utilisent dans les exécutions que vous lancez. À la prochaine, ils vous demanderont de le reconnecter.",+ "agents": "Agents qui l'utilisent",+ "no_agents": "Aucun agent ne l'utilise.",+ "running": "Exécution en cours — elle s'arrête",+ "active_runs_one": "{{count}} exécution en cours s'arrête maintenant.",+ "active_runs_other": "{{count}} exécutions en cours s'arrêtent maintenant.",+ "impact_failed": "Impossible de vérifier quels agents l'utilisent.",+ "cancel": "Annuler",+ "confirm": "Déconnecter"+ },+ "team_requests": {+ "title": "Compte d'équipe {{app}} requis",+ "run_waiting": "Exécution en attente",+ "asked": "Demandé",+ "summary": " · « {{summary}} »",+ "resumes": "Le connecter une fois répond à toutes ces demandes, et les exécutions en attente reprennent là où elles se sont arrêtées.",+ "decline_all": "Tout refuser",+ "open_app": "Ouvrir l'app"}},"voice_input": {diff --git a/packages/views/locales/ja/agents.json b/packages/views/locales/ja/agents.jsonindex acbd2581ed..0cd711d9e8 100644--- a/packages/views/locales/ja/agents.json+++ b/packages/views/locales/ja/agents.json@@ -211,7 +211,12 @@"status": "ステータス","runs_7d": "実行 (7日)","edit_access_aria": "アクセス: {{value}}。アクセスを変更",- "all_settings": "すべての設定"+ "all_settings": "すべての設定",+ "apps": "アプリ",+ "apps_needs_account_other": "{{count}} 件が自分のアカウントを必要としています",+ "apps_count_other": "{{count}} 個のアプリ",+ "apps_none": "なし",+ "apps_aria": "アプリ: {{value}}。アプリを表示"},"pickers": {"concurrency_range": "最大同時実行数({{min}}–{{max}})",@@ -645,13 +650,9 @@"load_failed": "このエージェントのアプリを読み込めませんでした。","empty": "接続済みのアプリはありません。","level": "アカウント範囲",- "team_connected": "チームアカウント接続済み",- "team_missing": "チームアカウント未接続",- "personal_connected": "あなたのアカウントは接続済み",- "personal_missing": "このアプリはまだ接続していません","team_admin_only": "エージェントにチームアカウントを付与できるのはワークスペース管理者のみです。","team_shared_warning": "このエージェントを実行できる人は、このチームアカウントを通じて操作できます。",- "manage_link": "設定 → 接続済みアプリ でアカウントを管理",+ "manage_link": "アプリ → アカウント でアカウントを管理","save_failed_toast": "保存できませんでした。もう一度お試しください","team_help": "管理者が接続する、ワークスペース共有のアカウントです。","personal_help": "実行を開始した人のアカウントを使います。各自で接続する必要があります。",@@ -1071,5 +1072,35 @@"comment": "修正しました。375px 以下では料金カードを 1 列にしています。PR を作成し、テストも通っています。","step_read": "{{file}} を読む"}+ },+ "apps_section": {+ "title": "アプリ",+ "empty": "このエージェントはまだアプリを使用していません。",+ "connect_yours": "自分のアカウントを接続",+ "reconnect": "再接続",+ "connect_team": "チームアカウントを接続",+ "acts_as_team": "チームアカウントとして動作",+ "acts_as_starter": "実行を開始した人のアカウントとして動作"+ },+ "add_app_dialog": {+ "title": "{{agent}} にアプリを追加",+ "description": "個人アカウントのアプリはエージェントを開始した人のアカウントを使うため、自分のアカウントがなくても追加できます。",+ "search_other": "{{count}} 個のアプリを検索",+ "search_label": "アプリを検索",+ "curated": "厳選",+ "recommended_team": "通常はチームアカウント",+ "recommended_personal": "通常は個人アカウント",+ "team_connected": "チームアカウント接続済み",+ "add": "追加",+ "add_aria": "{{app}} を追加",+ "empty": "一致するアプリはありません。",+ "load_failed": "アプリを読み込めませんでした。",+ "added_toast": "{{app}} を {{agent}} に追加しました。"+ },+ "app_requests": {+ "title_adds_app": "{{agent}} が {{app}} を使おうとしています",+ "new_app": "このエージェントの新しいアプリ",+ "adds_app_note": "応答すると、今後の実行で {{agent}} が {{app}} を使えるようになります。",+ "add_to_agent": "{{app}} を {{agent}} に追加"}}diff --git a/packages/views/locales/ja/inbox.json b/packages/views/locales/ja/inbox.jsonindex c404406990..78adf4c491 100644--- a/packages/views/locales/ja/inbox.json+++ b/packages/views/locales/ja/inbox.json@@ -69,6 +69,7 @@"autopilot_quota_exceeded_body": "このワークスペースは現在の期間の自動化実行上限 {{limit}} 回に達しました。実行枠が {{resetAt}} にリセットされるか、アップグレードまたは実行回数の追加購入を行うまで、以降の自動化は開始されません。","project_owner_joined_body": "{{name}} はワークスペースのオーナーで、このプライベートプロジェクトに自分を追加しました。タスク、コメント、添付ファイルを閲覧できるようになりました。","open_project": "プロジェクトを開く",+ "open_app": "アプリを開く","autopilot_quota_upgrade": "オプションを見る","archive": "アーカイブ","unarchive": "アーカイブ解除",diff --git a/packages/views/locales/ja/layout.json b/packages/views/locales/ja/layout.jsonindex eaacc3b936..90d25fc0e2 100644--- a/packages/views/locales/ja/layout.json+++ b/packages/views/locales/ja/layout.json@@ -11,6 +11,7 @@"usage": "分析","runtimes": "ランタイム","skills": "スキル",+ "apps": "アプリ","settings": "設定","views": "ビュー","docs": "ドキュメント"@@ -23,6 +24,7 @@"member": "メンバー","squad": "スクワッド","skill": "スキル",+ "app": "アプリ","machine": "マシン","runtime": "ランタイム","attachment": "添付ファイル",diff --git a/packages/views/locales/ja/settings.json b/packages/views/locales/ja/settings.jsonindex bec92aa0c0..102ac8ffac 100644--- a/packages/views/locales/ja/settings.json+++ b/packages/views/locales/ja/settings.json@@ -595,7 +595,6 @@"billing": "請求とプラン","code": "コード","channels": "メッセージング",- "apps": "接続済みアプリ","workflows": "ワークフロー","voice_input": "音声入力"},@@ -1743,6 +1742,7 @@"layout": {"scope": {"account": "アカウント · 全デバイスで同期",+ "all_workspaces": "すべてのワークスペース","device": "このデバイスのみ","device_workspace": "このデバイスのみ · {{name}}","workspace": "{{name}} ワークスペース",@@ -1832,21 +1832,8 @@"authorization_expired": "WeChatの認証が失効しました。もう一度スキャンして接続してください。"},"connected_apps": {- "description": "エージェントが外部アプリを操作するアカウントです。許可された操作はすぐに実行されます。","loading": "アプリを読み込み中…","load_failed": "アプリを読み込めませんでした。",- "team_title": "チームアカウント",- "team_description": "サポート用メールや会社の GitHub など、ワークスペースが所有する共有アカウントです。管理者が接続し、チームアカウントを付与されたエージェントはその名義で操作します。",- "team_empty": "チームアカウントはまだありません。",- "team_empty_member": "チームアカウントはまだありません。ワークスペース管理者に接続を依頼してください。",- "personal_title": "自分のアカウント",- "personal_description": "あなた自身のアカウントです。あなたが起動した実行では、「起動した人のアカウント」に設定されたアプリがこれを使います。",- "personal_empty": "まだアカウントを接続していません。",- "connected_by": "{{name}} が接続",- "last_used": "最終使用 {{when}}",- "last_used_never": "未使用",- "used_by_other": "{{count}} 個のエージェントが使用",- "expired": "再接続が必要","reconnect": "再接続","rules": "ルール","activity": "アクティビティ",@@ -1862,35 +1849,7 @@"toast_disconnected": "接続を解除しました","toast_failed": "問題が発生しました。もう一度お試しください。","add": {- "search": "アプリを検索…",- "empty": "一致するアプリはありません。",- "curated": "厳選",- "recommended_team": "通常はチームアカウント",- "recommended_personal": "通常は個人アカウント",- "connect_team": "チームアカウントを接続",- "connect_personal": "自分のアカウントを接続",- "connecting": "接続中…",- "connected": "接続済み",- "connect": "接続",- "team_description": "ワークスペース共有のアカウントを接続します。利用するエージェントは、各エージェントの「アプリ」で設定します。",- "personal_description": "自分が実行を開始したときに、自分自身の連携アカウントを使用します。"- },- "disconnect_team": {- "title": "チームの {{app}} アカウントの接続を解除しますか?",- "description": "チームアカウントを使うエージェントはすぐにアクセスできなくなります。",- "agents": "使用中のエージェント",- "no_agents": "使用しているエージェントはありません。",- "active_tasks": "実行中: {{count}}",- "active_autopilots": "有効なオートパイロット: {{count}}",- "pending": "取り消される確認待ち: {{count}}",- "cancel": "キャンセル",- "confirm": "接続を解除"- },- "disconnect_personal": {- "title": "あなたの {{app}} アカウントの接続を解除しますか?",- "description": "あなたが起動した実行では使えなくなります。後で再接続できます。",- "cancel": "キャンセル",- "confirm": "接続を解除"+ "empty": "一致するアプリはありません。"},"detail": {"team_title": "{{app}} · チームアカウント",@@ -1941,6 +1900,36 @@"team": "チームアカウント","personal": "開始者のアカウント"},+ "status": {+ "connected": "接続済み",+ "not_connected": "未接続",+ "needs_reconnecting": "再接続が必要",+ "requested": "依頼済み"+ },+ "owner": {+ "team": "チームアカウント",+ "personal": "あなたのアカウント"+ },+ "account_row": {+ "admins_notified": "管理者に通知済み",+ "withdraw": "取り下げる",+ "decline": "却下",+ "toast_declined": "依頼を却下しました。待機中のエージェントはこのアカウントなしで続行します。",+ "toast_withdrawn": "依頼を取り下げました"+ },+ "disclosure": {+ "title": "{{app}} を接続",+ "personal_subtitle": "自分のアカウントです。次の画面でアプリにログインします。",+ "team_subtitle": "ワークスペース全体で共有するチームアカウントです。次の画面でアプリにログインします。",+ "without_asking": "エージェントが毎回確認せずに実行できること",+ "logged": "エージェントの呼び出しはすべて、実行元のタスクまたはチャットに記録されます。",+ "used_by": "{{agents}} が {{app}} を使用しており、このアカウントとして操作します。",+ "used_by_none": "このアプリを使用しているエージェントはまだありません。エージェントのページから追加できます。",+ "visibility_personal": "自分が開始した実行でのみ使われます。他のワークスペースでも使えます。",+ "visibility_team": "チームアカウントを割り当てられたエージェントは、誰が実行を開始してもこのアカウントとして操作します。",+ "cancel": "キャンセル",+ "continue": "続ける"+ },"levels": {"read": "読み取りのみ","confirm_writes": "書き込み前に確認",@@ -1976,7 +1965,13 @@"connected_resumed": "{{app}} を接続しました。エージェントは中断したところから再開します。","rate_limited": "このアカウントは 1 分あたりの呼び出し上限に達しました。1 分後にもう一度承認してください。","rate_limited_some_other": "{{count}} 件のリクエストが 1 分あたりの上限に達しました。1 分後にもう一度承認してください。",- "withdrawn": "このエージェントを使えなくなったため、リクエストは取り下げられました。"+ "withdrawn": "このエージェントを使えなくなったため、リクエストは取り下げられました。",+ "title_connect_team": "{{agent}} は {{app}} のアカウントが必要です",+ "title_member_ask": "{{name}} が {{app}} のチームアカウントを依頼しました",+ "waiting_for_admin": "管理者を待っています",+ "team_note": "チームアカウントとして動くすべてのエージェントが使えるようになります。",+ "admins_notified": "ワークスペースの管理者に受信トレイで通知しました。",+ "connect_team": "チーム用に接続"},"tools": {"tab": "ツール",@@ -2010,6 +2005,94 @@"cancel": "キャンセル","admin_required": "ワークスペース管理者が制限を解除できます。","account_link": "このアカウントには保存済みの操作制限があります。接続済みアプリで解除してください。"+ },+ "hub": {+ "description": "{{workspace}} のエージェントが使えるすべてのアプリと、使用するアカウント。",+ "tabs": {+ "in_use": "使用中",+ "attention": "要対応",+ "accounts": "アカウント",+ "all": "すべてのアプリ"+ },+ "search": "アプリを検索",+ "popular": "{{workspace}} で人気",+ "scope_team": "チームアカウント",+ "scope_personal": "個人アカウント",+ "scope_both": "チームと個人のアカウント",+ "used_by": "{{agents}} が使用中",+ "wanted_by": "{{agents}} が使用を希望",+ "asked_by": "{{names}} が依頼",+ "members_asked_other": "{{count}} 人のメンバーが依頼",+ "set_up": "設定",+ "connect": "接続",+ "reconnect": "再接続",+ "ask_admin": "管理者に依頼",+ "toast_requested": "ワークスペース管理者に {{app}} の接続を依頼しました。",+ "empty_in_use": "使用中のアプリはまだありません。アプリを設定すると、エージェントが使えるようになります。",+ "empty_attention": "対応が必要なものはありません。",+ "no_matches": "検索に一致するアプリはありません。",+ "unavailable": "このサーバーではアプリを利用できません。",+ "retry": "再試行"+ },+ "app_page": {+ "agents_title": "エージェント",+ "agents_empty": "このワークスペースにはまだエージェントがいません。",+ "source_label": "{{agent}} が {{app}} で使うアカウント",+ "source_team": "チームアカウント",+ "source_personal": "実行を開始した人",+ "not_using": "{{app}} を使用しない",+ "enable": "{{agent}} に {{app}} の使用を許可",+ "team_admin_only": "チームアカウントのアクセスを変更できるのはワークスペース管理者のみです。",+ "save_failed": "エージェントを更新できませんでした。",+ "activity_title": "最近のアクティビティ",+ "activity_empty": "まだ {{app}} を使用したエージェントはありません。",+ "as_team": "チームアカウントとして",+ "as_you": "あなたとして",+ "in_chat": "チャット",+ "accounts_title": "アカウント",+ "account_actions": "{{account}}の操作",+ "capabilities_title": "エージェントができること",+ "capabilities_note": "毎回確認せずに実行できます。",+ "accounts_description": "{{workspace}} でエージェントが使える {{app}} のアカウント。",+ "team_account_hint": "{{workspace}} の全員で共有 · 管理者が接続",+ "your_account_hint": "あなたが開始した実行でのみ使用",+ "agents_description": "エージェントごとに、どのアカウントとして動くかを選びます。",+ "ready_team": "チームアカウントで利用可能",+ "needs_team": "チームアカウントが必要",+ "ready_yours": "あなたのアカウントで利用可能",+ "needs_yours": "あなたのアカウントが必要"+ },+ "accounts_page": {+ "empty": "このワークスペースではまだアカウントを接続していません。",+ "used_by": "{{agents}} が使用",+ "team_title": "チームアカウント",+ "team_description_admin": "ワークスペースの全員で共有します。接続できるのは管理者だけです。",+ "team_description_member": "管理者が接続します。閲覧と依頼ができます。",+ "team_empty": "チームアカウントはまだありません。",+ "yours_title": "あなたのアカウント",+ "yours_description": "使えるのはあなただけです。エージェントはあなたが開始した実行で使います。",+ "needed_by": "{{agents}} が必要としています"+ },+ "disconnect_dialog": {+ "title": "{{app}} の接続を解除しますか?",+ "team_body": "これらのエージェントはこのアカウントとして動きます。次に {{app}} を使う時点で、作業せずに管理者へ依頼します。",+ "personal_body": "これらのエージェントは、あなたが開始した実行でこのアカウントを使います。次に実行を開始すると、再接続を求められます。",+ "agents": "使用しているエージェント",+ "no_agents": "使用しているエージェントはありません。",+ "running": "実行中 — 停止します",+ "active_runs_other": "実行中の {{count}} 件が今すぐ停止します。",+ "impact_failed": "使用しているエージェントを確認できませんでした。",+ "cancel": "キャンセル",+ "confirm": "接続を解除"+ },+ "team_requests": {+ "title": "{{app}} のチームアカウントが必要です",+ "run_waiting": "実行が待機中",+ "asked": "依頼",+ "summary": " · 「{{summary}}」",+ "resumes": "一度接続すればここにある依頼すべてに対応でき、待機中の実行は止まったところから再開します。",+ "decline_all": "すべて却下",+ "open_app": "アプリを開く"}},"voice_input": {diff --git a/packages/views/locales/ko/agents.json b/packages/views/locales/ko/agents.jsonindex f5053287c1..74c44b6ae1 100644--- a/packages/views/locales/ko/agents.json+++ b/packages/views/locales/ko/agents.json@@ -211,7 +211,12 @@"status": "상태","runs_7d": "실행 (7일)","edit_access_aria": "접근 권한: {{value}}. 접근 권한 변경",- "all_settings": "모든 설정"+ "all_settings": "모든 설정",+ "apps": "앱",+ "apps_needs_account_other": "{{count}}개에 내 계정 필요",+ "apps_count_other": "앱 {{count}}개",+ "apps_none": "없음",+ "apps_aria": "앱: {{value}}. 앱 보기"},"pickers": {"concurrency_range": "최대 동시 실행 수({{min}}-{{max}})",@@ -645,13 +650,9 @@"load_failed": "이 에이전트의 앱을 불러오지 못했습니다.","empty": "연결된 앱이 없습니다.","level": "계정 범위",- "team_connected": "팀 계정 연결됨",- "team_missing": "팀 계정 미연결",- "personal_connected": "내 계정 연결됨",- "personal_missing": "이 앱을 아직 연결하지 않았습니다","team_admin_only": "에이전트에 팀 계정을 부여할 수 있는 사람은 워크스페이스 관리자뿐입니다.","team_shared_warning": "이 에이전트를 실행할 수 있는 사람은 누구나 이 팀 계정으로 작업할 수 있습니다.",- "manage_link": "설정 → 연결된 앱에서 계정 관리",+ "manage_link": "앱 → 계정에서 계정 관리","save_failed_toast": "저장하지 못했습니다. 다시 시도하세요","team_help": "관리자가 연결하는 워크스페이스 공용 계정입니다.","personal_help": "실행을 시작한 사람의 계정을 사용합니다. 각자 계정을 연결해야 합니다.",@@ -1071,5 +1072,35 @@"comment": "수정했습니다. 375px 이하에서 요금 카드가 한 열로 바뀝니다. PR을 열었고 테스트도 통과했습니다.","step_read": "{{file}} 읽기"}+ },+ "apps_section": {+ "title": "앱",+ "empty": "이 에이전트는 아직 앱을 사용하지 않습니다.",+ "connect_yours": "내 계정 연결",+ "reconnect": "다시 연결",+ "connect_team": "팀 계정 연결",+ "acts_as_team": "팀 계정으로 동작",+ "acts_as_starter": "실행을 시작한 사람의 계정으로 동작"+ },+ "add_app_dialog": {+ "title": "{{agent}}에 앱 추가",+ "description": "개인 계정 앱은 에이전트를 시작한 사람의 계정을 사용하므로, 내 계정이 없어도 추가할 수 있습니다.",+ "search_other": "앱 {{count}}개 검색",+ "search_label": "앱 검색",+ "curated": "엄선",+ "recommended_team": "보통 팀 계정",+ "recommended_personal": "보통 개인 계정",+ "team_connected": "팀 계정 연결됨",+ "add": "추가",+ "add_aria": "{{app}} 추가",+ "empty": "일치하는 앱이 없습니다.",+ "load_failed": "앱을 불러오지 못했습니다.",+ "added_toast": "{{agent}}에 {{app}}을(를) 추가했습니다."+ },+ "app_requests": {+ "title_adds_app": "{{agent}}이(가) {{app}} 사용을 요청합니다",+ "new_app": "이 에이전트의 새 앱",+ "adds_app_note": "응답하면 이후 실행부터 {{agent}}이(가) {{app}}을(를) 사용할 수 있습니다.",+ "add_to_agent": "{{agent}}에 {{app}} 추가"}}diff --git a/packages/views/locales/ko/inbox.json b/packages/views/locales/ko/inbox.jsonindex 317b996c6e..4b005a04b9 100644--- a/packages/views/locales/ko/inbox.json+++ b/packages/views/locales/ko/inbox.json@@ -69,6 +69,7 @@"autopilot_quota_exceeded_body": "이 워크스페이스는 현재 기간의 오토파일럿 실행 한도 {{limit}}회에 도달했습니다. 한도가 {{resetAt}}에 초기화되거나 업그레이드 또는 실행 횟수를 추가 구매할 때까지 이후 오토파일럿 실행은 시작되지 않습니다.","project_owner_joined_body": "{{name}} 님은 워크스페이스 소유자이며 이 비공개 프로젝트에 자신을 추가했습니다. 이제 태스크, 댓글, 첨부 파일을 볼 수 있습니다.","open_project": "프로젝트 열기",+ "open_app": "앱 열기","autopilot_quota_upgrade": "옵션 보기","archive": "보관","unarchive": "보관 해제",diff --git a/packages/views/locales/ko/layout.json b/packages/views/locales/ko/layout.jsonindex f4e17a88b2..0dfbf79232 100644--- a/packages/views/locales/ko/layout.json+++ b/packages/views/locales/ko/layout.json@@ -11,6 +11,7 @@"usage": "분석","runtimes": "런타임","skills": "스킬",+ "apps": "앱","settings": "설정","views": "뷰","docs": "문서"@@ -23,6 +24,7 @@"member": "멤버","squad": "스쿼드","skill": "스킬",+ "app": "앱","machine": "머신","runtime": "런타임","attachment": "첨부파일",diff --git a/packages/views/locales/ko/settings.json b/packages/views/locales/ko/settings.jsonindex e487409bc0..7c279b8b08 100644--- a/packages/views/locales/ko/settings.json+++ b/packages/views/locales/ko/settings.json@@ -595,7 +595,6 @@"billing": "결제 및 요금제","code": "코드","channels": "메신저",- "apps": "연결된 앱","workflows": "워크플로","voice_input": "음성 입력"},@@ -1743,6 +1742,7 @@"layout": {"scope": {"account": "계정 · 모든 기기에 동기화",+ "all_workspaces": "내 모든 워크스페이스","device": "이 기기에만","device_workspace": "이 기기에만 · {{name}}","workspace": "{{name}} 워크스페이스",@@ -1832,21 +1832,8 @@"authorization_expired": "WeChat 인증이 만료되었습니다. 다시 스캔하여 연결하세요."},"connected_apps": {- "description": "에이전트가 외부 앱을 사용할 때 쓰는 계정입니다. 허용된 작업은 즉시 실행됩니다.","loading": "앱을 불러오는 중…","load_failed": "앱을 불러오지 못했습니다.",- "team_title": "팀 계정",- "team_description": "고객 지원 메일함이나 회사 GitHub처럼 워크스페이스가 소유한 공유 계정입니다. 관리자가 연결하며, 팀 계정을 받은 에이전트는 그 계정으로 작업합니다.",- "team_empty": "아직 팀 계정이 없습니다.",- "team_empty_member": "아직 팀 계정이 없습니다. 워크스페이스 관리자에게 연결을 요청하세요.",- "personal_title": "내 계정",- "personal_description": "내 계정입니다. 내가 실행을 시작하면 '실행한 사람의 계정'으로 설정된 앱이 이 계정을 사용합니다.",- "personal_empty": "아직 연결한 계정이 없습니다.",- "connected_by": "{{name}} 님이 연결",- "last_used": "마지막 사용 {{when}}",- "last_used_never": "사용한 적 없음",- "used_by_other": "에이전트 {{count}}개가 사용 중",- "expired": "다시 연결 필요","reconnect": "다시 연결","rules": "규칙","activity": "활동",@@ -1862,35 +1849,7 @@"toast_disconnected": "연결이 해제되었습니다","toast_failed": "문제가 발생했습니다. 다시 시도하세요.","add": {- "search": "앱 검색…",- "empty": "일치하는 앱이 없습니다.",- "curated": "엄선",- "recommended_team": "보통 팀 계정",- "recommended_personal": "보통 개인 계정",- "connect_team": "팀 계정 연결",- "connect_personal": "내 계정 연결",- "connecting": "연결 중…",- "connected": "연결됨",- "connect": "연결",- "team_description": "워크스페이스 공용 계정을 연결합니다. 사용할 에이전트는 각 에이전트의 앱 페이지에서 설정합니다.",- "personal_description": "실행을 시작할 때 직접 연결한 계정을 사용합니다."- },- "disconnect_team": {- "title": "팀 {{app}} 계정 연결을 해제할까요?",- "description": "팀 계정을 쓰는 에이전트는 즉시 접근 권한을 잃습니다.",- "agents": "사용 중인 에이전트",- "no_agents": "사용 중인 에이전트가 없습니다.",- "active_tasks": "진행 중인 실행: {{count}}",- "active_autopilots": "활성 오토파일럿: {{count}}",- "pending": "취소될 확인 요청: {{count}}",- "cancel": "취소",- "confirm": "연결 해제"- },- "disconnect_personal": {- "title": "내 {{app}} 계정 연결을 해제할까요?",- "description": "내가 시작한 실행에서 더 이상 사용할 수 없습니다. 나중에 다시 연결할 수 있습니다.",- "cancel": "취소",- "confirm": "연결 해제"+ "empty": "일치하는 앱이 없습니다."},"detail": {"team_title": "{{app}} · 팀 계정",@@ -1941,6 +1900,36 @@"team": "팀 계정","personal": "실행 시작자의 계정"},+ "status": {+ "connected": "연결됨",+ "not_connected": "연결 안 됨",+ "needs_reconnecting": "다시 연결 필요",+ "requested": "요청됨"+ },+ "owner": {+ "team": "팀 계정",+ "personal": "내 계정"+ },+ "account_row": {+ "admins_notified": "관리자에게 알림",+ "withdraw": "철회",+ "decline": "거절",+ "toast_declined": "요청을 거절했습니다. 기다리던 에이전트는 이 계정 없이 계속합니다.",+ "toast_withdrawn": "요청을 철회했습니다"+ },+ "disclosure": {+ "title": "{{app}} 연결",+ "personal_subtitle": "내 계정입니다. 다음 화면에서 앱에 로그인합니다.",+ "team_subtitle": "워크스페이스 전체가 공유하는 팀 계정입니다. 다음 화면에서 앱에 로그인합니다.",+ "without_asking": "에이전트가 매번 묻지 않고 할 수 있는 작업",+ "logged": "에이전트의 모든 호출은 해당 태스크나 채팅에 기록됩니다.",+ "used_by": "{{agents}}이(가) {{app}}을(를) 사용하며 이 계정으로 작업합니다.",+ "used_by_none": "아직 이 앱을 사용하는 에이전트가 없습니다. 에이전트 페이지에서 추가하세요.",+ "visibility_personal": "내가 시작한 실행에서만 사용됩니다. 내 다른 워크스페이스에서도 사용할 수 있습니다.",+ "visibility_team": "팀 계정을 부여받은 에이전트는 누가 실행을 시작하든 이 계정으로 작업합니다.",+ "cancel": "취소",+ "continue": "계속"+ },"levels": {"read": "읽기 전용","confirm_writes": "쓰기 전 확인",@@ -1976,7 +1965,13 @@"connected_resumed": "{{app}} 연결됨. 에이전트가 멈춘 곳부터 이어서 진행합니다.","rate_limited": "이 계정이 분당 호출 한도에 도달했습니다. 1분 후에 다시 승인하세요.","rate_limited_some_other": "요청 {{count}}개가 분당 한도에 걸렸습니다. 1분 후에 다시 승인하세요.",- "withdrawn": "이 에이전트를 더 이상 사용할 수 없어 요청이 철회되었습니다."+ "withdrawn": "이 에이전트를 더 이상 사용할 수 없어 요청이 철회되었습니다.",+ "title_connect_team": "{{agent}}에 {{app}} 계정이 필요합니다",+ "title_member_ask": "{{name}} 님이 {{app}} 팀 계정을 요청했습니다",+ "waiting_for_admin": "관리자를 기다리는 중",+ "team_note": "팀 계정으로 동작하는 모든 에이전트가 사용할 수 있습니다.",+ "admins_notified": "워크스페이스 관리자에게 받은 편지함으로 알렸습니다.",+ "connect_team": "팀용으로 연결"},"tools": {"tab": "도구",@@ -2010,6 +2005,94 @@"cancel": "취소","admin_required": "워크스페이스 관리자가 제한을 해제할 수 있습니다.","account_link": "이 계정에 저장된 작업 제한이 있습니다. 연결된 앱에서 해제하세요."+ },+ "hub": {+ "description": "{{workspace}}의 에이전트가 사용할 수 있는 모든 앱과 각 앱에서 사용하는 계정입니다.",+ "tabs": {+ "in_use": "사용 중",+ "attention": "확인 필요",+ "accounts": "계정",+ "all": "모든 앱"+ },+ "search": "앱 검색",+ "popular": "{{workspace}}에서 인기",+ "scope_team": "팀 계정",+ "scope_personal": "개인 계정",+ "scope_both": "팀 계정 및 개인 계정",+ "used_by": "{{agents}} 사용 중",+ "wanted_by": "{{agents}}이(가) 사용 희망",+ "asked_by": "{{names}}의 요청",+ "members_asked_other": "멤버 {{count}}명이 요청함",+ "set_up": "설정",+ "connect": "연결",+ "reconnect": "다시 연결",+ "ask_admin": "관리자에게 요청",+ "toast_requested": "워크스페이스 관리자에게 {{app}} 연결을 요청했습니다.",+ "empty_in_use": "아직 사용 중인 앱이 없습니다. 앱을 설정하면 에이전트가 사용할 수 있습니다.",+ "empty_attention": "확인할 항목이 없습니다.",+ "no_matches": "검색과 일치하는 앱이 없습니다.",+ "unavailable": "이 서버에서는 앱을 사용할 수 없습니다.",+ "retry": "다시 시도"+ },+ "app_page": {+ "agents_title": "에이전트",+ "agents_empty": "이 워크스페이스에 아직 에이전트가 없습니다.",+ "source_label": "{{agent}}이(가) {{app}}에 사용하는 계정",+ "source_team": "팀 계정",+ "source_personal": "실행을 시작한 사람",+ "not_using": "{{app}} 사용 안 함",+ "enable": "{{agent}}이(가) {{app}}을(를) 사용하도록 허용",+ "team_admin_only": "팀 계정 접근 권한은 워크스페이스 관리자만 변경할 수 있습니다.",+ "save_failed": "에이전트를 업데이트하지 못했습니다.",+ "activity_title": "최근 활동",+ "activity_empty": "아직 {{app}}을(를) 사용한 에이전트가 없습니다.",+ "as_team": "팀 계정으로",+ "as_you": "내 계정으로",+ "in_chat": "채팅",+ "accounts_title": "계정",+ "account_actions": "{{account}} 작업",+ "capabilities_title": "에이전트가 할 수 있는 작업",+ "capabilities_note": "매번 묻지 않고 실행합니다.",+ "accounts_description": "{{workspace}}에서 에이전트가 사용할 수 있는 {{app}} 계정입니다.",+ "team_account_hint": "{{workspace}} 전체가 공유 · 관리자가 연결",+ "your_account_hint": "내가 시작한 실행에서만 사용",+ "agents_description": "에이전트마다 어떤 계정으로 동작할지 고릅니다.",+ "ready_team": "팀 계정으로 사용 가능",+ "needs_team": "팀 계정 필요",+ "ready_yours": "내 계정으로 사용 가능",+ "needs_yours": "내 계정 필요"+ },+ "accounts_page": {+ "empty": "이 워크스페이스에서 연결한 계정이 없습니다.",+ "used_by": "{{agents}} 사용 중",+ "team_title": "팀 계정",+ "team_description_admin": "워크스페이스 전체가 공유합니다. 관리자만 연결할 수 있습니다.",+ "team_description_member": "관리자가 연결합니다. 확인하고 요청할 수 있습니다.",+ "team_empty": "아직 팀 계정이 없습니다.",+ "yours_title": "내 계정",+ "yours_description": "나만 사용할 수 있으며, 에이전트는 내가 시작한 실행에서 사용합니다.",+ "needed_by": "{{agents}}에 필요"+ },+ "disconnect_dialog": {+ "title": "{{app}} 연결을 해제할까요?",+ "team_body": "이 에이전트들은 이 계정으로 동작합니다. 다음 {{app}} 작업에서는 일하는 대신 관리자에게 요청합니다.",+ "personal_body": "이 에이전트들은 내가 시작한 실행에서 이 계정을 씁니다. 다음에 실행을 시작하면 다시 연결하라고 요청합니다.",+ "agents": "사용 중인 에이전트",+ "no_agents": "사용 중인 에이전트가 없습니다.",+ "running": "실행 중 — 중지됩니다",+ "active_runs_other": "진행 중인 실행 {{count}}개가 지금 중지됩니다.",+ "impact_failed": "사용 중인 에이전트를 확인하지 못했습니다.",+ "cancel": "취소",+ "confirm": "연결 해제"+ },+ "team_requests": {+ "title": "{{app}} 팀 계정이 필요합니다",+ "run_waiting": "실행 대기 중",+ "asked": "요청함",+ "summary": " · “{{summary}}”",+ "resumes": "한 번 연결하면 여기 있는 모든 요청이 해결되고, 대기 중인 실행은 멈춘 곳에서 이어집니다.",+ "decline_all": "모두 거절",+ "open_app": "앱 열기"}},"voice_input": {diff --git a/packages/views/locales/ru/agents.json b/packages/views/locales/ru/agents.jsonindex 25f5a888d1..3f9d768c04 100644--- a/packages/views/locales/ru/agents.json+++ b/packages/views/locales/ru/agents.json@@ -247,7 +247,18 @@"status": "Статус","runs_7d": "Запуски за 7 дней","edit_access_aria": "Доступ: {{value}}. Изменить доступ",- "all_settings": "Все настройки"+ "all_settings": "Все настройки",+ "apps": "Приложения",+ "apps_needs_account_one": "{{count}} требует вашего аккаунта",+ "apps_needs_account_few": "{{count}} требуют вашего аккаунта",+ "apps_needs_account_many": "{{count}} требуют вашего аккаунта",+ "apps_needs_account_other": "{{count}} требуют вашего аккаунта",+ "apps_count_one": "{{count}} приложение",+ "apps_count_few": "{{count}} приложения",+ "apps_count_many": "{{count}} приложений",+ "apps_count_other": "{{count}} приложения",+ "apps_none": "Нет",+ "apps_aria": "Приложения: {{value}}. Показать приложения"},"pickers": {"concurrency_range": "Максимум одновременных запусков ({{min}}–{{max}})",@@ -852,13 +863,9 @@"load_failed": "Не удалось загрузить приложения этого агента.","empty": "Нет доступных подключённых приложений.","level": "Область действия аккаунта",- "team_connected": "Аккаунт команды подключён",- "team_missing": "Аккаунт команды не подключён",- "personal_connected": "Ваш аккаунт подключён",- "personal_missing": "Вы ещё не подключили это приложение","team_admin_only": "Только администраторы рабочего пространства могут предоставить агенту аккаунт команды.","team_shared_warning": "Любой, кто может запустить этого агента, сможет использовать через него этот командный аккаунт.",- "manage_link": "Управление аккаунтами: Настройки → Подключённые приложения",+ "manage_link": "Управление аккаунтами: Приложения → Аккаунты","save_failed_toast": "Не удалось сохранить — попробуйте ещё раз","team_help": "Общий аккаунт рабочего пространства, подключённый администратором.","personal_help": "Каждый запуск использует аккаунт того, кто его инициировал. Каждый участник должен подключить свой аккаунт.",@@ -1158,5 +1165,38 @@}},"title": "Создайте первого ИИ-коллегу"+ },+ "apps_section": {+ "title": "Приложения",+ "empty": "Этот агент пока не использует приложения.",+ "connect_yours": "Подключить свой",+ "reconnect": "Переподключить",+ "connect_team": "Подключить аккаунт команды",+ "acts_as_team": "Действует от аккаунта команды",+ "acts_as_starter": "Действует от аккаунта того, кто начал запуск"+ },+ "add_app_dialog": {+ "title": "Добавить приложение агенту {{agent}}",+ "description": "Приложение с личным аккаунтом использует аккаунт того, кто запускает агента, поэтому его можно добавить без своего аккаунта.",+ "search_one": "Поиск среди {{count}} приложения",+ "search_few": "Поиск среди {{count}} приложений",+ "search_many": "Поиск среди {{count}} приложений",+ "search_other": "Поиск среди {{count}} приложения",+ "search_label": "Поиск приложений",+ "curated": "Избранное",+ "recommended_team": "Обычно аккаунт команды",+ "recommended_personal": "Обычно личный аккаунт",+ "team_connected": "Аккаунт команды подключён",+ "add": "Добавить",+ "add_aria": "Добавить {{app}}",+ "empty": "Подходящих приложений нет.",+ "load_failed": "Не удалось загрузить приложения.",+ "added_toast": "{{app}} добавлено агенту {{agent}}."+ },+ "app_requests": {+ "title_adds_app": "{{agent}} хочет использовать {{app}}",+ "new_app": "Новое приложение для этого агента",+ "adds_app_note": "Ответ добавит {{app}} агенту {{agent}} для будущих запусков.",+ "add_to_agent": "Добавить {{app}} агенту {{agent}}"}}diff --git a/packages/views/locales/ru/inbox.json b/packages/views/locales/ru/inbox.jsonindex c63e17074d..68e3104729 100644--- a/packages/views/locales/ru/inbox.json+++ b/packages/views/locales/ru/inbox.json@@ -75,6 +75,7 @@"autopilot_quota_exceeded_body": "Рабочее пространство исчерпало лимит в {{limit}} запусков автопилота за текущий период. Новые запуски не начнутся, пока лимит не сбросится {{resetAt}}, или пока рабочее пространство не сменит тариф либо не купит дополнительные запуски.","project_owner_joined_body": "{{name}}, владелец рабочего пространства, теперь участвует в этом закрытом проекте и видит его задачи, комментарии и вложения.","open_project": "Открыть проект",+ "open_app": "Открыть приложение","autopilot_quota_upgrade": "Посмотреть варианты","archive": "Архивировать","unarchive": "Восстановить из архива",diff --git a/packages/views/locales/ru/layout.json b/packages/views/locales/ru/layout.jsonindex 42f607ef62..c161769bab 100644--- a/packages/views/locales/ru/layout.json+++ b/packages/views/locales/ru/layout.json@@ -11,6 +11,7 @@"usage": "Аналитика","runtimes": "Среды выполнения","skills": "Навыки",+ "apps": "Приложения","settings": "Настройки","views": "Представления","docs": "Документы"@@ -23,6 +24,7 @@"member": "Участник","squad": "Команда","skill": "Навык",+ "app": "Приложение","machine": "Машина","runtime": "Среда выполнения","attachment": "Вложение",diff --git a/packages/views/locales/ru/settings.json b/packages/views/locales/ru/settings.jsonindex 12fe736a28..5ac7129e74 100644--- a/packages/views/locales/ru/settings.json+++ b/packages/views/locales/ru/settings.json@@ -613,7 +613,6 @@"billing": "Оплата","code": "Код","channels": "Мессенджеры",- "apps": "Подключённые приложения","workflows": "Рабочие процессы","voice_input": "Голосовой ввод"},@@ -1791,6 +1790,7 @@"layout": {"scope": {"account": "Аккаунт · синхронизировано",+ "all_workspaces": "Все ваши рабочие пространства","device": "Только это устройство","device_workspace": "Это устройство · {{name}}","workspace": "Рабочее пространство {{name}}",@@ -1883,24 +1883,8 @@"authorization_expired": "Авторизация WeChat истекла. Отсканируйте код повторно для подключения."},"connected_apps": {- "description": "Аккаунты, через которые ваши агенты работают с внешними приложениями. Разрешённые действия выполняются сразу.","loading": "Загрузка приложений…","load_failed": "Не удалось загрузить приложения.",- "team_title": "Аккаунты команды",- "team_description": "Общие аккаунты рабочего пространства, например почта поддержки или GitHub компании. Их подключают администраторы; агенты, которым предоставлен доступ, действуют от имени этих аккаунтов.",- "team_empty": "Пока нет аккаунтов команды.",- "team_empty_member": "Пока нет аккаунтов команды. Попросите администратора рабочего пространства подключить аккаунт.",- "personal_title": "Мои аккаунты",- "personal_description": "Ваши личные аккаунты. Когда вы запускаете выполнение, агенты используют их для приложений с настройкой «Аккаунт инициатора».",- "personal_empty": "Вы ещё не подключили ни одного аккаунта.",- "connected_by": "Подключил(а) {{name}}",- "last_used": "Последнее использование: {{when}}",- "last_used_never": "Ещё не использовался",- "used_by_one": "Использует {{count}} агент",- "used_by_few": "Используют {{count}} агента",- "used_by_many": "Используют {{count}} агентов",- "used_by_other": "Используют {{count}} агента",- "expired": "Нужно переподключить","reconnect": "Переподключить","rules": "Правила","activity": "Активность",@@ -1916,35 +1900,7 @@"toast_disconnected": "Аккаунт отключён","toast_failed": "Что-то пошло не так. Попробуйте ещё раз.","add": {- "search": "Поиск приложений…",- "empty": "Подходящих приложений нет.",- "curated": "Избранное",- "recommended_team": "Обычно аккаунт команды",- "recommended_personal": "Обычно личный аккаунт",- "connect_team": "Подключить командный аккаунт",- "connect_personal": "Подключить мой аккаунт",- "connecting": "Подключение…",- "connected": "Подключено",- "connect": "Подключить",- "team_description": "Подключите общий аккаунт рабочего пространства. Доступ агентов настраивается на странице приложений каждого агента.",- "personal_description": "Использовать ваш собственный подключённый аккаунт при запуске."- },- "disconnect_team": {- "title": "Отключить аккаунт команды в {{app}}?",- "description": "Агенты, использующие аккаунт команды, сразу потеряют доступ.",- "agents": "Агенты с доступом",- "no_agents": "Ни один агент не использует этот аккаунт.",- "active_tasks": "Выполнения в процессе: {{count}}",- "active_autopilots": "Активные автоматизации: {{count}}",- "pending": "Подтверждения, которые будут отменены: {{count}}",- "cancel": "Отмена",- "confirm": "Отключить"- },- "disconnect_personal": {- "title": "Отключить ваш аккаунт в {{app}}?",- "description": "Запускаемые вами выполнения больше не смогут его использовать. Позже аккаунт можно подключить снова.",- "cancel": "Отмена",- "confirm": "Отключить"+ "empty": "Подходящих приложений нет."},"detail": {"team_title": "{{app}} · аккаунт команды",@@ -1995,6 +1951,36 @@"team": "Аккаунт команды","personal": "Аккаунт инициатора"},+ "status": {+ "connected": "Подключён",+ "not_connected": "Не подключён",+ "needs_reconnecting": "Нужно переподключить",+ "requested": "Запрошен"+ },+ "owner": {+ "team": "Аккаунт команды",+ "personal": "Ваш аккаунт"+ },+ "account_row": {+ "admins_notified": "администраторы уведомлены",+ "withdraw": "Отозвать",+ "decline": "Отклонить",+ "toast_declined": "Запросы отклонены. Ожидающие агенты продолжат без аккаунта.",+ "toast_withdrawn": "Запрос отозван"+ },+ "disclosure": {+ "title": "Подключить {{app}}",+ "personal_subtitle": "Ваш собственный аккаунт. На следующем экране вы войдёте в приложение.",+ "team_subtitle": "Аккаунт команды, общий для всего рабочего пространства. На следующем экране вы войдёте в приложение.",+ "without_asking": "Агенты могут делать это, не спрашивая каждый раз",+ "logged": "Каждый вызов агента записывается в задаче или чате, для которых он выполнялся.",+ "used_by": "Агенты, использующие {{app}}: {{agents}}. Они будут действовать от имени этого аккаунта.",+ "used_by_none": "Ни один агент пока не использует это приложение. Добавьте его агенту на странице агента.",+ "visibility_personal": "Его используют только ваши запуски. Он работает и в других ваших рабочих пространствах.",+ "visibility_team": "Агенты с аккаунтом команды действуют от его имени, кто бы ни начал запуск.",+ "cancel": "Отмена",+ "continue": "Продолжить"+ },"levels": {"read": "Только чтение","confirm_writes": "Подтверждать запись",@@ -2036,7 +2022,13 @@"rate_limited_some_few": "{{count}} запроса достигли минутного лимита. Одобрите их повторно через минуту.","rate_limited_some_many": "{{count}} запросов достигли минутного лимита. Одобрите их повторно через минуту.","rate_limited_some_other": "{{count}} запроса достигли минутного лимита. Одобрите их повторно через минуту.",- "withdrawn": "Вы больше не можете использовать этого агента, поэтому запрос отозван."+ "withdrawn": "Вы больше не можете использовать этого агента, поэтому запрос отозван.",+ "title_connect_team": "{{agent}} нужен аккаунт {{app}}",+ "title_member_ask": "{{name}} запросил аккаунт команды {{app}}",+ "waiting_for_admin": "Ждёт администратора",+ "team_note": "Им смогут пользоваться все агенты, которые действуют от аккаунта команды.",+ "admins_notified": "Администраторы рабочего пространства получили уведомление во «Входящих».",+ "connect_team": "Подключить для команды"},"tools": {"tab": "Инструменты",@@ -2076,6 +2068,100 @@"cancel": "Отмена","admin_required": "Администратор может восстановить доступ.","account_link": "У этого аккаунта сохранились ограничения. Восстановите доступ в подключённых приложениях."+ },+ "hub": {+ "description": "Все приложения, с которыми могут работать агенты в {{workspace}}, и чьи аккаунты они используют.",+ "tabs": {+ "in_use": "Используются",+ "attention": "Требуют внимания",+ "accounts": "Аккаунты",+ "all": "Все приложения"+ },+ "search": "Поиск приложений",+ "popular": "Популярные в {{workspace}}",+ "scope_team": "Аккаунт команды",+ "scope_personal": "Личный аккаунт",+ "scope_both": "Аккаунты команды и личные",+ "used_by": "Используют: {{agents}}",+ "wanted_by": "Нужно агентам: {{agents}}",+ "asked_by": "Запросили: {{names}}",+ "members_asked_one": "Запросил {{count}} участник",+ "members_asked_few": "Запросили {{count}} участника",+ "members_asked_many": "Запросили {{count}} участников",+ "members_asked_other": "Запросили {{count}} участника",+ "set_up": "Настроить",+ "connect": "Подключить",+ "reconnect": "Переподключить",+ "ask_admin": "Попросить администратора",+ "toast_requested": "Администраторы рабочего пространства получили запрос на подключение {{app}}.",+ "empty_in_use": "Пока ни одно приложение не используется. Настройте приложение, чтобы агенты могли с ним работать.",+ "empty_attention": "Ничего не требует вашего внимания.",+ "no_matches": "Нет приложений по вашему запросу.",+ "unavailable": "Приложения недоступны на этом сервере.",+ "retry": "Повторить"+ },+ "app_page": {+ "agents_title": "Агенты",+ "agents_empty": "В этом рабочем пространстве пока нет агентов.",+ "source_label": "Аккаунт, который {{agent}} использует для {{app}}",+ "source_team": "Аккаунт команды",+ "source_personal": "Тот, кто начинает запуск",+ "not_using": "Не использует {{app}}",+ "enable": "Разрешить {{agent}} использовать {{app}}",+ "team_admin_only": "Только администраторы рабочего пространства могут менять доступ к аккаунту команды.",+ "save_failed": "Не удалось обновить агента.",+ "activity_title": "Недавняя активность",+ "activity_empty": "Ни один агент ещё не использовал {{app}}.",+ "as_team": "от аккаунта команды",+ "as_you": "от вашего имени",+ "in_chat": "чат",+ "accounts_title": "Аккаунты",+ "account_actions": "Действия: {{account}}",+ "capabilities_title": "Что могут агенты",+ "capabilities_note": "Не спрашивая каждый раз.",+ "accounts_description": "Какими аккаунтами {{app}} агенты могут пользоваться в {{workspace}}.",+ "team_account_hint": "Общий для всех в {{workspace}} · подключают администраторы",+ "your_account_hint": "Используется только в запусках, которые начинаете вы",+ "agents_description": "Каждый агент выбирает, от чьего аккаунта он действует.",+ "ready_team": "Готов с аккаунтом команды",+ "needs_team": "Нужен аккаунт команды",+ "ready_yours": "Готов с вашим аккаунтом",+ "needs_yours": "Нужен ваш аккаунт"+ },+ "accounts_page": {+ "empty": "Вы не подключили ни одного аккаунта в этом рабочем пространстве.",+ "used_by": "использует {{agents}}",+ "team_title": "Аккаунты команды",+ "team_description_admin": "Общие для всего рабочего пространства. Подключают только администраторы.",+ "team_description_member": "Их подключают администраторы. Вы можете их видеть и запросить нужный.",+ "team_empty": "Аккаунтов команды пока нет.",+ "yours_title": "Ваши аккаунты",+ "yours_description": "Пользоваться ими можете только вы; агенты используют их в запусках, которые начинаете вы.",+ "needed_by": "нужен агенту {{agents}}"+ },+ "disconnect_dialog": {+ "title": "Отключить {{app}}?",+ "team_body": "Эти агенты действуют от этого аккаунта. На следующем шаге в {{app}} они обратятся к администраторам вместо работы.",+ "personal_body": "Эти агенты используют его в запусках, которые начинаете вы. В следующем запуске вас попросят подключить его снова.",+ "agents": "Агенты, которые им пользуются",+ "no_agents": "Ни один агент им не пользуется.",+ "running": "Идёт запуск — он остановится",+ "active_runs_one": "Сейчас остановится {{count}} идущий запуск.",+ "active_runs_few": "Сейчас остановятся {{count}} идущих запуска.",+ "active_runs_many": "Сейчас остановятся {{count}} идущих запусков.",+ "active_runs_other": "Сейчас остановятся {{count}} идущих запуска.",+ "impact_failed": "Не удалось проверить, какие агенты им пользуются.",+ "cancel": "Отмена",+ "confirm": "Отключить"+ },+ "team_requests": {+ "title": "Нужен аккаунт команды {{app}}",+ "run_waiting": "Запуск ждёт",+ "asked": "Запрошено",+ "summary": " · «{{summary}}»",+ "resumes": "Одно подключение отвечает на все эти запросы, а ожидающие запуски продолжат с того места, где остановились.",+ "decline_all": "Отклонить все",+ "open_app": "Открыть приложение"}},"voice_input": {diff --git a/packages/views/locales/zh-Hans/agents.json b/packages/views/locales/zh-Hans/agents.jsonindex c374ebf081..ef29c4ac1d 100644--- a/packages/views/locales/zh-Hans/agents.json+++ b/packages/views/locales/zh-Hans/agents.json@@ -211,7 +211,12 @@"status": "状态","runs_7d": "运行(7 天)","edit_access_aria": "访问权限:{{value}}。更改访问权限",- "all_settings": "全部设置"+ "all_settings": "全部设置",+ "apps": "应用",+ "apps_needs_account_other": "{{count}} 个需要你的账号",+ "apps_count_other": "{{count}} 个应用",+ "apps_none": "无",+ "apps_aria": "应用:{{value}}。查看应用"},"pickers": {"concurrency_range": "最大并行运行数({{min}}–{{max}})",@@ -786,13 +791,9 @@"load_failed": "无法加载此智能体的应用。","empty": "暂无已连接的应用。","level": "账号范围",- "team_connected": "团队账号已连接",- "team_missing": "团队账号未连接",- "personal_connected": "你的账号已连接",- "personal_missing": "你还没有连接这个应用","team_admin_only": "只有工作区管理员可以为智能体配置团队账号。","team_shared_warning": "能运行这个智能体的人,都能通过它使用该团队账号。",- "manage_link": "在 设置 → 已连接应用 中管理账号",+ "manage_link": "在 应用 → 账号 中管理账号","save_failed_toast": "保存失败,请重试","team_help": "工作区共用的账号,由管理员连接。","personal_help": "每次运行使用触发者自己已连接的账号;未连接时需先连接。",@@ -1071,5 +1072,35 @@"comment": "修好了:价格卡片在 375px 下改为单列。已开 PR,测试通过。","step_read": "读取 {{file}}"}+ },+ "apps_section": {+ "title": "应用",+ "empty": "这个智能体还没有使用任何应用。",+ "connect_yours": "连接我的账号",+ "reconnect": "重新连接",+ "connect_team": "连接团队账号",+ "acts_as_team": "以团队账号行动",+ "acts_as_starter": "以发起运行的人的账号行动"+ },+ "add_app_dialog": {+ "title": "为 {{agent}} 添加应用",+ "description": "使用个人账号的应用会用发起运行者的账号,所以即使你自己没有账号也可以添加。",+ "search_other": "搜索 {{count}} 个应用",+ "search_label": "搜索应用",+ "curated": "精选",+ "recommended_team": "通常用团队账号",+ "recommended_personal": "通常用个人账号",+ "team_connected": "团队账号已连接",+ "add": "添加",+ "add_aria": "添加 {{app}}",+ "empty": "没有匹配的应用。",+ "load_failed": "无法加载应用。",+ "added_toast": "已将 {{app}} 添加给 {{agent}}。"+ },+ "app_requests": {+ "title_adds_app": "{{agent}} 想使用 {{app}}",+ "new_app": "此智能体的新应用",+ "adds_app_note": "回应后,{{agent}} 之后的运行都可以使用 {{app}}。",+ "add_to_agent": "将 {{app}} 添加给 {{agent}}"}}diff --git a/packages/views/locales/zh-Hans/inbox.json b/packages/views/locales/zh-Hans/inbox.jsonindex bf45b3c7fc..ad6c5559f8 100644--- a/packages/views/locales/zh-Hans/inbox.json+++ b/packages/views/locales/zh-Hans/inbox.json@@ -69,6 +69,7 @@"autopilot_quota_exceeded_body": "当前周期的 {{limit}} 次自动化执行额度已用完。在 {{resetAt}} 重置、升级套餐或加购之前,后续自动化执行将不会启动。","project_owner_joined_body": "{{name}} 是工作区所有者,已把自己加入这个私有项目,现在可以看到其中的任务、评论和附件。","open_project": "打开项目",+ "open_app": "打开应用","autopilot_quota_upgrade": "查看选项","archive": "归档","unarchive": "取消归档",diff --git a/packages/views/locales/zh-Hans/layout.json b/packages/views/locales/zh-Hans/layout.jsonindex 5d5d894acd..757ddf1d31 100644--- a/packages/views/locales/zh-Hans/layout.json+++ b/packages/views/locales/zh-Hans/layout.json@@ -11,6 +11,7 @@"usage": "统计","runtimes": "运行时","skills": "Skills",+ "apps": "应用","settings": "设置","views": "视图","docs": "知识库"@@ -23,6 +24,7 @@"member": "成员","squad": "小队","skill": "Skill",+ "app": "应用","machine": "机器","runtime": "运行时","attachment": "附件",diff --git a/packages/views/locales/zh-Hans/settings.json b/packages/views/locales/zh-Hans/settings.jsonindex af9a5b1382..3bb52fcb54 100644--- a/packages/views/locales/zh-Hans/settings.json+++ b/packages/views/locales/zh-Hans/settings.json@@ -595,7 +595,6 @@"billing": "账单与套餐","code": "代码","channels": "消息渠道",- "apps": "已连接应用","workflows": "工作流","voice_input": "语音输入"},@@ -1743,6 +1742,7 @@"layout": {"scope": {"account": "账号 · 所有设备同步",+ "all_workspaces": "你的所有工作区","device": "仅本设备","device_workspace": "仅本设备 · {{name}}","workspace": "{{name}} 工作区",@@ -1832,21 +1832,8 @@"authorization_expired": "微信授权已过期,请重新扫码连接。"},"connected_apps": {- "description": "智能体通过这些账号操作外部应用,允许的操作会直接执行。","loading": "正在加载应用...","load_failed": "无法加载应用。",- "team_title": "团队账号",- "team_description": "工作区共有的账号,例如客服邮箱或公司 GitHub。由管理员连接;被授予团队账号的智能体以该账号身份操作。",- "team_empty": "还没有团队账号。",- "team_empty_member": "还没有团队账号。请联系工作区管理员连接。",- "personal_title": "我的账号",- "personal_description": "你自己的账号。由你触发的运行中,设为\"触发者账号\"的应用会使用这些账号。",- "personal_empty": "你还没有连接任何账号。",- "connected_by": "由 {{name}} 连接",- "last_used": "最近使用 {{when}}",- "last_used_never": "尚未使用",- "used_by_other": "{{count}} 个智能体在用",- "expired": "需要重新连接","reconnect": "重新连接","rules": "规则","activity": "调用记录",@@ -1862,35 +1849,7 @@"toast_disconnected": "已断开","toast_failed": "操作失败,请重试。","add": {- "search": "搜索应用...",- "empty": "没有匹配的应用。",- "curated": "精选",- "recommended_team": "通常用团队账号",- "recommended_personal": "通常用个人账号",- "connect_team": "连接团队账号",- "connect_personal": "连接我的账号",- "connecting": "正在连接...",- "connected": "已连接",- "connect": "连接",- "team_description": "连接工作区共用的账号。哪些智能体可以使用,在各智能体的\"应用\"页设置。",- "personal_description": "连接你自己的账号。应用设为\"触发者账号\"时,由你触发的运行会使用它。"- },- "disconnect_team": {- "title": "断开团队的 {{app}} 账号?",- "description": "使用团队账号的智能体会立即失去访问权限。",- "agents": "正在使用的智能体",- "no_agents": "没有智能体在用。",- "active_tasks": "进行中的运行:{{count}}",- "active_autopilots": "启用中的自动化:{{count}}",- "pending": "将被取消的待确认请求:{{count}}",- "cancel": "取消",- "confirm": "断开"- },- "disconnect_personal": {- "title": "断开你的 {{app}} 账号?",- "description": "你触发的运行将无法再使用它。之后可以重新连接。",- "cancel": "取消",- "confirm": "断开"+ "empty": "没有匹配的应用。"},"detail": {"team_title": "{{app}} · 团队账号",@@ -1976,7 +1935,13 @@"connected_resumed": "{{app}} 已连接,智能体会从中断处继续。","rate_limited": "这个账号已达到每分钟调用上限,请一分钟后再批准。","rate_limited_some_other": "有 {{count}} 个请求触发了每分钟上限,请一分钟后再批准。",- "withdrawn": "你已无法使用这个智能体,请求已撤回。"+ "withdrawn": "你已无法使用这个智能体,请求已撤回。",+ "title_connect_team": "{{agent}} 需要 {{app}} 账号",+ "title_member_ask": "{{name}} 申请了 {{app}} 团队账号",+ "waiting_for_admin": "等待管理员",+ "team_note": "所有以团队账号行动的智能体都可以使用它。",+ "admins_notified": "已在收件箱通知工作区管理员。",+ "connect_team": "为团队连接"},"tools": {"tab": "工具",@@ -2010,6 +1975,124 @@"cancel": "取消","admin_required": "请工作区管理员解除限制。","account_link": "此账号仍有旧操作限制。请在已连接应用中解除。"+ },+ "status": {+ "connected": "已连接",+ "not_connected": "未连接",+ "needs_reconnecting": "需要重新连接",+ "requested": "已请求"+ },+ "owner": {+ "team": "团队账号",+ "personal": "你的账号"+ },+ "account_row": {+ "admins_notified": "已通知管理员",+ "withdraw": "撤回",+ "decline": "拒绝",+ "toast_declined": "已拒绝请求,等待中的智能体会在没有该账号的情况下继续。",+ "toast_withdrawn": "已撤回请求"+ },+ "disclosure": {+ "title": "连接 {{app}}",+ "personal_subtitle": "你自己的账号。下一步会跳转到该应用登录。",+ "team_subtitle": "整个工作区共用的团队账号。下一步会跳转到该应用登录。",+ "without_asking": "智能体无需每次征得同意即可执行",+ "logged": "智能体的每次调用都会记录在对应的任务或聊天中。",+ "used_by": "{{agents}} 在用 {{app}},将以这个账号的身份操作。",+ "used_by_none": "还没有智能体使用这个应用。可在智能体页面把它添加给智能体。",+ "visibility_personal": "只有你发起的运行会使用它。它在你的其他工作区中同样可用。",+ "visibility_team": "被分配团队账号的智能体都以它的身份操作,无论谁发起运行。",+ "cancel": "取消",+ "continue": "继续"+ },+ "hub": {+ "description": "{{workspace}} 中智能体可以使用的所有应用,以及它们使用谁的账号。",+ "tabs": {+ "in_use": "使用中",+ "attention": "需要处理",+ "accounts": "账号",+ "all": "全部应用"+ },+ "search": "搜索应用",+ "popular": "{{workspace}} 中常用",+ "scope_team": "团队账号",+ "scope_personal": "个人账号",+ "scope_both": "团队和个人账号",+ "used_by": "{{agents}} 在用",+ "wanted_by": "{{agents}} 想用",+ "asked_by": "{{names}} 发起了请求",+ "members_asked_other": "{{count}} 位成员发起了请求",+ "set_up": "设置",+ "connect": "连接",+ "reconnect": "重新连接",+ "ask_admin": "请管理员连接",+ "toast_requested": "已请工作区管理员连接 {{app}}。",+ "empty_in_use": "还没有使用中的应用。设置一个,让智能体可以使用它。",+ "empty_attention": "没有需要你处理的事项。",+ "no_matches": "没有匹配的应用。",+ "unavailable": "此服务器未提供应用功能。",+ "retry": "重试"+ },+ "app_page": {+ "agents_title": "智能体",+ "agents_empty": "此工作区还没有智能体。",+ "source_label": "{{agent}} 使用 {{app}} 时用的账号",+ "source_team": "团队账号",+ "source_personal": "发起运行的人",+ "not_using": "不使用 {{app}}",+ "enable": "允许 {{agent}} 使用 {{app}}",+ "team_admin_only": "只有工作区管理员可以修改团队账号的使用权限。",+ "save_failed": "无法更新智能体。",+ "activity_title": "最近调用",+ "activity_empty": "还没有智能体使用过 {{app}}。",+ "as_team": "以团队账号",+ "as_you": "以你的身份",+ "in_chat": "聊天",+ "accounts_title": "账号",+ "account_actions": "{{account}}操作",+ "capabilities_title": "智能体可以做什么",+ "capabilities_note": "无需每次征得同意。",+ "accounts_description": "{{workspace}} 中智能体可以使用的 {{app}} 账号。",+ "team_account_hint": "{{workspace}} 所有人共享 · 由管理员连接",+ "your_account_hint": "只在你发起的运行中使用",+ "agents_description": "每个智能体选择以谁的账号行动。",+ "ready_team": "团队账号已就绪",+ "needs_team": "需要团队账号",+ "ready_yours": "你的账号已就绪",+ "needs_yours": "需要你的账号"+ },+ "accounts_page": {+ "empty": "你还没有在这个工作区连接任何账号。",+ "used_by": "{{agents}} 在用",+ "team_title": "团队账号",+ "team_description_admin": "整个工作区共享,只有管理员可以连接。",+ "team_description_member": "由管理员连接。你可以查看,也可以申请。",+ "team_empty": "还没有团队账号。",+ "yours_title": "你的账号",+ "yours_description": "只有你能使用;智能体会在你发起的运行中使用它们。",+ "needed_by": "{{agents}} 需要它"+ },+ "disconnect_dialog": {+ "title": "断开 {{app}}?",+ "team_body": "这些智能体以这个账号行动。下次用到 {{app}} 时,它们会向管理员发起请求,而不是继续工作。",+ "personal_body": "这些智能体会在你发起的运行中使用它。你下次发起运行时,会被要求重新连接。",+ "agents": "使用它的智能体",+ "no_agents": "没有智能体在用。",+ "running": "运行中 — 将会停止",+ "active_runs_other": "{{count}} 个进行中的运行会立即停止。",+ "impact_failed": "无法确认哪些智能体在用它。",+ "cancel": "取消",+ "confirm": "断开"+ },+ "team_requests": {+ "title": "需要 {{app}} 团队账号",+ "run_waiting": "运行等待中",+ "asked": "已申请",+ "summary": " · \"{{summary}}\"",+ "resumes": "连接一次即可回应这里的所有请求,等待中的运行会从中断处继续。",+ "decline_all": "全部拒绝",+ "open_app": "打开应用"}},"voice_input": {diff --git a/packages/views/locales/zh-Hant/agents.json b/packages/views/locales/zh-Hant/agents.jsonindex 51fd079a5b..01ecef5a3c 100644--- a/packages/views/locales/zh-Hant/agents.json+++ b/packages/views/locales/zh-Hant/agents.json@@ -211,7 +211,12 @@"status": "狀態","runs_7d": "執行(7 天)","edit_access_aria": "訪問權限:{{value}}。變更訪問權限",- "all_settings": "全部設定"+ "all_settings": "全部設定",+ "apps": "應用程式",+ "apps_needs_account_other": "{{count}} 個需要你的帳號",+ "apps_count_other": "{{count}} 個應用",+ "apps_none": "無",+ "apps_aria": "應用程式:{{value}}。查看應用程式"},"pickers": {"concurrency_range": "最大並行執行數({{min}}–{{max}})",@@ -786,13 +791,9 @@"load_failed": "無法載入此 AI 代理的應用。","empty": "尚無已連線的應用程式。","level": "帳號範圍",- "team_connected": "團隊帳號已連線",- "team_missing": "團隊帳號未連線",- "personal_connected": "你的帳號已連線",- "personal_missing": "你還沒有連線這個應用","team_admin_only": "只有工作區管理員可以給 AI 代理團隊帳號。","team_shared_warning": "能執行這個 AI 代理的人,都能透過它使用該團隊帳號。",- "manage_link": "在 設定 → 已連線應用 中管理帳號",+ "manage_link": "在 應用程式 → 帳號 中管理帳號","save_failed_toast": "儲存失敗,請重試","team_help": "工作區共用的帳號,由管理員連線。","personal_help": "每次執行使用觸發者自己已連線的帳號;尚未連線時須先連線。",@@ -1071,5 +1072,35 @@"comment": "修好了:價格卡片在 375px 下改為單欄。已開 PR,測試通過。","step_read": "讀取 {{file}}"}+ },+ "apps_section": {+ "title": "應用程式",+ "empty": "這個 AI 代理還沒有使用任何應用。",+ "connect_yours": "連線我的帳號",+ "reconnect": "重新連線",+ "connect_team": "連線團隊帳號",+ "acts_as_team": "以團隊帳號行動",+ "acts_as_starter": "以發起執行的人的帳號行動"+ },+ "add_app_dialog": {+ "title": "為 {{agent}} 新增應用",+ "description": "使用個人帳號的應用會用發起執行者的帳號,所以即使你自己沒有帳號也可以新增。",+ "search_other": "搜尋 {{count}} 個應用",+ "search_label": "搜尋應用",+ "curated": "精選",+ "recommended_team": "通常用團隊帳號",+ "recommended_personal": "通常用個人帳號",+ "team_connected": "團隊帳號已連線",+ "add": "新增",+ "add_aria": "新增 {{app}}",+ "empty": "沒有符合的應用。",+ "load_failed": "無法載入應用。",+ "added_toast": "已將 {{app}} 新增至 {{agent}}。"+ },+ "app_requests": {+ "title_adds_app": "{{agent}} 想使用 {{app}}",+ "new_app": "此 AI 代理的新應用",+ "adds_app_note": "回應後,{{agent}} 之後的執行都可以使用 {{app}}。",+ "add_to_agent": "將 {{app}} 新增至 {{agent}}"}}diff --git a/packages/views/locales/zh-Hant/inbox.json b/packages/views/locales/zh-Hant/inbox.jsonindex ce3696a613..94bd5bfbe0 100644--- a/packages/views/locales/zh-Hant/inbox.json+++ b/packages/views/locales/zh-Hant/inbox.json@@ -69,6 +69,7 @@"autopilot_quota_exceeded_body": "目前週期的 {{limit}} 次自動化執行額度已用完。在 {{resetAt}} 重置、升級方案或加購之前,後續自動化執行將不會啟動。","project_owner_joined_body": "{{name}} 是工作區所有者,已把自己加入這個私有專案,現在可以看到其中的任務、評論和附件。","open_project": "開啟專案",+ "open_app": "開啟應用程式","autopilot_quota_upgrade": "查看選項","archive": "歸檔","unarchive": "取消歸檔",diff --git a/packages/views/locales/zh-Hant/layout.json b/packages/views/locales/zh-Hant/layout.jsonindex e554f78dd1..92a813f8af 100644--- a/packages/views/locales/zh-Hant/layout.json+++ b/packages/views/locales/zh-Hant/layout.json@@ -11,6 +11,7 @@"usage": "統計","runtimes": "執行時","skills": "Skills",+ "apps": "應用程式","settings": "設定","views": "檢視","docs": "知識庫"@@ -23,6 +24,7 @@"member": "成員","squad": "小隊","skill": "Skill",+ "app": "應用程式","machine": "機器","runtime": "執行時","attachment": "附件",diff --git a/packages/views/locales/zh-Hant/settings.json b/packages/views/locales/zh-Hant/settings.jsonindex 575937da5e..f56b651af2 100644--- a/packages/views/locales/zh-Hant/settings.json+++ b/packages/views/locales/zh-Hant/settings.json@@ -595,7 +595,6 @@"billing": "帳單與套餐","code": "程式碼","channels": "訊息渠道",- "apps": "已連線應用","workflows": "工作流","voice_input": "語音輸入"},@@ -1743,6 +1742,7 @@"layout": {"scope": {"account": "帳號 · 所有裝置同步",+ "all_workspaces": "你的所有工作區","device": "僅本裝置","device_workspace": "僅本裝置 · {{name}}","workspace": "{{name}} 工作區",@@ -1832,21 +1832,8 @@"authorization_expired": "微信授權已過期,請重新掃碼連接。"},"connected_apps": {- "description": "AI 代理透過這些帳號操作外部應用,允許的操作會直接執行。","loading": "正在載入應用…","load_failed": "無法載入應用。",- "team_title": "團隊帳號",- "team_description": "工作區共有的帳號,例如客服信箱或公司 GitHub。由管理員連線;被授予團隊帳號的 AI 代理以該帳號身分操作。",- "team_empty": "還沒有團隊帳號。",- "team_empty_member": "還沒有團隊帳號。請聯絡工作區管理員連線。",- "personal_title": "我的帳號",- "personal_description": "你自己的帳號。由你觸發的執行中,設為「觸發者帳號」的應用會使用這些帳號。",- "personal_empty": "你還沒有連線任何帳號。",- "connected_by": "由 {{name}} 連線",- "last_used": "最近使用 {{when}}",- "last_used_never": "尚未使用",- "used_by_other": "{{count}} 個 AI 代理在用",- "expired": "需要重新連線","reconnect": "重新連線","rules": "規則","activity": "呼叫紀錄",@@ -1862,35 +1849,7 @@"toast_disconnected": "已中斷連線","toast_failed": "操作失敗,請重試。","add": {- "search": "搜尋應用…",- "empty": "沒有符合的應用。",- "curated": "精選",- "recommended_team": "通常用團隊帳號",- "recommended_personal": "通常用個人帳號",- "connect_team": "連線團隊帳號",- "connect_personal": "連線我的帳號",- "connecting": "正在連線…",- "connected": "已連線",- "connect": "連線",- "team_description": "連線工作區共用的帳號。哪些 AI 代理可以使用,請在各 AI 代理的「應用程式」頁設定。",- "personal_description": "當你觸發執行時,使用你自己連線的帳號。"- },- "disconnect_team": {- "title": "中斷團隊的 {{app}} 帳號?",- "description": "使用團隊帳號的 AI 代理會立即失去存取權限。",- "agents": "正在使用的 AI 代理",- "no_agents": "沒有 AI 代理在用。",- "active_tasks": "進行中的執行:{{count}}",- "active_autopilots": "啟用中的自動化:{{count}}",- "pending": "將被取消的待確認請求:{{count}}",- "cancel": "取消",- "confirm": "中斷連線"- },- "disconnect_personal": {- "title": "中斷你的 {{app}} 帳號?",- "description": "你觸發的執行將無法再使用它。之後可以重新連線。",- "cancel": "取消",- "confirm": "中斷連線"+ "empty": "沒有符合的應用。"},"detail": {"team_title": "{{app}} · 團隊帳號",@@ -1941,6 +1900,36 @@"team": "團隊帳號","personal": "觸發者的帳號"},+ "status": {+ "connected": "已連線",+ "not_connected": "未連線",+ "needs_reconnecting": "需要重新連線",+ "requested": "已請求"+ },+ "owner": {+ "team": "團隊帳號",+ "personal": "你的帳號"+ },+ "account_row": {+ "admins_notified": "已通知管理員",+ "withdraw": "撤回",+ "decline": "拒絕",+ "toast_declined": "已拒絕請求,等待中的智慧體會在沒有該帳號的情況下繼續。",+ "toast_withdrawn": "已撤回請求"+ },+ "disclosure": {+ "title": "連線 {{app}}",+ "personal_subtitle": "你自己的帳號。下一步會前往該應用登入。",+ "team_subtitle": "整個工作區共用的團隊帳號。下一步會前往該應用登入。",+ "without_asking": "AI 代理無需每次徵求同意即可執行",+ "logged": "AI 代理的每次呼叫都會記錄在對應的任務或聊天中。",+ "used_by": "{{agents}} 在用 {{app}},將以這個帳號的身分操作。",+ "used_by_none": "還沒有 AI 代理使用這個應用。可在 AI 代理頁面將它新增至 AI 代理。",+ "visibility_personal": "只有你發起的執行會使用它。它在你的其他工作區中同樣可用。",+ "visibility_team": "獲派團隊帳號的 AI 代理都以它的身分操作,無論誰發起執行。",+ "cancel": "取消",+ "continue": "繼續"+ },"levels": {"read": "唯讀","confirm_writes": "寫入前先確認",@@ -1976,7 +1965,13 @@"connected_resumed": "{{app}} 已連線,代理會從中斷處繼續。","rate_limited": "這個帳號已達到每分鐘呼叫上限,請一分鐘後再核准。","rate_limited_some_other": "有 {{count}} 個請求觸發了每分鐘上限,請一分鐘後再核准。",- "withdrawn": "你已無法使用這個代理,請求已撤回。"+ "withdrawn": "你已無法使用這個代理,請求已撤回。",+ "title_connect_team": "{{agent}} 需要 {{app}} 帳號",+ "title_member_ask": "{{name}} 申請了 {{app}} 團隊帳號",+ "waiting_for_admin": "等待管理員",+ "team_note": "所有以團隊帳號行動的智慧體都可以使用它。",+ "admins_notified": "已在收件匣通知工作區管理員。",+ "connect_team": "為團隊連線"},"tools": {"tab": "工具",@@ -2010,6 +2005,94 @@"cancel": "取消","admin_required": "請工作區管理員解除限制。","account_link": "此帳號仍有舊操作限制。請在已連接應用中解除。"+ },+ "hub": {+ "description": "{{workspace}} 中 AI 代理可以使用的所有應用,以及它們使用誰的帳號。",+ "tabs": {+ "in_use": "使用中",+ "attention": "需要處理",+ "accounts": "帳號",+ "all": "全部應用"+ },+ "search": "搜尋應用",+ "popular": "{{workspace}} 中常用",+ "scope_team": "團隊帳號",+ "scope_personal": "個人帳號",+ "scope_both": "團隊和個人帳號",+ "used_by": "{{agents}} 在用",+ "wanted_by": "{{agents}} 想用",+ "asked_by": "{{names}} 提出了請求",+ "members_asked_other": "{{count}} 位成員提出了請求",+ "set_up": "設定",+ "connect": "連線",+ "reconnect": "重新連線",+ "ask_admin": "請管理員連線",+ "toast_requested": "已請工作區管理員連線 {{app}}。",+ "empty_in_use": "還沒有使用中的應用。設定一個,讓 AI 代理可以使用它。",+ "empty_attention": "沒有需要你處理的事項。",+ "no_matches": "沒有符合的應用。",+ "unavailable": "此伺服器未提供應用功能。",+ "retry": "重試"+ },+ "app_page": {+ "agents_title": "AI 代理",+ "agents_empty": "此工作區還沒有 AI 代理。",+ "source_label": "{{agent}} 使用 {{app}} 時用的帳號",+ "source_team": "團隊帳號",+ "source_personal": "發起執行的人",+ "not_using": "不使用 {{app}}",+ "enable": "允許 {{agent}} 使用 {{app}}",+ "team_admin_only": "只有工作區管理員可以修改團隊帳號的使用權限。",+ "save_failed": "無法更新 AI 代理。",+ "activity_title": "最近呼叫",+ "activity_empty": "還沒有 AI 代理使用過 {{app}}。",+ "as_team": "以團隊帳號",+ "as_you": "以你的身分",+ "in_chat": "聊天",+ "accounts_title": "帳號",+ "account_actions": "{{account}}操作",+ "capabilities_title": "AI 代理可以做什麼",+ "capabilities_note": "無需每次徵求同意。",+ "accounts_description": "{{workspace}} 中智慧體可以使用的 {{app}} 帳號。",+ "team_account_hint": "{{workspace}} 所有人共用 · 由管理員連線",+ "your_account_hint": "只在你發起的執行中使用",+ "agents_description": "每個智慧體選擇以誰的帳號行動。",+ "ready_team": "團隊帳號已就緒",+ "needs_team": "需要團隊帳號",+ "ready_yours": "你的帳號已就緒",+ "needs_yours": "需要你的帳號"+ },+ "accounts_page": {+ "empty": "你還沒有在這個工作區連線任何帳號。",+ "used_by": "{{agents}} 在用",+ "team_title": "團隊帳號",+ "team_description_admin": "整個工作區共用,只有管理員可以連線。",+ "team_description_member": "由管理員連線。你可以查看,也可以申請。",+ "team_empty": "還沒有團隊帳號。",+ "yours_title": "你的帳號",+ "yours_description": "只有你能使用;智慧體會在你發起的執行中使用它們。",+ "needed_by": "{{agents}} 需要它"+ },+ "disconnect_dialog": {+ "title": "中斷 {{app}}?",+ "team_body": "這些智慧體以這個帳號行動。下次用到 {{app}} 時,它們會向管理員發出請求,而不是繼續工作。",+ "personal_body": "這些智慧體會在你發起的執行中使用它。你下次發起執行時,會被要求重新連線。",+ "agents": "使用它的智慧體",+ "no_agents": "沒有智慧體在用。",+ "running": "執行中 — 將會停止",+ "active_runs_other": "{{count}} 個進行中的執行會立即停止。",+ "impact_failed": "無法確認哪些智慧體在用它。",+ "cancel": "取消",+ "confirm": "中斷"+ },+ "team_requests": {+ "title": "需要 {{app}} 團隊帳號",+ "run_waiting": "執行等待中",+ "asked": "已申請",+ "summary": " · 「{{summary}}」",+ "resumes": "連線一次即可回應這裡的所有請求,等待中的執行會從中斷處繼續。",+ "decline_all": "全部拒絕",+ "open_app": "開啟應用程式"}},"voice_input": {diff --git a/packages/views/package.json b/packages/views/package.jsonindex e5c687857f..a554929e30 100644--- a/packages/views/package.json+++ b/packages/views/package.json@@ -34,6 +34,7 @@"./modals/create-issue": "./modals/create-issue.tsx","./my-issues": "./my-issues/index.ts","./skills": "./skills/index.ts",+ "./apps": "./apps/index.ts","./agents": "./agents/index.ts","./agents/agent-detail-page": "./agents/components/agent-detail-page.tsx","./agents/agents-page": "./agents/components/agents-page.tsx",diff --git a/packages/views/search/search-command.test.tsx b/packages/views/search/search-command.test.tsxindex 5d31a9f541..55913ef808 100644--- a/packages/views/search/search-command.test.tsx+++ b/packages/views/search/search-command.test.tsx@@ -172,6 +172,9 @@ vi.mock("@multica/core/auth", async (importOriginal) => {};});+const composio = vi.hoisted(() => ({ available: true }));+vi.mock("../common/use-composio-available", () => ({ useComposioAvailable: () => composio.available }));+vi.mock("@multica/core/hooks", async (importOriginal) => ({...(await importOriginal<typeof import("@multica/core/hooks")>()),useWorkspaceId: () => "ws-test",@@ -368,6 +371,7 @@ const rowText = (text: string) =>describe("SearchCommand", () => {beforeEach(() => {+ composio.available = true;queryData.clear();apiFns.clear();apiFns.set("getBaseUrl", vi.fn(() => "http://127.0.0.1:8080"));@@ -479,6 +483,17 @@ describe("SearchCommand", () => {}});+ it("leaves Apps out when the server has no connected apps", async () => {+ composio.available = false;+ const user = userEvent.setup();+ renderSearch();+ await user.type(input(), enLayout.nav.apps);+ await waitFor(() => expect(renderedValues()).not.toContain("page:apps"));+ await user.clear(input());+ await user.type(input(), enLayout.nav.skills);+ await waitFor(() => expect(renderedValues()).toContain("page:skills"));+ });+it("does not surface a page on an incidental substring of a hidden keyword", async () => {const user = userEvent.setup();renderSearch();diff --git a/packages/views/search/use-root-model.ts b/packages/views/search/use-root-model.tsindex 669523e308..2ad96645a7 100644--- a/packages/views/search/use-root-model.ts+++ b/packages/views/search/use-root-model.ts@@ -7,6 +7,7 @@ import { DOCS_V1_FLAG } from "@multica/core/feature-flags";import { WORKSPACE_PAGES, type WorkspacePageKey } from "@multica/core/paths";import { partitionAggregatedSearchResults } from "@multica/core/search/cancelled-rank";import type { SearchDocResult, SearchIssueResult, SearchProjectResult } from "@multica/core/types";+import { useComposioAvailable } from "../common/use-composio-available";import { useT } from "../i18n";import { useAgentCommandGroup, useAutopilotCommandGroup, useChatCommandGroup, useInboxCommandGroup, useProjectCommandGroup } from "./commands/context-commands";import { useGlobalCommands } from "./commands/global-commands";@@ -47,6 +48,7 @@ const PAGE_KEYWORDS: Record<WorkspacePageKey, string[]> = {runtimes: ["runtimes", "environments", "machines", "运行时"],docs: ["docs", "knowledge", "知识库"],skills: ["skills", "library", "技能"],+ apps: ["apps", "integrations", "connected", "accounts", "composio", "应用", "集成"],settings: ["settings", "config", "preferences", "设置", "配置"],};@@ -195,14 +197,15 @@ export function useRootModel(const objects = useObjectSearch(scope === "issues" || scope === "commands" ? "" : q, active);const recent = useRecentItems(active && !rawQuery.trim());+ const appsAvailable = useComposioAvailable();const navPages = useMemo<NavPage[]>(() =>- NAV_PAGE_KEYS.filter((key) => key !== "docs" || docsEnabled).map((key) => ({+ NAV_PAGE_KEYS.filter((key) => (key !== "docs" || docsEnabled) && (key !== "apps" || appsAvailable)).map((key) => ({key,label: tNav(($) => $.nav[WORKSPACE_PAGES[key].navKey]),keywords: PAGE_KEYWORDS[key],})),- [docsEnabled, tNav],+ [docsEnabled, tNav, appsAvailable],);return useMemo<RootModel>(() => {diff --git a/packages/views/settings/components/add-app-dialog.test.tsx b/packages/views/settings/components/add-app-dialog.test.tsxdeleted file mode 100644index 7338636c4c..0000000000--- a/packages/views/settings/components/add-app-dialog.test.tsx+++ /dev/null@@ -1,169 +0,0 @@-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";-import { cleanup, render, screen, waitFor, within } from "@testing-library/react";-import userEvent from "@testing-library/user-event";-import { api, ApiError } from "@multica/core/api";-import type { PaidFeatureAccess } from "@multica/core/billing";-import { toast } from "sonner";-import enBilling from "../../locales/en/billing.json";-import { I18nProvider } from "@multica/core/i18n/react";-import type { AppAccountScope, AppsOverview } from "@multica/core/types";-import enCommon from "../../locales/en/common.json";-import enSettings from "../../locales/en/settings.json";-import { AddAppDialog } from "./add-app-dialog";--vi.mock("sonner", () => ({ toast: { error: vi.fn(), success: vi.fn() } }));-vi.mock("@multica/core/paths", async (importOriginal) => ({- ...(await importOriginal<object>()),- useWorkspacePaths: () => ({ settings: () => "/acme/settings" }),-}));-vi.mock("../../navigation", async (importOriginal) => ({- ...(await importOriginal<object>()),- AppLink: ({ href, children, ...props }: React.ComponentProps<"a"> & { href: string }) => <a href={href} {...props}>{children}</a>,-}));--vi.mock("@multica/core/api", async (importOriginal) => ({- ...(await importOriginal<typeof import("@multica/core/api")>()),- api: { connectApp: vi.fn() },-}));--const overview: AppsOverview = {- catalog_mode: "all", can_manage: true, agent_apps: [], personal: [],- team: [{ id: "team-gmail", toolkit_slug: "gmail", status: "active", connected_at: "", last_used_at: null }],-};-const catalog = [- { slug: "gmail", name: "Gmail", curated: true, recommended_scope: "personal" as const },- { slug: "notion", name: "Notion", curated: true, recommended_scope: "team" as const },-];--beforeEach(() => { vi.mocked(api.connectApp).mockRejectedValue(new Error("offline")); });-afterEach(() => {- cleanup();- vi.clearAllMocks();- delete (window as { desktopAPI?: unknown }).desktopAPI;-});--function renderDialog(- scope: AppAccountScope,- canManage = true,- extra: { overview?: AppsOverview; teamAccess?: Pick<PaidFeatureAccess, "canAdd" | "state">; onConnectError?: (e: unknown) => void } = {},-) {- render(<I18nProvider locale="en" resources={{ en: { common: enCommon, settings: enSettings, billing: enBilling } }}>- <AddAppDialog open onOpenChange={vi.fn()} scope={scope} canManage={canManage}- overview={extra.overview ?? overview} catalog={catalog} catalogLoading={false} catalogError={false}- teamAccess={extra.teamAccess} onConnectError={extra.onConnectError} />- </I18nProvider>);-}--describe("AddAppDialog", () => {- it("shows only team connection actions in the team context", async () => {- const user = userEvent.setup();- renderDialog("team");- const dialog = screen.getByRole("dialog", { name: "Connect team account" });- expect(within(dialog).getAllByRole("button", { name: "Connect" })).toHaveLength(1);- expect(within(dialog).getByText("Connected")).toBeVisible();- await user.click(within(dialog).getByRole("button", { name: "Connect" }));- await waitFor(() => expect(api.connectApp).toHaveBeenCalledWith("team", "notion"));- });-- it("does not mistake a team connection for the caller's personal connection", async () => {- const user = userEvent.setup();- renderDialog("personal", false);- const dialog = screen.getByRole("dialog", { name: "Connect my account" });- expect(within(dialog).getAllByRole("button", { name: "Connect" })).toHaveLength(2);- expect(within(dialog).queryByText("Connected")).not.toBeInTheDocument();- const row = within(dialog).getByText("Gmail").closest("li")!;- await user.click(within(row).getByRole("button", { name: "Connect" }));- await waitFor(() => expect(api.connectApp).toHaveBeenCalledWith("personal", "gmail"));- });-- it("guards team connections even if a member is passed a team dialog", async () => {- const user = userEvent.setup();- renderDialog("team", false);- const connect = screen.getByRole("button", { name: "Connect" });- expect(connect).toBeDisabled();- await user.click(connect);- expect(api.connectApp).not.toHaveBeenCalled();- });-- it("keeps the scoped dialog open after failure and permits retry", async () => {- const user = userEvent.setup();- renderDialog("team");- const connect = screen.getByRole("button", { name: "Connect" });- await user.click(connect);- await waitFor(() => expect(connect).toBeEnabled());- expect(screen.getByRole("dialog", { name: "Connect team account" })).toBeVisible();- await user.click(connect);- await waitFor(() => expect(api.connectApp).toHaveBeenCalledTimes(2));- expect(api.connectApp).toHaveBeenLastCalledWith("team", "notion");- });-- it("hands the hosted flow to the system browser on Desktop and frees the row", async () => {- // Desktop blocks same-window navigation to another origin, so assigning- // the location left the row on "Connecting..." forever.- const openExternal = vi.fn();- (window as { desktopAPI?: unknown }).desktopAPI = { openExternal, pickDirectory: vi.fn() };- vi.mocked(api.connectApp).mockResolvedValue({ redirect_url: "https://connect.example.test/flow" });- const user = userEvent.setup();- renderDialog("team");- const connect = screen.getByRole("button", { name: "Connect" });- await user.click(connect);- await waitFor(() => expect(openExternal).toHaveBeenCalledWith("https://connect.example.test/flow"));- await waitFor(() => expect(connect).toBeEnabled());- expect(connect).toHaveTextContent("Connect");- });-});--describe("AddAppDialog on a plan without team app accounts (MUL-9491)", () => {- const withExpiredSlack: AppsOverview = {- ...overview,- team: [...overview.team, { id: "team-slack", toolkit_slug: "slack", status: "expired", connected_at: "", last_used_at: null }],- };- const catalogWithSlack = [...catalog, { slug: "slack", name: "Slack", curated: true }];-- it("connects a new team app normally when the plan includes it", async () => {- const user = userEvent.setup();- renderDialog("team", true, { teamAccess: { canAdd: true, state: "available" } });- expect(screen.queryByText("View plans")).not.toBeInTheDocument();- await user.click(screen.getByRole("button", { name: "Connect" }));- await waitFor(() => expect(api.connectApp).toHaveBeenCalledWith("team", "notion"));- });-- it("replaces Connect with Upgrade to add for an app without a team account", async () => {- const user = userEvent.setup();- renderDialog("team", true, { teamAccess: { canAdd: false, state: "read_only" } });- expect(screen.getByText("Read-only. Upgrade to edit.")).toBeVisible();- const upgrade = screen.getByRole("link", { name: "Upgrade to add" });- expect(upgrade).toHaveAttribute("href", "/acme/settings?tab=billing");- expect(screen.queryByRole("button", { name: "Connect" })).not.toBeInTheDocument();- await user.click(upgrade);- expect(api.connectApp).not.toHaveBeenCalled();- });-- it("still reconnects an app's existing team account", async () => {- const user = userEvent.setup();- render(<I18nProvider locale="en" resources={{ en: { common: enCommon, settings: enSettings, billing: enBilling } }}>- <AddAppDialog open onOpenChange={vi.fn()} scope="team" canManage overview={withExpiredSlack}- catalog={catalogWithSlack} catalogLoading={false} catalogError={false}- teamAccess={{ canAdd: false, state: "read_only" }} />- </I18nProvider>);- await user.click(screen.getByRole("button", { name: "Reconnect" }));- await waitFor(() => expect(api.connectApp).toHaveBeenCalledWith("team", "slack"));- });-- it("does not gate personal accounts", () => {- renderDialog("personal", true, { teamAccess: { canAdd: false, state: "unavailable" } });- expect(screen.getAllByRole("button", { name: "Connect" })).toHaveLength(2);- expect(screen.queryByText("View plans")).not.toBeInTheDocument();- });-- it("explains a feature_locked refusal and reports it to the caller", async () => {- const locked = new ApiError("locked", 403, "Forbidden", { code: "feature_locked", feature: "team_app_accounts" });- vi.mocked(api.connectApp).mockRejectedValue(locked);- const onConnectError = vi.fn();- const user = userEvent.setup();- renderDialog("team", true, { teamAccess: { canAdd: true, state: "available" }, onConnectError });- await user.click(screen.getByRole("button", { name: "Connect" }));- await waitFor(() => expect(toast.error).toHaveBeenCalledWith(enBilling.paid_feature.locked_error));- expect(onConnectError).toHaveBeenCalledWith(locked);- });-});diff --git a/packages/views/settings/components/add-app-dialog.tsx b/packages/views/settings/components/add-app-dialog.tsxdeleted file mode 100644index e314d07517..0000000000--- a/packages/views/settings/components/add-app-dialog.tsx+++ /dev/null@@ -1,193 +0,0 @@-"use client";--import { useMemo, useState } from "react";-import { toast } from "sonner";-import { Check, Loader2 } from "@multica/ui/icons";-import { Badge } from "@multica/ui/components/ui/badge";-import { Button, buttonVariants } from "@multica/ui/components/ui/button";-import {- Dialog,- DialogContent,- DialogDescription,- DialogHeader,- DialogTitle,-} from "@multica/ui/components/ui/dialog";-import { Input } from "@multica/ui/components/ui/input";-import { api } from "@multica/core/api";-import type { PaidFeatureAccess } from "@multica/core/billing";-import { useWorkspacePaths } from "@multica/core/paths";-import type { AppAccountScope, AppCatalogEntry, AppsOverview } from "@multica/core/types";-import { ComposioToolkitLogo } from "../../common/composio-toolkit-logo";-import { PaidFeatureNotice, usePaidFeatureErrorMessage } from "../../billing";-import { useT } from "../../i18n";-import { AppLink } from "../../navigation";-import { isDesktopShell, openExternal } from "../../platform";--/**- * The add-app dialog: every app the workspace allows, curated ones first.- * The section that opened it determines the account scope.- */-export function AddAppDialog({- open,- onOpenChange,- canManage,- scope,- overview,- catalog,- catalogLoading,- catalogError,- teamAccess,- onConnectError,-}: {- open: boolean;- onOpenChange: (open: boolean) => void;- canManage: boolean;- scope: AppAccountScope;- overview: AppsOverview;- catalog: AppCatalogEntry[];- catalogLoading: boolean;- catalogError: boolean;- /** The plan's `team_app_accounts` access. Omitted means available. */- teamAccess?: Pick<PaidFeatureAccess, "canAdd" | "state">;- onConnectError?: (error: unknown) => void;-}) {- const { t } = useT("settings");- const paidFeatureError = usePaidFeatureErrorMessage();- const [query, setQuery] = useState("");- const [connecting, setConnecting] = useState<string | null>(null);-- const connected = useMemo(() => {- const set = new Set<string>();- for (const c of overview[scope]) if (c.status === "active") set.add(c.toolkit_slug);- return set;- }, [overview, scope]);- // A team account that already exists (active or expired) can always be- // reauthorized; only a team account for a new app needs the paid feature.- const existingTeam = useMemo(- () => new Set(overview.team.filter((c) => c.status !== "revoked").map((c) => c.toolkit_slug)),- [overview.team],- );- const canAddTeam = teamAccess?.canAdd ?? true;- const teamState = scope === "team" ? teamAccess?.state : null;-- const filtered = useMemo(() => {- const q = query.trim().toLowerCase();- if (!q) return catalog;- return catalog.filter(- (app) =>- app.name.toLowerCase().includes(q) ||- app.slug.includes(q) ||- (app.category ?? "").toLowerCase().includes(q),- );- }, [catalog, query]);-- async function connect(app: AppCatalogEntry) {- if (connecting || (scope === "team" && (!canManage || (!canAddTeam && !existingTeam.has(app.slug))))) return;- setConnecting(app.slug);- try {- const { redirect_url } = await api.connectApp(scope, app.slug);- openExternal(redirect_url, { webTarget: "same-tab" });- // The web tab leaves for the hosted flow. Desktop opens it in the system- // browser and stays here, so the row must become clickable again.- if (isDesktopShell()) setConnecting(null);- } catch (e) {- onConnectError?.(e);- toast.error(paidFeatureError(e, e instanceof Error && e.message ? e.message : t(($) => $.connected_apps.toast_failed)));- setConnecting(null);- }- }-- const connectButton = (app: AppCatalogEntry) => {- if (connected.has(app.slug)) {- return (- <span className="inline-flex items-center gap-1 text-caption text-muted-foreground">- <Check className="size-3" />- {t(($) => $.connected_apps.add.connected)}- </span>- );- }- const reconnect = scope === "team" && existingTeam.has(app.slug);- if (scope === "team" && canManage && !canAddTeam && !reconnect) {- return <UpgradeToAddLink />;- }- return (- <Button- size="xs"- variant="outline"- disabled={connecting !== null || (scope === "team" && !canManage)}- onClick={() => connect(app)}- >- {connecting === app.slug && <Loader2 className="animate-spin" />}- {connecting === app.slug- ? t(($) => $.connected_apps.add.connecting)- : reconnect- ? t(($) => $.connected_apps.reconnect)- : t(($) => $.connected_apps.add.connect)}- </Button>- );- };-- return (- <Dialog open={open} onOpenChange={onOpenChange}>- <DialogContent className="sm:max-w-2xl">- <DialogHeader>- <DialogTitle>{scope === "team" ? t(($) => $.connected_apps.add.connect_team) : t(($) => $.connected_apps.add.connect_personal)}</DialogTitle>- <DialogDescription>{scope === "team" ? t(($) => $.connected_apps.add.team_description) : t(($) => $.connected_apps.add.personal_description)}</DialogDescription>- </DialogHeader>- {canManage && (teamState === "read_only" || teamState === "unavailable") ? (- <PaidFeatureNotice state={teamState} />- ) : null}- <Input- autoFocus- value={query}- onChange={(e) => setQuery(e.target.value)}- placeholder={t(($) => $.connected_apps.add.search)}- />- <div className="max-h-[60vh] min-h-48 overflow-y-auto rounded-lg border">- {catalogLoading ? (- <p className="p-4 text-caption text-muted-foreground">{t(($) => $.connected_apps.loading)}</p>- ) : catalogError ? (- <p className="p-4 text-caption text-destructive">{t(($) => $.connected_apps.load_failed)}</p>- ) : filtered.length === 0 ? (- <p className="p-4 text-caption text-muted-foreground">{t(($) => $.connected_apps.add.empty)}</p>- ) : (- <ul className="divide-y">- {filtered.map((app) => (- <li key={app.slug} className="flex items-center gap-3 px-3 py-2.5">- <ComposioToolkitLogo slug={app.slug} name={app.name} fallbackLogo={app.logo} />- <div className="min-w-0 flex-1">- <p className="flex items-center gap-2 truncate text-body font-medium">- {app.name || app.slug}- {app.curated && (- <Badge variant="secondary">{t(($) => $.connected_apps.add.curated)}</Badge>- )}- </p>- <p className="truncate text-caption text-muted-foreground">- {app.recommended_scope === "team"- ? t(($) => $.connected_apps.add.recommended_team)- : app.recommended_scope === "personal"- ? t(($) => $.connected_apps.add.recommended_personal)- : app.category}- </p>- </div>- <div className="shrink-0">{connectButton(app)}</div>- </li>- ))}- </ul>- )}- </div>- </DialogContent>- </Dialog>- );-}--/** Stands in for Connect where the plan cannot add a team account. */-function UpgradeToAddLink() {- const { t } = useT("billing");- const paths = useWorkspacePaths();- return (- <AppLink href={`${paths.settings()}?tab=billing`} className={buttonVariants({ size: "xs", variant: "outline" })}>- {t(($) => $.paid_feature.upgrade_to_add)}- </AppLink>- );-}diff --git a/packages/views/settings/components/apps-settings.test.tsx b/packages/views/settings/components/apps-settings.test.tsxdeleted file mode 100644index 2c9d4dfe9f..0000000000--- a/packages/views/settings/components/apps-settings.test.tsx+++ /dev/null@@ -1,203 +0,0 @@-import { afterEach, beforeEach, expect, it, vi } from "vitest";-import { cleanup, fireEvent, 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 { workspaceFeatureKeys } from "@multica/core/billing";-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 enBilling from "../../locales/en/billing.json";-import { toast } from "sonner";-import { openExternal } from "../../platform";-import { AppsSettings } from "./apps-settings";--const nav = vi.hoisted(() => ({- searchParams: new URLSearchParams(),- pathname: "/acme/settings",- replace: vi.fn(),-}));--vi.mock("@multica/core/api", async (importOriginal) => ({- ...(await importOriginal<typeof import("@multica/core/api")>()),- api: {- getAppsOverview: vi.fn(), listAppCatalog: vi.fn(), updateAppSettings: vi.fn(), updateAppRules: vi.fn(),- getWorkspaceFeatures: vi.fn(), connectApp: vi.fn(),- },-}));-vi.mock("../../platform", async (importOriginal) => ({- ...(await importOriginal<typeof import("../../platform")>()),- openExternal: vi.fn(),-}));-vi.mock("@multica/core/paths", async (importOriginal) => ({- ...(await importOriginal<object>()),- useWorkspacePaths: () => ({ settings: () => "/acme/settings" }),-}));-vi.mock("@multica/core/hooks", () => ({ useWorkspaceId: () => "ws-1" }));-vi.mock("sonner", () => ({ toast: { success: vi.fn(), error: vi.fn() } }));-vi.mock("@multica/core/workspace/hooks", () => ({ useActorName: () => ({ getActorName: () => "Admin" }) }));-vi.mock("../../navigation", () => ({- useNavigation: () => nav,- AppLink: ({ href, children, ...props }: React.ComponentProps<"a"> & { href: string }) => <a href={href} {...props}>{children}</a>,-}));--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.getWorkspaceFeatures).mockResolvedValue({ features: {} });- 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();- nav.searchParams = new URLSearchParams();- vi.clearAllMocks();- delete (window as { desktopAPI?: unknown }).desktopAPI;-});--function renderSettings() {- const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });- render(<QueryClientProvider client={client}>- <I18nProvider locale="en" resources={{ en: { common: enCommon, settings: enSettings, billing: enBilling } }}>- <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 previous 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 previous 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("Previous action restrictions are still limiting this account.")).toHaveLength(1);-});--it("reconnects an expired account from its row", async () => {- overview.personal = [- ...overview.personal,- { id: "personal-2", toolkit_slug: "mobbin", status: "expired", connected_at: "", last_used_at: null },- ];- vi.mocked(api.connectApp).mockResolvedValue({ redirect_url: "https://auth.example.com/authorize?state=s" });- const user = userEvent.setup();- renderSettings();- expect(await screen.findByText("Needs reconnecting")).toBeVisible();- const buttons = screen.getAllByRole("button", { name: "Reconnect" });- expect(buttons).toHaveLength(1);- await user.click(buttons[0]!);- await waitFor(() => expect(api.connectApp).toHaveBeenCalledWith("personal", "mobbin"));- expect(openExternal).toHaveBeenCalledWith("https://auth.example.com/authorize?state=s", { webTarget: "same-tab" });-});--it("opens a connection dialog for the section that launched it", async () => {- const user = userEvent.setup();- renderSettings();- expect(await screen.findByRole("button", { name: "Connect team account" })).toBeVisible();- expect(screen.queryByRole("button", { name: "Add app" })).not.toBeInTheDocument();- await user.click(screen.getByRole("button", { name: "Connect team account" }));- expect(screen.getByRole("dialog", { name: "Connect team account" })).toBeVisible();- await user.keyboard("{Escape}");- await waitFor(() => expect(screen.queryByRole("dialog")).not.toBeInTheDocument());- await user.click(screen.getByRole("button", { name: "Connect my account" }));- expect(screen.getByRole("dialog", { name: "Connect my account" })).toBeVisible();-});--it("only offers members the personal connection entry", async () => {- overview.can_manage = false;- renderSettings();- expect(await screen.findByRole("button", { name: "Connect my account" })).toBeVisible();- expect(screen.queryByRole("button", { name: "Connect team account" })).not.toBeInTheDocument();-});--it("reloads accounts when the Desktop window is focused again after connecting in the browser", async () => {- (window as { desktopAPI?: unknown }).desktopAPI = { pickDirectory: vi.fn() };- renderSettings();- await screen.findByText("A previous app list is hiding other apps.");- expect(api.getAppsOverview).toHaveBeenCalledTimes(1);- fireEvent.focus(window);- await waitFor(() => expect(api.getAppsOverview).toHaveBeenCalledTimes(2));-});--it("does not reload on focus on the web, where the flow returns to this tab", async () => {- renderSettings();- await screen.findByText("A previous app list is hiding other apps.");- fireEvent.focus(window);- await new Promise((resolve) => setTimeout(resolve, 20));- expect(api.getAppsOverview).toHaveBeenCalledTimes(1);-});--it("passes the plan's team account access to the connect dialog", async () => {- vi.mocked(api.getWorkspaceFeatures).mockResolvedValue({ features: { team_app_accounts: "locked" } });- vi.mocked(api.listAppCatalog).mockResolvedValue({ catalog_mode: "all", apps: [- { slug: "gmail", name: "Gmail", curated: true },- { slug: "notion", name: "Notion", curated: true },- ] });- overview.team = [{ id: "team-1", toolkit_slug: "gmail", status: "expired", connected_at: "", last_used_at: null }];- const user = userEvent.setup();- renderSettings();- await waitFor(() => expect(api.getWorkspaceFeatures).toHaveBeenCalled());- await user.click(await screen.findByRole("button", { name: "Connect team account" }));- const dialog = screen.getByRole("dialog", { name: "Connect team account" });- expect(await within(dialog).findByText("Read-only. Upgrade to edit.")).toBeVisible();- expect(within(dialog).getByRole("button", { name: "Reconnect" })).toBeEnabled();- expect(within(dialog).getByRole("link", { name: "Upgrade to add" })).toBeVisible();-});--it("explains a team connect refused by the plan and refetches the plan", async () => {- nav.searchParams = new URLSearchParams(- "tab=apps&error=composio_connect_failed&reason=feature_locked&scope=team",- );- const invalidate = vi.spyOn(QueryClient.prototype, "invalidateQueries");- renderSettings();- await waitFor(() => expect(toast.error).toHaveBeenCalledWith(enBilling.paid_feature.locked_error));- expect(toast.error).not.toHaveBeenCalledWith(enSettings.connected_apps.toast_connect_failed);- expect(invalidate).toHaveBeenCalledWith({ queryKey: workspaceFeatureKeys.all("ws-1") });- invalidate.mockRestore();- expect(nav.replace).toHaveBeenCalledWith("/acme/settings?tab=apps");-});--it("keeps the generic retry message when an older server sends no reason", async () => {- nav.searchParams = new URLSearchParams("tab=integrations&error=composio_connect_failed");- renderSettings();- await waitFor(() => expect(toast.error).toHaveBeenCalledWith(enSettings.connected_apps.toast_connect_failed));- expect(toast.error).not.toHaveBeenCalledWith(enBilling.paid_feature.locked_error);- expect(nav.replace).toHaveBeenCalledWith("/acme/settings?tab=apps");-});diff --git a/packages/views/settings/components/apps-settings.tsx b/packages/views/settings/components/apps-settings.tsxdeleted file mode 100644index 8631ebd53d..0000000000--- a/packages/views/settings/components/apps-settings.tsx+++ /dev/null@@ -1,439 +0,0 @@-"use client";--import { useEffect, useMemo, useRef, useState } from "react";-import { useQuery, useQueryClient } from "@tanstack/react-query";-import { toast } from "sonner";-import { AlertTriangle, Plus, Trash2 } from "@multica/ui/icons";-import { Button } from "@multica/ui/components/ui/button";-import {- AlertDialog,- AlertDialogAction,- AlertDialogCancel,- AlertDialogContent,- AlertDialogDescription,- AlertDialogFooter,- AlertDialogHeader,- AlertDialogTitle,-} from "@multica/ui/components/ui/alert-dialog";-import { api } from "@multica/core/api";-import { useWorkspaceId } from "@multica/core/hooks";-import {- FEATURE_LOCKED_CODE,- refreshFeaturesOnLockedError,- usePaidFeatureAccess,- workspaceFeatureKeys,-} from "@multica/core/billing";-import {- appCatalogOptions,- appsOverviewOptions,- connectedAppsKeys,- teamAppImpactOptions,- useDisconnectTeamApp,- useRestoreAppAccess,-} from "@multica/core/connected-apps";-import { useActorName } from "@multica/core/workspace/hooks";-import type {- AppAccountScope,- AppCatalogEntry,- 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 { isDesktopShell, openExternal } from "../../platform";-import { AddAppDialog } from "./add-app-dialog";-import { AppAccountDialog } from "./app-account-dialog";-import { SettingsCard, SettingsSection } from "./settings-layout";--type AccountTarget = { scope: AppAccountScope; connection: AppConnection; name: string };--/** 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 { t: tBilling } = useT("billing");- const wsId = useWorkspaceId();- const qc = useQueryClient();- const navigation = useNavigation();- const overview = useQuery(appsOverviewOptions(wsId));- const catalog = useQuery(appCatalogOptions(wsId));- const restore = useRestoreAppAccess();- // Without the paid feature existing team accounts keep working and can be- // reauthorized or disconnected; only a team account for a new app is refused.- const teamAccess = usePaidFeatureAccess(wsId, "team_app_accounts", {- hasExistingConfig: (overview.data?.team ?? []).some((c) => c.status !== "revoked"),- });-- const [addingScope, setAddingScope] = useState<AppAccountScope | null>(null);- const [detail, setDetail] = useState<AccountTarget | null>(null);- const [disconnecting, setDisconnecting] = useState<AccountTarget | null>(null);-- // The hosted connect flow returns with `?connected=<slug>` or- // `?error=composio_connect_failed`, plus `reason=feature_locked` when the- // plan refused a team account (older servers send no reason). Consume it- // once, then drop the params so a refresh does not toast again.- const connectedParam = navigation.searchParams.get("connected");- const errorParam = navigation.searchParams.get("error");- const reasonParam = navigation.searchParams.get("reason");- const consumed = useRef<string | null>(null);- useEffect(() => {- const key = connectedParam- ? `connected:${connectedParam}`- : errorParam === "composio_connect_failed"- ? "error"- : null;- if (!key || consumed.current === key) return;- consumed.current = key;- if (connectedParam) {- toast.success(t(($) => $.connected_apps.toast_connected));- void qc.invalidateQueries({ queryKey: connectedAppsKeys.all(wsId) });- } else if (reasonParam === FEATURE_LOCKED_CODE) {- // This tab's view of the plan was stale: refetch so the page switches to- // its locked state.- toast.error(tBilling(($) => $.paid_feature.locked_error));- void qc.invalidateQueries({ queryKey: workspaceFeatureKeys.all(wsId) });- } else {- toast.error(t(($) => $.connected_apps.toast_connect_failed));- }- const params = new URLSearchParams(navigation.searchParams);- params.set("tab", "apps");- for (const k of ["integration", "connected", "error", "reason", "scope"]) params.delete(k);- navigation.replace(`${navigation.pathname}?${params.toString()}`);- // eslint-disable-next-line react-hooks/exhaustive-deps- }, [connectedParam, errorParam]);-- // Desktop finishes the hosted flow in the system browser, so that return- // never reaches this window. Reload the accounts when it is focused again.- useEffect(() => {- if (!isDesktopShell()) return;- const refresh = () => void qc.invalidateQueries({ queryKey: connectedAppsKeys.overview(wsId) });- window.addEventListener("focus", refresh);- return () => window.removeEventListener("focus", refresh);- }, [qc, wsId]);-- const appBySlug = useMemo(() => {- const m = new Map<string, AppCatalogEntry>();- for (const app of catalog.data?.apps ?? []) m.set(app.slug, app);- return m;- }, [catalog.data]);-- const agentCount = useMemo(() => {- const m = new Map<string, number>();- for (const app of overview.data?.agent_apps ?? []) {- const key = `${app.account_scope}:${app.toolkit_slug}`;- m.set(key, (m.get(key) ?? 0) + 1);- }- return m;- }, [overview.data]);-- if (overview.isLoading) {- return <p className="text-body text-muted-foreground">{t(($) => $.connected_apps.loading)}</p>;- }- if (overview.isError || !overview.data) {- return <p className="text-body text-destructive">{t(($) => $.connected_apps.load_failed)}</p>;- }- const data = overview.data;- const canManage = data.can_manage;- const nameOf = (slug: string) => appBySlug.get(slug)?.name || slug;- const rows = (scope: AppAccountScope, connections: AppConnection[]) =>- connections- .filter((c) => c.status !== "revoked")- .map((c) => (- <AccountRow- key={c.id}- scope={scope}- connection={c}- app={appBySlug.get(c.toolkit_slug)}- agents={agentCount.get(`${scope}:${c.toolkit_slug}`) ?? 0}- canManage={scope === "personal" || canManage}- onOpen={() => setDetail({ scope, connection: c, name: nameOf(c.toolkit_slug) })}- onDisconnect={() => setDisconnecting({ scope, connection: c, name: nameOf(c.toolkit_slug) })}- />- ));- const teamRows = rows("team", data.team);- const personalRows = rows("personal", data.personal);-- return (- <div className="space-y-8">- <p className="text-caption text-muted-foreground">{t(($) => $.connected_apps.description)}</p>-- {data.catalog_mode !== "all" && (- <SavedAppRestriction- kind="catalog"- onRestore={canManage ? () => restore.mutateAsync({ catalog: true }) : undefined}- />- )}-- <SettingsSection- anchor="team-accounts"- title={t(($) => $.connected_apps.team_title)}- description={t(($) => $.connected_apps.team_description)}- action={canManage ? (- <Button size="sm" onClick={() => setAddingScope("team")}>- <Plus />- {t(($) => $.connected_apps.add.connect_team)}- </Button>- ) : undefined}- >- {teamRows.length > 0 ? (- <SettingsCard>{teamRows}</SettingsCard>- ) : (- <EmptyCard- text={- canManage- ? t(($) => $.connected_apps.team_empty)- : t(($) => $.connected_apps.team_empty_member)- }- />- )}- </SettingsSection>-- <SettingsSection- anchor="my-accounts"- title={t(($) => $.connected_apps.personal_title)}- description={t(($) => $.connected_apps.personal_description)}- action={(- <Button size="sm" onClick={() => setAddingScope("personal")}>- <Plus />- {t(($) => $.connected_apps.add.connect_personal)}- </Button>- )}- >- {personalRows.length > 0 ? (- <SettingsCard>{personalRows}</SettingsCard>- ) : (- <EmptyCard text={t(($) => $.connected_apps.personal_empty)} />- )}- </SettingsSection>-- {addingScope && (- <AddAppDialog- key={addingScope}- scope={addingScope}- open- onOpenChange={(open) => { if (!open) setAddingScope(null); }}- canManage={canManage}- overview={data}- catalog={catalog.data?.apps ?? []}- catalogLoading={catalog.isLoading}- catalogError={catalog.isError}- teamAccess={teamAccess}- onConnectError={(error) => refreshFeaturesOnLockedError(qc, wsId, error)}- />- )}- {detail && (- <AppAccountDialog- scope={detail.scope}- slug={detail.connection.toolkit_slug}- name={detail.name}- onClose={() => setDetail(null)}- />- )}- {disconnecting?.scope === "team" && (- <DisconnectTeamDialog target={disconnecting} onClose={() => setDisconnecting(null)} />- )}- {disconnecting?.scope === "personal" && (- <DisconnectPersonalDialog target={disconnecting} onClose={() => setDisconnecting(null)} />- )}- </div>- );-}--function EmptyCard({ text }: { text: string }) {- return (- <div className="rounded-lg border border-dashed px-4 py-6 text-center text-caption text-muted-foreground">- {text}- </div>- );-}--function AccountRow({- scope,- connection,- app,- agents,- canManage,- onOpen,- onDisconnect,-}: {- scope: AppAccountScope;- connection: AppConnection;- app?: AppCatalogEntry;- agents: number;- canManage: boolean;- onOpen: () => void;- onDisconnect: () => void;-}) {- const { t } = useT("settings");- const timeAgo = useTimeAgo();- const { getActorName } = useActorName();- const restore = useRestoreAppAccess();- const [reconnecting, setReconnecting] = useState(false);- const name = app?.name || connection.toolkit_slug;- const expired = connection.status === "expired";-- async function reconnect() {- setReconnecting(true);- try {- const { redirect_url } = await api.connectApp(scope, connection.toolkit_slug);- openExternal(redirect_url, { webTarget: "same-tab" });- // Desktop opens the hosted flow in the system browser and stays here.- if (isDesktopShell()) setReconnecting(false);- } catch (e) {- toast.error(e instanceof Error && e.message ? e.message : t(($) => $.connected_apps.toast_failed));- setReconnecting(false);- }- }- const meta = [- scope === "team" && connection.connected_by- ? t(($) => $.connected_apps.connected_by, { name: getActorName("member", connection.connected_by) })- : null,- connection.last_used_at- ? t(($) => $.connected_apps.last_used, { when: timeAgo(connection.last_used_at) })- : t(($) => $.connected_apps.last_used_never),- agents > 0 ? t(($) => $.connected_apps.used_by, { count: agents }) : null,- ].filter(Boolean);-- return (- <div>- <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 && (- <>- {expired && (- <Button variant="outline" size="sm" onClick={reconnect} disabled={reconnecting}>- {t(($) => $.connected_apps.reconnect)}- </Button>- )}- <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>- {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>- );-}--function DisconnectTeamDialog({ target, onClose }: { target: AccountTarget; onClose: () => void }) {- const { t } = useT("settings");- const wsId = useWorkspaceId();- const impact = useQuery(teamAppImpactOptions(wsId, target.connection.toolkit_slug));- const disconnect = useDisconnectTeamApp();- const data = impact.data;-- return (- <AlertDialog open onOpenChange={(open) => !open && !disconnect.isPending && onClose()}>- <AlertDialogContent>- <AlertDialogHeader>- <AlertDialogTitle>{t(($) => $.connected_apps.disconnect_team.title, { app: target.name })}</AlertDialogTitle>- <AlertDialogDescription>{t(($) => $.connected_apps.disconnect_team.description)}</AlertDialogDescription>- </AlertDialogHeader>- {data && (- <div className="space-y-2 text-caption">- <p className="font-medium">{t(($) => $.connected_apps.disconnect_team.agents)}</p>- <p className="text-muted-foreground">- {data.agents.length > 0- ? data.agents.map((a) => a.name).join(", ")- : t(($) => $.connected_apps.disconnect_team.no_agents)}- </p>- <ul className="space-y-0.5 text-muted-foreground">- <li>{t(($) => $.connected_apps.disconnect_team.active_tasks, { count: data.active_tasks })}</li>- <li>{t(($) => $.connected_apps.disconnect_team.active_autopilots, { count: data.active_autopilots })}</li>- <li>{t(($) => $.connected_apps.disconnect_team.pending, { count: data.pending_requests })}</li>- </ul>- </div>- )}- <AlertDialogFooter>- <AlertDialogCancel disabled={disconnect.isPending}>- {t(($) => $.connected_apps.disconnect_team.cancel)}- </AlertDialogCancel>- <AlertDialogAction- variant="destructive"- disabled={disconnect.isPending}- onClick={() =>- disconnect.mutate(target.connection.id, {- onSuccess: () => {- toast.success(t(($) => $.connected_apps.toast_disconnected));- onClose();- },- onError: () => toast.error(t(($) => $.connected_apps.toast_failed)),- })- }- >- {t(($) => $.connected_apps.disconnect_team.confirm)}- </AlertDialogAction>- </AlertDialogFooter>- </AlertDialogContent>- </AlertDialog>- );-}--function DisconnectPersonalDialog({ target, onClose }: { target: AccountTarget; onClose: () => void }) {- const { t } = useT("settings");- const wsId = useWorkspaceId();- const qc = useQueryClient();- const [pending, setPending] = useState(false);-- return (- <AlertDialog open onOpenChange={(open) => !open && !pending && onClose()}>- <AlertDialogContent>- <AlertDialogHeader>- <AlertDialogTitle>{t(($) => $.connected_apps.disconnect_personal.title, { app: target.name })}</AlertDialogTitle>- <AlertDialogDescription>{t(($) => $.connected_apps.disconnect_personal.description)}</AlertDialogDescription>- </AlertDialogHeader>- <AlertDialogFooter>- <AlertDialogCancel disabled={pending}>{t(($) => $.connected_apps.disconnect_personal.cancel)}</AlertDialogCancel>- <AlertDialogAction- variant="destructive"- disabled={pending}- onClick={async () => {- setPending(true);- try {- await api.deleteComposioConnection(target.connection.id);- await qc.invalidateQueries({ queryKey: connectedAppsKeys.all(wsId) });- toast.success(t(($) => $.connected_apps.toast_disconnected));- onClose();- } catch {- toast.error(t(($) => $.connected_apps.toast_failed));- } finally {- setPending(false);- }- }}- >- {t(($) => $.connected_apps.disconnect_personal.confirm)}- </AlertDialogAction>- </AlertDialogFooter>- </AlertDialogContent>- </AlertDialog>- );-}diff --git a/packages/views/settings/components/connected-apps-tab.tsx b/packages/views/settings/components/connected-apps-tab.tsxdeleted file mode 100644index d6aa9054ad..0000000000--- a/packages/views/settings/components/connected-apps-tab.tsx+++ /dev/null@@ -1,38 +0,0 @@-"use client";--import { useQuery } from "@tanstack/react-query";-import { ApiError, errorCode } from "@multica/core/api";-import { composioToolkitsOptions } from "@multica/core/composio";-import { useFeatureEnabled } from "@multica/core/config";-import { COMPOSIO_MCP_APPS_FLAG } from "@multica/core/feature-flags";-import { useT } from "../../i18n";-import { AppsSettings } from "./apps-settings";-import { SettingsTab } from "./settings-layout";--/**- * Whether the Connected apps page exists. A pending or failed catalog read- * still counts as available — only an explicit "Composio is not configured on- * this server" hides the page, so a transient error never removes it.- */-export function useComposioAvailable(): boolean {- const enabled = useFeatureEnabled(COMPOSIO_MCP_APPS_FLAG, false);- const toolkits = useQuery({ ...composioToolkitsOptions(), enabled });- return (- enabled &&- errorCode(toolkits.error) !== "composio_not_configured" &&- !(toolkits.error instanceof ApiError && toolkits.error.status === 503)- );-}--/**- * Connected apps belong to the workspace: team accounts are shared and- * admin-managed, personal accounts are each member's own (MUL-8516).- */-export function ConnectedAppsTab() {- const { t } = useT("settings");- return (- <SettingsTab title={t(($) => $.page.tabs.apps)} scope="workspace">- <AppsSettings />- </SettingsTab>- );-}diff --git a/packages/views/settings/components/mcp-tab.tsx b/packages/views/settings/components/mcp-tab.tsxindex d23439224c..1caa08e338 100644--- a/packages/views/settings/components/mcp-tab.tsx+++ b/packages/views/settings/components/mcp-tab.tsx@@ -16,7 +16,7 @@ import {} from "@multica/ui/components/ui/alert-dialog";import { Badge } from "@multica/ui/components/ui/badge";import { Button } from "@multica/ui/components/ui/button";-import { useCurrentWorkspace } from "@multica/core/paths";+import { paths, useCurrentWorkspace } from "@multica/core/paths";import { useCurrentMember } from "@multica/core/permissions";import { useFeatureEnabled } from "@multica/core/config";import { PLUGINS_V1_FLAG } from "@multica/core/feature-flags";@@ -39,7 +39,7 @@ import {SettingsTab,} from "./settings-layout";import { AppLink, useOptionalNavigation } from "../../navigation";-import { useComposioAvailable } from "./connected-apps-tab";+import { useComposioAvailable } from "../../common/use-composio-available";import { settingsHref } from "./settings-navigation";/**@@ -361,6 +361,8 @@ export function McpTab() {*/function ToolSourcesOverview() {const { t } = useT("settings");+ const { t: tl } = useT("layout");+ const workspaceSlug = useCurrentWorkspace()?.slug;const navigation = useOptionalNavigation();const appsAvailable = useComposioAvailable();const tabHref = (tab: string) =>@@ -376,14 +378,14 @@ function ToolSourcesOverview() {description: t(($) => $.mcp_sources.mcp),href: null,},- ...(appsAvailable+ ...(appsAvailable && workspaceSlug? [{key: "apps",icon: Plug,- title: t(($) => $.page.tabs.apps),+ title: tl(($) => $.nav.apps),description: t(($) => $.mcp_sources.apps),- href: tabHref("apps"),+ href: paths.workspace(workspaceSlug).apps(),},]: []),diff --git a/packages/views/settings/components/settings-layout.tsx b/packages/views/settings/components/settings-layout.tsxindex abe9e0f74f..b20e4dca63 100644--- a/packages/views/settings/components/settings-layout.tsx+++ b/packages/views/settings/components/settings-layout.tsx@@ -14,6 +14,7 @@ import {Check,ChevronRight,Eye,+ Globe,Laptop,Loader2,UserRound,@@ -35,6 +36,7 @@ export type SettingsSaveStatus = "idle" | "saving" | "saved" | "error";*/export type SettingsScope =| "account"+ | "all-workspaces"| "device"| "device-workspace"| "workspace"@@ -53,14 +55,16 @@ export function SettingsScopeBadge({ scope }: { scope: SettingsScope }) {if (scope === "workspace" || scope === "workspace-only" || scope === "device-workspace") {return <WorkspaceScopeBadge scope={scope} />;}- const Icon = scope === "account" ? UserRound : Laptop;+ const Icon = scope === "account" ? UserRound : scope === "all-workspaces" ? Globe : Laptop;return (<span data-slot="settings-scope" className={SCOPE_BADGE_CLASS}><Icon aria-hidden="true" className="size-3" /><span className="truncate">{scope === "account"? t(($) => $.layout.scope.account)- : t(($) => $.layout.scope.device)}+ : scope === "all-workspaces"+ ? t(($) => $.layout.scope.all_workspaces)+ : t(($) => $.layout.scope.device)}</span></span>);diff --git a/packages/views/settings/components/settings-navigation.test.ts b/packages/views/settings/components/settings-navigation.test.tsindex 13de5355db..52897ffd81 100644--- a/packages/views/settings/components/settings-navigation.test.ts+++ b/packages/views/settings/components/settings-navigation.test.ts@@ -1,6 +1,6 @@// @vitest-environment nodeimport { describe, expect, it } from "vitest";-import { resolveSettingsLocation, settingsHref } from "./settings-navigation";+import { movedAppsHref, resolveSettingsLocation, settingsHref } from "./settings-navigation";const resolve = (search: string) =>resolveSettingsLocation(new URLSearchParams(search));@@ -61,13 +61,13 @@ describe("settings location", () => {});it.each(["connected=notion", "error=composio_connect_failed"])(- "sends the Composio OAuth callback (%s) to Connected apps",+ "sends the legacy personal Composio callback (%s) to the Apps page's Accounts",(callback) => {- expect(resolve(`tab=integrations&${callback}`).tab).toBe("apps");+ expect(resolve(`tab=integrations&${callback}`)).toEqual({ tab: "apps", section: "accounts", integration: null });},);- it("lands a team connect refused by the plan on Connected apps", () => {+ it("lands a team connect refused by the plan on the Apps page", () => {expect(resolve("tab=apps&error=composio_connect_failed&reason=feature_locked&scope=team"),).toEqual({ tab: "apps", section: null, integration: null });@@ -76,6 +76,35 @@ describe("settings location", () => {).toBe("apps");});+ it.each([+ ["tab=apps", null],+ ["tab=apps&connected=gmail", "accounts"],+ ["tab=apps&error=composio_connect_failed", "accounts"],+ ["tab=apps&connected=gmail&scope=team", null],+ ["tab=apps&error=composio_connect_failed&scope=team", null],+ ["tab=apps&error=something_else", null],+ ["tab=accounts", "accounts"],+ ["tab=connected-accounts", "accounts"],+ ])("routes %s to the Apps page (tab %s)", (search, section) => {+ expect(resolve(search)).toEqual({ tab: "apps", section, integration: null });+ });++ it("keeps only the connect result when a settings link moves to the Apps page", () => {+ expect(movedAppsHref("/acme/apps", new URLSearchParams("tab=apps"))).toBe("/acme/apps");+ expect(+ movedAppsHref("/acme/apps", new URLSearchParams("tab=apps&connected=notion&scope=team§ion=x")),+ ).toBe("/acme/apps?connected=notion");+ expect(+ movedAppsHref("/acme/apps", new URLSearchParams("tab=apps&error=composio_connect_failed&scope=team")),+ ).toBe("/acme/apps?error=composio_connect_failed");+ expect(+ movedAppsHref("/acme/apps", new URLSearchParams("tab=apps&error=composio_connect_failed&reason=feature_locked&scope=team")),+ ).toBe("/acme/apps?error=composio_connect_failed&reason=feature_locked");+ expect(+ movedAppsHref("/acme/apps", new URLSearchParams("tab=apps&connected=gmail"), "accounts"),+ ).toBe("/acme/apps?tab=accounts&connected=gmail");+ });+it("passes current pages and anchors through untouched", () => {expect(resolve("tab=code§ion=pr-sidebar")).toEqual({tab: "code",diff --git a/packages/views/settings/components/settings-navigation.ts b/packages/views/settings/components/settings-navigation.tsindex 6801ec8bbd..70878ec235 100644--- a/packages/views/settings/components/settings-navigation.ts+++ b/packages/views/settings/components/settings-navigation.ts@@ -35,12 +35,26 @@ export interface SettingsLocation {integration: string | null;}+function isComposioCallback(params: URLSearchParams) {+ return params.has("connected") || params.get("error") === "composio_connect_failed";+}++// A plan refusal (`reason=feature_locked`) can only be for a team account.+function isPersonalComposioCallback(params: URLSearchParams) {+ return isComposioCallback(params) && params.get("scope") !== "team" && params.get("reason") !== "feature_locked";+}+/*** Resolve a settings URL, including links that predate the current layout.* Server redirects still point at some of them — the GitHub App install flow* returns to `?tab=github` / `?tab=repositories` and the Composio OAuth flow to- * `?tab=integrations&connected=…` — so these mappings are part of the URL- * contract, not bookmarks we can drop.+ * `?tab=apps&connected=…[&scope=team]` (once `?tab=integrations&connected=…`)+ * — so these mappings are part of the URL contract, not bookmarks we can drop.+ *+ * The workspace's apps and accounts left settings for the Apps page: `apps`+ * here means "redirect to it", and section `accounts` its Accounts tab, where+ * a personal connection returns. `accounts` and `connected-accounts` were+ * settings tabs before.*/export function resolveSettingsLocation(params: URLSearchParams,@@ -67,11 +81,19 @@ export function resolveSettingsLocation(return { tab: "code", section: section ?? "repositories", integration: null };case "channels":return { tab: "channels", section, integration: null };+ case "accounts":+ case "connected-accounts":+ return { tab: "apps", section: "accounts", integration: null };+ case "apps":+ if (isPersonalComposioCallback(params)) {+ return { tab: "apps", section: "accounts", integration: null };+ }+ return { tab: "apps", section: null, integration: null };case "integrations": {- const composioCallback =- params.has("connected") ||- params.get("error") === "composio_connect_failed";- if (composioCallback || integration === "composio") {+ if (isPersonalComposioCallback(params)) {+ return { tab: "apps", section: "accounts", integration: null };+ }+ if (isComposioCallback(params) || integration === "composio") {return { tab: "apps", section: null, integration: null };}if (integration === "github") {@@ -110,3 +132,15 @@ export function settingsHref(if (detail.integration) params.set("integration", detail.integration);return `${pathname}?${params.toString()}`;}++/** The Apps page for a retired settings link, keeping the connect result. */+export function movedAppsHref(appsPath: string, searchParams: URLSearchParams, section: string | null = null) {+ const params = new URLSearchParams();+ if (section) params.set("tab", section);+ for (const key of ["connected", "error", "reason"]) {+ const value = searchParams.get(key);+ if (value) params.set(key, value);+ }+ const search = params.toString();+ return search ? `${appsPath}?${search}` : appsPath;+}diff --git a/packages/views/settings/components/settings-page.test.tsx b/packages/views/settings/components/settings-page.test.tsxindex 7daaf3670a..877897e92e 100644--- a/packages/views/settings/components/settings-page.test.tsx+++ b/packages/views/settings/components/settings-page.test.tsx@@ -66,14 +66,13 @@ const shell = vi.hoisted(() => ({appsAvailable: false,role: "owner" as "owner" | "admin" | "member",}));-vi.mock("./connected-apps-tab", () => ({- ConnectedAppsTab: () => <div>ConnectedAppsTab</div>,+vi.mock("../../common/use-composio-available", () => ({useComposioAvailable: () => shell.appsAvailable,}));vi.mock("@multica/core/paths", () => ({useCurrentWorkspace: () => ({ id: "ws-1", name: "Acme" }),- useWorkspacePaths: () => ({ autopilots: () => "/acme/autopilots" }),+ useWorkspacePaths: () => ({ autopilots: () => "/acme/autopilots", apps: () => "/acme/apps" }),}));vi.mock("@multica/core/workspace/avatar-url", () => ({resolvePublicFileUrl: (url: string | null | undefined) => url ?? null,@@ -390,20 +389,38 @@ describe("SettingsPage information architecture", () => {);});- it("lists Connected apps with the workspace connections only when Composio is available", () => {+ it("keeps accounts out of settings, sending old links to the Apps page's Accounts", () => {+ shell.appsAvailable = true;const first = renderWithI18n(<SettingsPage />);- expect(screen.queryByRole("link", { name: "Connected apps" })).toBeNull();+ expect(within(nav()).queryByRole("link", { name: /Accounts|Connected apps/ })).toBeNull();first.unmount();+ navigationState.search = "tab=accounts";+ const second = renderWithI18n(<SettingsPage />);+ expect(replace).toHaveBeenLastCalledWith("/acme/apps?tab=accounts");+ second.unmount();++ navigationState.search = "tab=connected-accounts";+ renderWithI18n(<SettingsPage />);+ expect(replace).toHaveBeenLastCalledWith("/acme/apps?tab=accounts");+ });++ it("sends the retired Apps tab and team connect returns to the Apps page", () => {shell.appsAvailable = true;- navigationState.search = "tab=integrations&connected=notion";+ navigationState.search = "tab=apps";+ const first = renderWithI18n(<SettingsPage />);+ expect(replace).toHaveBeenLastCalledWith("/acme/apps");+ first.unmount();++ navigationState.search = "tab=apps&connected=notion&scope=team";renderWithI18n(<SettingsPage />);- const personal = within(nav()).getByRole("region", { name: /Personal/ });- expect(within(personal).queryByRole("link", { name: "Connected apps" })).toBeNull();- expect(- within(nav()).getByRole("link", { name: "Connected apps" }),- ).toHaveAttribute("aria-current", "page");- expect(screen.getByText("ConnectedAppsTab")).toBeInTheDocument();+ expect(replace).toHaveBeenLastCalledWith("/acme/apps?connected=notion");+ });++ it("sends a personal connect return to the Apps page's Accounts", () => {+ navigationState.search = "tab=apps&connected=notion";+ renderWithI18n(<SettingsPage />);+ expect(replace).toHaveBeenLastCalledWith("/acme/apps?tab=accounts&connected=notion");});it("marks pages a member can only view", () => {diff --git a/packages/views/settings/components/settings-page.tsx b/packages/views/settings/components/settings-page.tsxindex 8686acd062..89dff48090 100644--- a/packages/views/settings/components/settings-page.tsx+++ b/packages/views/settings/components/settings-page.tsx@@ -13,7 +13,6 @@ import {MessagesSquare,Mic,Palette,- Plug,Search,Server,Settings,@@ -34,7 +33,7 @@ import {} from "@multica/core/feature-flags";import { TooltipHint } from "@multica/ui/components/common/tooltip-hint";import { cn } from "@multica/ui/lib/utils";-import { resolveSettingsLocation, settingsHref } from "./settings-navigation";+import { movedAppsHref, resolveSettingsLocation, settingsHref } from "./settings-navigation";import { AppLink, useNavigation } from "../../navigation";import { useRestoredScrollRef } from "../../platform/scroll-restoration";import { AccountTab } from "./account-tab";@@ -45,7 +44,6 @@ import { WorkspaceTab } from "./workspace-tab";import { MembersTab } from "./members-tab";import { CodeTab } from "./code-tab";import { ChannelsTab } from "./channels-tab";-import { ConnectedAppsTab, useComposioAvailable } from "./connected-apps-tab";import { NotificationsTab } from "./notifications-tab";import { LabelsTab } from "./labels-tab";import { WorkflowsTab } from "../../workflows/workflows-tab";@@ -141,7 +139,6 @@ export function SettingsPage({ extraDeviceTabs = [] }: SettingsPageProps = {}) {BILLING_WORKSPACE_SUBSCRIPTIONS_FLAG,false,);- const appsAvailable = useComposioAvailable();const voiceInputAvailable = localVoiceAPI() !== undefined;const entry = (value: string,@@ -257,9 +254,6 @@ export function SettingsPage({ extraDeviceTabs = [] }: SettingsPageProps = {}) {MessagesSquare,<ChannelsTab />,),- ...(appsAvailable- ? [entry("apps", t(($) => $.page.tabs.apps), Plug, <ConnectedAppsTab />)]- : []),entry("mcp", t(($) => $.page.tabs.mcp), Server, <McpTab />, {adminOnly: true,}),@@ -294,10 +288,14 @@ export function SettingsPage({ extraDeviceTabs = [] }: SettingsPageProps = {}) {// Wakeup defaults moved to the issue wakeups list; old links land there.const wakeupsMoved = location.tab === "wakeups";const wakeupsTarget = wakeupsHref(paths.autopilots());+ // The workspace's apps and accounts moved to their own page.+ const appsMoved = location.tab === "apps";+ const appsTarget = movedAppsHref(paths.apps(), navigation.searchParams, location.section);const { replace } = navigation;useEffect(() => {if (wakeupsMoved) replace(wakeupsTarget);- }, [wakeupsMoved, wakeupsTarget, replace]);+ else if (appsMoved) replace(appsTarget);+ }, [wakeupsMoved, wakeupsTarget, appsMoved, appsTarget, replace]);const candidate =location.tab === "billing" && !billingEnabled ? "workspace" : location.tab;const active =diff --git a/packages/views/settings/components/use-settings-search-index.ts b/packages/views/settings/components/use-settings-search-index.tsindex 90ee8b2c88..e991219d4f 100644--- a/packages/views/settings/components/use-settings-search-index.ts+++ b/packages/views/settings/components/use-settings-search-index.ts@@ -298,11 +298,6 @@ export function useSettingsSearchIndex(title: t(($) => $.voice_input.history.title),description: t(($) => $.voice_input.history.description),},- {- tab: "apps",- title: t(($) => $.page.tabs.apps),- description: t(($) => $.connected_apps.description),- },// Workspace{ tab: "workspace", anchor: "name", title: t(($) => $.workspace.name_label) },{ tab: "workspace", anchor: "description", title: t(($) => $.workspace.description_label) },diff --git a/packages/views/test/shard-timings.json b/packages/views/test/shard-timings.jsonindex a819ea7ea2..ab7c16c5c3 100644--- a/packages/views/test/shard-timings.json+++ b/packages/views/test/shard-timings.json@@ -521,7 +521,6 @@"settings/components/code-tab.test.tsx": 1694,"settings/components/code-vcs.test.tsx": 1734,"settings/components/composio-tab.test.tsx": 769,- "settings/components/connected-apps-tab.test.tsx": 1289,"settings/components/delete-workspace-dialog.test.tsx": 1228,"settings/components/dingtalk-tab.test.tsx": 1469,"settings/components/issue-statuses-tab.test.tsx": 3724,diff --git a/server/cmd/migrate/main.go b/server/cmd/migrate/main.goindex 033c18873d..b7d3840a6f 100644--- a/server/cmd/migrate/main.go+++ b/server/cmd/migrate/main.go@@ -140,6 +140,7 @@ var pgBigmOperatorClass = extensionOperatorClass{// they are still pending: a fresh self-hosted install, which is exactly where an// interrupted build would otherwise leave a permanently unusable index.var concurrentIndexCleanups = map[string]string{+ "729_remote_app_connection_workspace_idx": "uq_remote_app_connection_owner_ws","720_remote_app_oauth_client_idx": "uq_remote_app_oauth_client_app_redirect","721_remote_app_connection_owner_idx": "uq_remote_app_connection_owner","676_chat_wakeup_due_idx": "idx_chat_wakeup_due",@@ -432,6 +433,7 @@ var concurrentIndexCleanups = map[string]string{// the retry, while a bare CREATE would stay wedged on "already exists"; both// cases need direction-specific cleanup before the rollback can retry safely.var concurrentDownIndexCleanups = map[string]string{+ "730_drop_remote_app_connection_owner_idx": "uq_remote_app_connection_owner","144_drop_agent_task_queue_chat_pending_v1": "idx_agent_task_queue_chat_pending","171_drop_legacy_label_namespace_index": "issue_label_workspace_name_lower_idx","256_drop_agent_task_queue_chat_pending_v2": "idx_agent_task_queue_chat_pending_v2",diff --git a/server/cmd/server/router.go b/server/cmd/server/router.goindex 7fc621deeb..c47df6e06e 100644--- a/server/cmd/server/router.go+++ b/server/cmd/server/router.go@@ -1406,6 +1406,7 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus// key and applies account rules and confirmations.appsCfg := connectedapps.Config{Queries: queries,+ TxStarter: pool,Composio: svc,TokenSecret: connectedapps.DeriveTokenSecret(stateSecret),PublicBaseURL: callbackBase,@@ -2132,6 +2133,7 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Busr.Get("/toolkits", h.ListComposioToolkits)r.Get("/connections", h.ListComposioConnections)r.Delete("/connections/{id}", h.DeleteComposioConnection)+ r.Get("/connections/{id}/impact", h.GetComposioConnectionImpact)})// User-scoped invitation routes (no workspace context required)@@ -2807,6 +2809,8 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Busr.Post("/team/connect", h.ConnectTeamApp)r.Get("/team/impact", h.GetTeamAppImpact)r.Delete("/team/connections/{id}", h.DisconnectTeamApp)+ r.Post("/team/requests", h.RequestTeamApp)+ r.Delete("/team/requests", h.DismissTeamAppRequests)r.Post("/personal/connect", h.ConnectPersonalApp)r.Get("/rules", h.GetAppRules)r.Put("/rules", h.UpdateAppRules)diff --git a/server/internal/connectedapps/catalog.go b/server/internal/connectedapps/catalog.goindex 10f532280c..75e454bd1d 100644--- a/server/internal/connectedapps/catalog.go+++ b/server/internal/connectedapps/catalog.go@@ -34,6 +34,8 @@ const (// classes; every other app works through automatic classification.type CuratedApp struct {Slug string+ // Name is how people see the app in inbox items and notes.+ Name string// Scope is the recommended account type: team, personal, or "" for either.Scope string// Overrides pins the class of specific tools, keyed by upper-case tool slug.@@ -41,33 +43,33 @@ type CuratedApp struct {}var curatedApps = []CuratedApp{- {Slug: "gmail", Scope: ScopePersonal},- {Slug: "googlecalendar", Scope: ScopePersonal, Overrides: map[string]string{+ {Slug: "gmail", Name: "Gmail", Scope: ScopePersonal},+ {Slug: "googlecalendar", Name: "Google Calendar", Scope: ScopePersonal, Overrides: map[string]string{"GOOGLECALENDAR_CREATE_EVENT": ClassSend,"GOOGLECALENDAR_UPDATE_EVENT": ClassSend,"GOOGLECALENDAR_PATCH_EVENT": ClassSend,"GOOGLECALENDAR_QUICK_ADD": ClassSend,"GOOGLECALENDAR_FIND_FREE_SLOTS": ClassRead,}},- {Slug: "outlook", Scope: ScopePersonal},- {Slug: "slack", Scope: ScopePersonal},- {Slug: "notion"},- {Slug: "googledrive"},- {Slug: "googledocs"},- {Slug: "googlesheets"},- {Slug: "confluence"},- {Slug: "linear"},- {Slug: "jira"},- {Slug: "asana"},- {Slug: "figma"},- {Slug: "mobbin", Scope: ScopePersonal},- {Slug: "sentry", Scope: ScopeTeam},- {Slug: "posthog", Scope: ScopeTeam},- {Slug: "hubspot", Scope: ScopeTeam},- {Slug: "zendesk", Scope: ScopeTeam},- {Slug: "intercom", Scope: ScopeTeam},- {Slug: "stripe", Scope: ScopeTeam},- {Slug: "airtable", Scope: ScopeTeam},+ {Slug: "outlook", Name: "Outlook", Scope: ScopePersonal},+ {Slug: "slack", Name: "Slack", Scope: ScopePersonal},+ {Slug: "notion", Name: "Notion"},+ {Slug: "googledrive", Name: "Google Drive"},+ {Slug: "googledocs", Name: "Google Docs"},+ {Slug: "googlesheets", Name: "Google Sheets"},+ {Slug: "confluence", Name: "Confluence"},+ {Slug: "linear", Name: "Linear"},+ {Slug: "jira", Name: "Jira"},+ {Slug: "asana", Name: "Asana"},+ {Slug: "figma", Name: "Figma"},+ {Slug: "mobbin", Name: "Mobbin", Scope: ScopePersonal},+ {Slug: "sentry", Name: "Sentry", Scope: ScopeTeam},+ {Slug: "posthog", Name: "PostHog", Scope: ScopeTeam},+ {Slug: "hubspot", Name: "HubSpot", Scope: ScopeTeam},+ {Slug: "zendesk", Name: "Zendesk", Scope: ScopeTeam},+ {Slug: "intercom", Name: "Intercom", Scope: ScopeTeam},+ {Slug: "stripe", Name: "Stripe", Scope: ScopeTeam},+ {Slug: "airtable", Name: "Airtable", Scope: ScopeTeam},}var curatedBySlug = func() map[string]CuratedApp {diff --git a/server/internal/connectedapps/catalog_test.go b/server/internal/connectedapps/catalog_test.gonew file mode 100644index 0000000000..b3286b6bc9--- /dev/null+++ b/server/internal/connectedapps/catalog_test.go@@ -0,0 +1,24 @@+package connectedapps++import "testing"++func TestCuratedAppsHaveNames(t *testing.T) {+ for _, app := range curatedApps {+ if app.Name == "" {+ t.Errorf("curated app %q has no name", app.Slug)+ }+ }+}++func TestAppLabel(t *testing.T) {+ for slug, want := range map[string]string{+ "posthog": "PostHog",+ "GoogleCalendar": "Google Calendar",+ "hubspot": "HubSpot",+ "some_app": "Some App",+ } {+ if got := appLabel(slug); got != want {+ t.Errorf("appLabel(%q) = %q, want %q", slug, got, want)+ }+ }+}diff --git a/server/internal/connectedapps/gateway.go b/server/internal/connectedapps/gateway.goindex 542199e235..301e5d9f27 100644--- a/server/internal/connectedapps/gateway.go+++ b/server/internal/connectedapps/gateway.go@@ -225,7 +225,9 @@ func (s *Service) dispatch(ctx context.Context, rn *run, req rpcRequest) (rpcResconst 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. " +"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."+ "If an account is not connected, use apps_request_connection and end your turn; you will be resumed after it is connected. " ++ "If you need an app that apps_list does not show, call apps_request_connection with its slug (e.g. googlecalendar) and end your turn: " ++ "the person who started the run may add it to you and connect their account."func gatewayTools() []map[string]any {str := func(desc string) map[string]any { return map[string]any{"type": "string", "description": desc} }@@ -271,11 +273,11 @@ func gatewayTools() []map[string]any {},{"name": toolRequestConnection,- "description": "Ask the person who triggered this run to connect their account for an app that shows not_connected. End your turn after calling it.",+ "description": "Ask for an app account that shows not_connected: your own account goes to the person who triggered this run, a team account to the workspace admins. Also adds an app you do not have yet. End your turn after calling it.","inputSchema": map[string]any{"type": "object","properties": map[string]any{- "app": str("App slug from apps_list"),+ "app": str("App slug from apps_list, or the slug of an app you do not have yet, e.g. googlecalendar"),"summary": str("One sentence: why you need this app."),},"required": []string{"app"},@@ -561,22 +563,72 @@ func (s *Service) toolRequestConnection(ctx context.Context, rn *run, slug, summslug = NormalizeSlug(slug)app, ok := rn.apps[slug]if !ok {- return textResult(fmt.Sprintf("app %q is not available to you in this run", slug), true)+ return s.requestNewApp(ctx, rn, slug, summary)}if _, err := s.resolveAccount(ctx, rn.workspaceID, rn.triggeredBy, slug, app.AccountScope); err == nil {return textResult("the account is already connected; use the app directly", false)}- if app.AccountScope == ScopeTeam {- return textResult("this app uses the team account, which a workspace admin connects in Settings › Apps. Tell the person in your reply and end your turn.", true)- }if !rn.triggeredBy.Valid {+ if app.AccountScope == ScopeTeam {+ return textResult("no person started this run, so the request cannot wait on it. A workspace admin connects the team account in Apps › Accounts; say so in your reply and end your turn.", true)+ }return textResult("no person triggered this run, so nobody can be asked to connect an account", true)}- req, err := s.createRequest(ctx, rn, "connect", app, "", "", map[string]any{}, summary)+ req, err := s.createRequest(ctx, rn, KindConnect, app, "", "", map[string]any{}, summary)if err != nil {return textResult("could not send the connection request", true)}- return textResult(fmt.Sprintf("requested: %s is asked to connect %s (request %s). End your turn now; you will be resumed after they connect.", "the person who triggered this run", slug, util.UUIDToString(req.ID)), false)+ who := "the person who triggered this run is"+ if app.AccountScope == ScopeTeam {+ who = "the workspace admins are"+ }+ return textResult(fmt.Sprintf("requested: %s asked to connect %s (request %s). End your turn now; you will be resumed after it is connected.", who, slug, util.UUIDToString(req.ID)), false)+}++// requestNewApp asks the person who triggered the run to add an app the agent+// does not have, through their personal account. Team accounts act as the+// whole workspace, so only an admin attaches one, in the agent's settings.+func (s *Service) requestNewApp(ctx context.Context, rn *run, slug, summary string) map[string]any {+ if slug == "" {+ return textResult("app is required", true)+ }+ if !rn.catalog.Allows(slug) {+ return textResult(fmt.Sprintf("app %q is not available in this workspace", slug), true)+ }+ if !rn.triggeredBy.Valid {+ return textResult("no person triggered this run, so nobody can be asked to add an app", true)+ }+ known, err := s.knownToolkit(ctx, slug)+ if err != nil {+ return textResult("could not look up this app right now; try again later", true)+ }+ if !known {+ return textResult(fmt.Sprintf("there is no app with the slug %q", slug), true)+ }+ if s.resumer == nil || !s.resumer.CanManageAgent(ctx, rn.workspaceID, rn.agent.ID, rn.triggeredBy) {+ return textResult(fmt.Sprintf("%s is not on your app list, and the person who started this run cannot add apps to you. "++ "Do not retry; say so in your reply and end your turn.", appLabel(slug)), true)+ }+ app := db.AgentApp{ToolkitSlug: slug, AccountScope: ScopePersonal}+ req, err := s.createRequest(ctx, rn, KindConnect, app, "", "", map[string]any{}, summary)+ if err != nil {+ return textResult("could not send the request", true)+ }+ return textResult(fmt.Sprintf("requested: the person who triggered this run is asked to add %s to you and connect their account (request %s). "++ "End your turn now; you will be resumed after they do.", slug, util.UUIDToString(req.ID)), false)+}++// knownToolkit reports whether slug names a real app: a curated one, or one+// the provider lists tools for.+func (s *Service) knownToolkit(ctx context.Context, slug string) (bool, error) {+ if _, ok := Curated(slug); ok {+ return true, nil+ }+ tools, err := s.composio.ListToolkitTools(ctx, slug)+ if err != nil {+ return false, err+ }+ return len(tools) > 0, nil}func truncate(s string, n int) string {diff --git a/server/internal/connectedapps/remote.go b/server/internal/connectedapps/remote.goindex 4f3ef4075e..edd36d9469 100644--- a/server/internal/connectedapps/remote.go+++ b/server/internal/connectedapps/remote.go@@ -215,27 +215,31 @@ type remoteState struct {Client string `json:"c"`Verifier string `json:"v"`ReturnTo string `json:"r,omitempty"`- Exp int64 `json:"e"`+ // Workspace is the workspace the account belongs to.+ Workspace string `json:"w,omitempty"`+ Exp int64 `json:"e"`}// RemoteConnectResult is what a completed (or failed) handshake was for.type RemoteConnectResult struct {- Slug string- Scope string- Owner pgtype.UUID- Actor pgtype.UUID- ReturnTo string+ Slug string+ Scope string+ Owner pgtype.UUID+ Actor pgtype.UUID+ Workspace pgtype.UUID+ ReturnTo string}// BeginRemoteConnect returns the authorization URL that connects an account-// for a remote app. owner is the workspace for a team account and the actor-// for a personal one; the caller has already checked the actor may do this.-func (s *Service) BeginRemoteConnect(ctx context.Context, slug, scope string, owner, actor pgtype.UUID, returnTo string) (string, error) {+// for a remote app in workspaceID. owner is the workspace for a team account+// and the actor for a personal one; the caller has already checked the actor+// may do this.+func (s *Service) BeginRemoteConnect(ctx context.Context, slug, scope string, workspaceID, owner, actor pgtype.UUID, returnTo string) (string, error) {app, ok := s.RemoteApp(slug)if !ok {return "", composiointeg.ErrToolkitNotSupported}- if !ValidScope(scope) || !owner.Valid || !actor.Valid {+ if !ValidScope(scope) || !owner.Valid || !actor.Valid || !workspaceID.Valid {return "", errors.New("connectedapps: invalid remote connect owner")}if !composiointeg.SafeReturnPath(returnTo) {@@ -252,7 +256,7 @@ func (s *Service) BeginRemoteConnect(ctx context.Context, slug, scope string, owstate, err := s.sealState(remoteState{App: app.Slug, Scope: scope, Owner: util.UUIDToString(owner), Actor: util.UUIDToString(actor),Client: util.UUIDToString(client.ID), Verifier: verifier, ReturnTo: returnTo,- Exp: s.now().Add(remoteStateTTL).Unix(),+ Workspace: util.UUIDToString(workspaceID), Exp: s.now().Add(remoteStateTTL).Unix(),})if err != nil {return "", err@@ -283,7 +287,14 @@ func (s *Service) CompleteRemoteConnect(ctx context.Context, rawState, code, oauif err1 != nil || err2 != nil || err3 != nil || !ok || !ValidScope(st.Scope) {return RemoteConnectResult{}, ErrRemoteState}- result := RemoteConnectResult{Slug: app.Slug, Scope: st.Scope, Owner: owner, Actor: actor, ReturnTo: st.ReturnTo}+ workspace := owner+ if st.Scope != ScopeTeam {+ var err4 error+ if workspace, err4 = util.ParseUUID(st.Workspace); err4 != nil {+ return RemoteConnectResult{}, ErrRemoteState+ }+ }+ result := RemoteConnectResult{Slug: app.Slug, Scope: st.Scope, Owner: owner, Actor: actor, Workspace: workspace, ReturnTo: st.ReturnTo}if oauthError != "" || code == "" {return result, fmt.Errorf("connectedapps: authorization not granted")}@@ -323,6 +334,7 @@ func (s *Service) CompleteRemoteConnect(ctx context.Context, rawState, code, oaurow, err := s.q.UpsertRemoteAppConnection(ctx, db.UpsertRemoteAppConnectionParams{AppSlug: app.Slug, Scope: st.Scope, OwnerID: owner, ConnectedBy: actor, OauthClientID: client.ID,AccessToken: access, RefreshToken: refresh, ExpiresAt: expiry(s.now(), tokens.ExpiresIn),+ WorkspaceID: workspace,})if err != nil {return result, fmt.Errorf("connectedapps: save remote account: %w", err)@@ -614,7 +626,7 @@ func (s *Service) resolveRemoteAccount(ctx context.Context, workspaceID, trigger}owner = triggeredBy}- row, err := s.q.GetActiveRemoteAppConnection(ctx, db.GetActiveRemoteAppConnectionParams{AppSlug: slug, Scope: scope, OwnerID: owner})+ row, err := s.q.GetActiveRemoteAppConnection(ctx, db.GetActiveRemoteAppConnectionParams{AppSlug: slug, Scope: scope, OwnerID: owner, WorkspaceID: workspaceID})if isNoRows(err) {return account{}, ErrAccountMissing}diff --git a/server/internal/connectedapps/requests.go b/server/internal/connectedapps/requests.goindex 4307958d4b..2ec013665f 100644--- a/server/internal/connectedapps/requests.go+++ b/server/internal/connectedapps/requests.go@@ -16,6 +16,7 @@ import ("github.com/multica-ai/multica/server/internal/util"db "github.com/multica-ai/multica/server/pkg/db/generated""github.com/multica-ai/multica/server/pkg/dbid"+ "github.com/multica-ai/multica/server/pkg/protocol")// EventRequestChanged tells clients to refetch the requests of an issue or@@ -76,19 +77,101 @@ func (s *Service) createRequest(ctx context.Context, rn *run, kind string, app dif err != nil {return db.AppActionRequest{}, err}- notif := NotifActionRequested- if kind == KindConnect {- notif = NotifConnectRequested+ switch {+ case isTeamConnect(req):+ s.notifyAdmins(ctx, req)+ case kind == KindConnect:+ s.notify(ctx, req, NotifConnectRequested)+ default:+ s.notify(ctx, req, NotifActionRequested)}- s.notify(ctx, req, notif)s.publishChange(req)return req, nil}+// isTeamConnect reports a request for the workspace's team account. Any+// admin may answer it, not only its approver, who is the person waiting.+func isTeamConnect(req db.AppActionRequest) bool {+ return req.Kind == KindConnect && req.AccountScope == ScopeTeam+}++// AskTeamAccount records a member asking the admins for a team account for+// slug, outside any run. Asking again while the ask is open changes nothing.+func (s *Service) AskTeamAccount(ctx context.Context, workspaceID, memberID pgtype.UUID, slug string, agentID pgtype.UUID) (db.AppActionRequest, error) {+ slug = NormalizeSlug(slug)+ if existing, err := s.q.FindPendingTeamAsk(ctx, db.FindPendingTeamAskParams{+ WorkspaceID: workspaceID, ToolkitSlug: slug, ApproverUserID: memberID,+ }); err == nil {+ return existing, nil+ } else if !isNoRows(err) {+ return db.AppActionRequest{}, err+ }+ req, err := s.q.CreateAppActionRequest(ctx, db.CreateAppActionRequestParams{+ WorkspaceID: workspaceID,+ Kind: KindConnect,+ AgentID: agentID,+ ApproverUserID: memberID,+ AccountScope: ScopeTeam,+ ToolkitSlug: slug,+ ActionClass: ClassSend,+ Arguments: []byte("{}"),+ ExpiresAt: pgtype.Timestamptz{Time: s.now().Add(TeamAskTTL), Valid: true},+ })+ if err != nil {+ return db.AppActionRequest{}, err+ }+ s.notifyAdmins(ctx, req)+ s.publishChange(req)+ return req, nil+}++// WithdrawTeamAsk cancels the member's own open ask for slug's team account.+func (s *Service) WithdrawTeamAsk(ctx context.Context, workspaceID, memberID pgtype.UUID, slug string) error {+ req, err := s.q.FindPendingTeamAsk(ctx, db.FindPendingTeamAskParams{+ WorkspaceID: workspaceID, ToolkitSlug: NormalizeSlug(slug), ApproverUserID: memberID,+ })+ if isNoRows(err) {+ return nil+ }+ if err != nil {+ return err+ }+ s.withdraw(ctx, req)+ s.archiveAdminNotifications(ctx, req)+ return nil+}++func (s *Service) archiveAdminNotifications(ctx context.Context, req db.AppActionRequest) {+ rows, err := s.q.ArchiveAppRequestInbox(ctx, db.ArchiveAppRequestInboxParams{+ WorkspaceID: req.WorkspaceID, RequestID: util.UUIDToString(req.ID),+ })+ if err != nil {+ slog.Warn("connectedapps: archive withdrawn request notifications failed", "request_id", util.UUIDToString(req.ID), "error", err)+ return+ }+ if s.bus == nil {+ return+ }+ for _, row := range rows {+ if row.RecipientType != "member" {+ continue+ }+ s.bus.Publish(events.Event{+ Type: protocol.EventInboxBatchArchived,+ WorkspaceID: util.UUIDToString(req.WorkspaceID),+ Payload: map[string]any{+ "recipient_id": util.UUIDToString(row.RecipientID),+ "count": int64(1),+ "reason": "app_request_withdrawn",+ },+ })+ }+}+// Approve executes an approved request with args (nil keeps the agent's) and// resumes the agent with the outcome. Only the approver may approve.func (s *Service) Approve(ctx context.Context, workspaceID, actorID, requestID pgtype.UUID, args map[string]any) (db.AppActionRequest, error) {- req, err := s.pendingForApprover(ctx, workspaceID, actorID, requestID)+ req, asAdmin, err := s.pendingForDecider(ctx, workspaceID, actorID, requestID)if err != nil {return db.AppActionRequest{}, err}@@ -96,8 +179,17 @@ func (s *Service) Approve(ctx context.Context, workspaceID, actorID, requestID ps.withdraw(ctx, req)return db.AppActionRequest{}, ErrNoLongerAllowed}+ addsApp := falseif req.Kind == KindConnect {- if _, err := s.resolveAccount(ctx, workspaceID, actorID, req.ToolkitSlug, req.AccountScope); err != nil {+ if _, has := s.agentApp(ctx, req.AgentID, req.ToolkitSlug); req.TaskID.Valid && !has {+ if req.AccountScope != ScopePersonal || !s.mayManage(ctx, req.WorkspaceID, req.AgentID, actorID) ||+ !s.Catalog(ctx, workspaceID).Allows(req.ToolkitSlug) {+ s.withdraw(ctx, req)+ return db.AppActionRequest{}, ErrCannotAddApp+ }+ addsApp = true+ }+ if _, err := s.resolveAccount(ctx, workspaceID, req.ApproverUserID, req.ToolkitSlug, req.AccountScope); err != nil {return db.AppActionRequest{}, ErrAccountMissing}} else if acct, err := s.resolveAccount(ctx, workspaceID, actorID, req.ToolkitSlug, req.AccountScope); err == nil &&@@ -113,7 +205,7 @@ func (s *Service) Approve(ctx context.Context, workspaceID, actorID, requestID p}decided, err := s.q.DecideAppActionRequest(ctx, db.DecideAppActionRequestParams{ID: requestID, WorkspaceID: workspaceID, Status: "approved", DecidedBy: actorID,- ApprovedArguments: approvedArgs,+ ApprovedArguments: approvedArgs, AsAdmin: asAdmin,})if isNoRows(err) {return db.AppActionRequest{}, ErrNotPending@@ -122,10 +214,37 @@ func (s *Service) Approve(ctx context.Context, workspaceID, actorID, requestID preturn db.AppActionRequest{}, err}if decided.Kind == KindConnect {+ if !decided.TaskID.Valid {+ s.publishChange(decided)+ s.notify(ctx, decided, NotifActionResult)+ return decided, nil+ }+ note := fmt.Sprintf("The %s account you asked for (request %s) is now connected. Continue the task and use the app.",+ appLabel(decided.ToolkitSlug), util.UUIDToString(decided.ID))+ if isTeamConnect(decided) {+ note = fmt.Sprintf("A workspace admin connected the team %s account you asked for (request %s). Continue the task and use the app.",+ appLabel(decided.ToolkitSlug), util.UUIDToString(decided.ID))+ }+ if addsApp {+ if err := s.addPersonalApp(ctx, decided, actorID); err != nil {+ slog.Warn("connectedapps: add app on approval failed", "request_id", util.UUIDToString(decided.ID), "error", err)+ if row, serr := s.q.SetAppActionRequestOutcome(ctx, db.SetAppActionRequestOutcomeParams{+ ID: decided.ID, WorkspaceID: decided.WorkspaceID, Status: "failed",+ Error: pgtype.Text{String: "the app could not be added to the agent", Valid: true},+ }); serr == nil {+ decided = row+ }+ s.publishChange(decided)+ s.resume(ctx, decided, actorID, fmt.Sprintf(+ "The person approved adding %s to you (request %s), but adding it failed. Continue without it and explain in your reply.",+ appLabel(decided.ToolkitSlug), util.UUIDToString(decided.ID)))+ return decided, nil+ }+ note = fmt.Sprintf("The person added %s to your apps and connected their account (request %s). Continue the task and use the app.",+ appLabel(decided.ToolkitSlug), util.UUIDToString(decided.ID))+ }s.publishChange(decided)- s.resume(ctx, decided, actorID, fmt.Sprintf(- "The %s account you asked for (request %s) is now connected. Continue the task and use the app.",- appLabel(decided.ToolkitSlug), util.UUIDToString(decided.ID)))+ s.resume(ctx, decided, actorID, note)return decided, nil}@@ -138,9 +257,9 @@ func (s *Service) Approve(ctx context.Context, workspaceID, actorID, requestID p// ResolveConnectRequests completes the connection requests a member was// asked to answer for slug, once they connected it, and resumes each agent.// It runs from the OAuth callback, so nobody has to come back and confirm.-func (s *Service) ResolveConnectRequests(ctx context.Context, userID pgtype.UUID, slug string) {+func (s *Service) ResolveConnectRequests(ctx context.Context, workspaceID, userID pgtype.UUID, slug string) {rows, err := s.q.ListPendingConnectRequestsForUser(ctx, db.ListPendingConnectRequestsForUserParams{- ApproverUserID: userID, ToolkitSlug: NormalizeSlug(slug),+ WorkspaceID: workspaceID, ApproverUserID: userID, ToolkitSlug: NormalizeSlug(slug),})if err != nil {slog.Warn("connectedapps: list connect requests failed", "toolkit", slug, "error", err)@@ -148,21 +267,58 @@ func (s *Service) ResolveConnectRequests(ctx context.Context, userID pgtype.UUID}for _, r := range rows {if _, err := s.Approve(ctx, r.WorkspaceID, userID, r.ID, nil); err != nil &&- !errors.Is(err, ErrNotPending) && !errors.Is(err, ErrNoLongerAllowed) {+ !errors.Is(err, ErrNotPending) && !errors.Is(err, ErrNoLongerAllowed) && !errors.Is(err, ErrCannotAddApp) {slog.Warn("connectedapps: resolve connect request failed", "request_id", util.UUIDToString(r.ID), "error", err)}}}+// ResolveTeamConnectRequests answers everything waiting for the workspace's+// team account for slug once an admin connected it: agents resume, members+// who asked are told.+func (s *Service) ResolveTeamConnectRequests(ctx context.Context, workspaceID, adminID pgtype.UUID, slug string) {+ rows, err := s.q.ListPendingTeamConnectRequests(ctx, db.ListPendingTeamConnectRequestsParams{+ WorkspaceID: workspaceID, ToolkitSlug: NormalizeSlug(slug),+ })+ if err != nil {+ slog.Warn("connectedapps: list team connect requests failed", "toolkit", slug, "error", err)+ return+ }+ for _, r := range rows {+ if _, err := s.Approve(ctx, workspaceID, adminID, r.ID, nil); err != nil &&+ !errors.Is(err, ErrNotPending) && !errors.Is(err, ErrNoLongerAllowed) && !errors.Is(err, ErrCannotAddApp) {+ slog.Warn("connectedapps: resolve team connect request failed", "request_id", util.UUIDToString(r.ID), "error", err)+ }+ }+}++// DeclineTeamConnectRequests is an admin declining everything waiting for+// the team account for slug.+func (s *Service) DeclineTeamConnectRequests(ctx context.Context, workspaceID, adminID pgtype.UUID, slug string) error {+ rows, err := s.q.ListPendingTeamConnectRequests(ctx, db.ListPendingTeamConnectRequestsParams{+ WorkspaceID: workspaceID, ToolkitSlug: NormalizeSlug(slug),+ })+ if err != nil {+ return err+ }+ for _, r := range rows {+ if _, err := s.Reject(ctx, workspaceID, adminID, r.ID, ""); err != nil && !errors.Is(err, ErrNotPending) {+ return err+ }+ }+ return nil+}+// Reject declines a request and resumes the agent so it can adapt.func (s *Service) Reject(ctx context.Context, workspaceID, actorID, requestID pgtype.UUID, reason string) (db.AppActionRequest, error) {- if _, err := s.pendingForApprover(ctx, workspaceID, actorID, requestID); err != nil {+ _, asAdmin, err := s.pendingForDecider(ctx, workspaceID, actorID, requestID)+ if err != nil {return db.AppActionRequest{}, err}reason = truncate(strings.TrimSpace(reason), 1000)decided, err := s.q.DecideAppActionRequest(ctx, db.DecideAppActionRequestParams{ID: requestID, WorkspaceID: workspaceID, Status: "rejected", DecidedBy: actorID,- Reason: pgtype.Text{String: reason, Valid: reason != ""},+ Reason: pgtype.Text{String: reason, Valid: reason != ""}, AsAdmin: asAdmin,})if isNoRows(err) {return db.AppActionRequest{}, ErrNotPending@@ -180,8 +336,17 @@ func (s *Service) Reject(ctx context.Context, workspaceID, actorID, requestID pg})}s.publishChange(decided)+ if !decided.TaskID.Valid {+ if decided.DecidedBy != decided.ApproverUserID {+ s.notify(ctx, decided, NotifActionResult)+ }+ return decided, nil+ }note := fmt.Sprintf("The person declined your %s request %s (%s).", appLabel(decided.ToolkitSlug), util.UUIDToString(decided.ID), decided.ToolSlug)- if decided.Kind == KindConnect {+ switch {+ case isTeamConnect(decided) && decided.DecidedBy != decided.ApproverUserID:+ note = fmt.Sprintf("A workspace admin declined to connect a team %s account (request %s).", appLabel(decided.ToolkitSlug), util.UUIDToString(decided.ID))+ case decided.Kind == KindConnect:note = fmt.Sprintf("The person declined to connect %s (request %s).", appLabel(decided.ToolkitSlug), util.UUIDToString(decided.ID))}if reason != "" {@@ -192,18 +357,30 @@ func (s *Service) Reject(ctx context.Context, workspaceID, actorID, requestID pgreturn decided, nil}-func (s *Service) pendingForApprover(ctx context.Context, workspaceID, actorID, requestID pgtype.UUID) (db.AppActionRequest, error) {- req, err := s.q.GetAppActionRequest(ctx, db.GetAppActionRequestParams{ID: requestID, WorkspaceID: workspaceID})+// pendingForDecider loads a pending request actorID may decide: its+// approver's, or, for a team account request, any admin's. asAdmin is set+// when the actor decides as an admin rather than as the approver.+func (s *Service) pendingForDecider(ctx context.Context, workspaceID, actorID, requestID pgtype.UUID) (req db.AppActionRequest, asAdmin bool, err error) {+ req, err = s.q.GetAppActionRequest(ctx, db.GetAppActionRequestParams{ID: requestID, WorkspaceID: workspaceID})if err != nil {- return db.AppActionRequest{}, ErrRequestNotFound+ return db.AppActionRequest{}, false, ErrRequestNotFound}if req.ApproverUserID != actorID {- return db.AppActionRequest{}, ErrNotApprover+ if !isTeamConnect(req) || !s.IsAdmin(ctx, workspaceID, actorID) {+ return db.AppActionRequest{}, false, ErrNotApprover+ }+ asAdmin = true}if req.Status != "pending" {- return db.AppActionRequest{}, ErrNotPending+ return db.AppActionRequest{}, false, ErrNotPending}- return req, nil+ return req, asAdmin, nil+}++// IsAdmin reports whether userID owns or administers the workspace.+func (s *Service) IsAdmin(ctx context.Context, workspaceID, userID pgtype.UUID) bool {+ member, err := s.q.GetMemberByUserAndWorkspace(ctx, db.GetMemberByUserAndWorkspaceParams{UserID: userID, WorkspaceID: workspaceID})+ return err == nil && (member.Role == "owner" || member.Role == "admin")}func personalOwner(req db.AppActionRequest) pgtype.UUID {@@ -307,9 +484,62 @@ func (s *Service) agentApp(ctx context.Context, agentID pgtype.UUID, slug stringreturn db.AgentApp{}, false}+// addPersonalApp attaches the requested app to the agent through the personal+// account of whoever triggers it, keeping the legacy allowlist in step. An+// app attached meanwhile keeps its account and level.+func (s *Service) addPersonalApp(ctx context.Context, req db.AppActionRequest, actorID pgtype.UUID) error {+ if s.tx == nil {+ return errors.New("connectedapps: no transaction starter configured")+ }+ agent, err := s.q.GetAgent(ctx, req.AgentID)+ if err != nil {+ return err+ }+ tx, err := s.tx.Begin(ctx)+ if err != nil {+ return err+ }+ defer tx.Rollback(ctx)+ qtx := s.q.WithTx(tx)+ apps, err := qtx.ListAgentApps(ctx, agent.ID)+ if err != nil {+ return err+ }+ slug := NormalizeSlug(req.ToolkitSlug)+ slugs := make([]string, 0, len(apps)+1)+ has := false+ for _, app := range apps {+ slugs = append(slugs, app.ToolkitSlug)+ has = has || NormalizeSlug(app.ToolkitSlug) == slug+ }+ if !has {+ if _, err := qtx.UpsertAgentApp(ctx, db.UpsertAgentAppParams{+ WorkspaceID: agent.WorkspaceID, AgentID: agent.ID, ToolkitSlug: slug,+ AccountScope: ScopePersonal, Level: DefaultLevel(agent.PermissionMode), CreatedBy: actorID,+ }); err != nil {+ return err+ }+ slugs = append(slugs, slug)+ }+ if err := qtx.SetAgentComposioToolkitAllowlist(ctx, db.SetAgentComposioToolkitAllowlistParams{ID: agent.ID, Slugs: slugs}); err != nil {+ return err+ }+ return tx.Commit(ctx)+}++func (s *Service) mayManage(ctx context.Context, workspaceID, agentID, userID pgtype.UUID) bool {+ return s.resumer != nil && s.resumer.CanManageAgent(ctx, workspaceID, agentID, userID)+}+// mayAct reports whether the approver is still a member who may run the// agent. Membership and agent access can change while a request waits.func (s *Service) mayAct(ctx context.Context, req db.AppActionRequest) bool {+ if !req.TaskID.Valid {+ _, err := s.q.GetMemberByUserAndWorkspace(ctx, db.GetMemberByUserAndWorkspaceParams{+ UserID: req.ApproverUserID, WorkspaceID: req.WorkspaceID,+ })+ return err == nil+ }return s.mayUseAgent(ctx, req.WorkspaceID, req.AgentID, req.ApproverUserID)}@@ -338,7 +568,8 @@ func (s *Service) resume(ctx context.Context, req db.AppActionRequest, actorID pslog.Info("connectedapps: approver can no longer run the agent; not resuming", "request_id", util.UUIDToString(req.ID))return}- if err := s.resumer.ResumeAfterDecision(ctx, req, actorID, note); err != nil {+ // The run continues as the person who started it, whoever decided.+ if err := s.resumer.ResumeAfterDecision(ctx, req, req.ApproverUserID, note); err != nil {slog.Warn("connectedapps: resume agent failed", "request_id", util.UUIDToString(req.ID), "error", err)}}@@ -399,6 +630,9 @@ func (s *Service) publishChange(req db.AppActionRequest) {}func appLabel(slug string) string {+ if app, ok := Curated(slug); ok {+ return app.Name+ }if name := runtimeapps.DisplayNameForToolkitSlug(slug); name != "" {return name}@@ -410,11 +644,45 @@ func appLabel(slug string) string {// answers. Results follow the recipient's agent-activity preference; the// inbox type registry owns both rules.func (s *Service) notify(ctx context.Context, req db.AppActionRequest, notifType string) {+ s.deliver(ctx, req, notifType, req.ApproverUserID)+}++// notifyAdmins tells the workspace's admins a team account is wanted. Only+// the first open request for an app notifies: the rest wait in the same+// place, and connecting the account answers them all.+func (s *Service) notifyAdmins(ctx context.Context, req db.AppActionRequest) {+ open, err := s.q.ListPendingTeamConnectRequests(ctx, db.ListPendingTeamConnectRequestsParams{+ WorkspaceID: req.WorkspaceID, ToolkitSlug: req.ToolkitSlug,+ })+ if err == nil && len(open) > 0 && open[0].ID != req.ID {+ return+ }+ admins, err := s.q.ListWorkspaceManagerUserIDs(ctx, req.WorkspaceID)+ if err != nil {+ slog.Warn("connectedapps: list admins for team request failed", "toolkit", req.ToolkitSlug, "error", err)+ return+ }+ for _, admin := range admins {+ if admin == req.ApproverUserID && !req.TaskID.Valid {+ continue+ }+ s.deliver(ctx, req, NotifConnectRequested, admin)+ }+}++func (s *Service) deliver(ctx context.Context, req db.AppActionRequest, notifType string, recipient pgtype.UUID) {actorType := pgtype.Text{String: "agent", Valid: true}+ actorID := req.AgentIDagentName := "Agent"if agent, err := s.q.GetAgent(ctx, req.AgentID); err == nil {agentName = agent.Name}+ if !req.TaskID.Valid {+ actorType, actorID, agentName = pgtype.Text{String: "member", Valid: true}, req.ApproverUserID, "A member"+ if user, err := s.q.GetUser(ctx, req.ApproverUserID); err == nil && user.Name != "" {+ agentName = user.Name+ }+ }title, issueStatus := agentName, ""if req.IssueID.Valid {if issue, err := s.q.GetIssue(ctx, req.IssueID); err == nil {@@ -424,6 +692,8 @@ func (s *Service) notify(ctx context.Context, req db.AppActionRequest, notifTypeif chat, err := s.q.GetChatSession(ctx, req.ChatSessionID); err == nil && chat.Title != "" {title = chat.Title}+ } else if !req.TaskID.Valid {+ title = appLabel(req.ToolkitSlug)}var body stringseverity := "action_required"@@ -431,6 +701,12 @@ func (s *Service) notify(ctx context.Context, req db.AppActionRequest, notifTypecase NotifActionResult:severity = "info"switch {+ case !req.TaskID.Valid && req.Status == "approved":+ body = fmt.Sprintf("An admin connected the team %s account you asked for", appLabel(req.ToolkitSlug))+ case !req.TaskID.Valid && req.Status == "rejected":+ body = fmt.Sprintf("An admin declined your request for a team %s account", appLabel(req.ToolkitSlug))+ case !req.TaskID.Valid:+ body = fmt.Sprintf("Your request for a team %s account expired without an answer", appLabel(req.ToolkitSlug))case req.Status == "blocked":body = fmt.Sprintf("A rule blocked %s from running %s · %s", agentName, appLabel(req.ToolkitSlug), req.ToolSlug)case req.Kind == KindConnect:@@ -440,6 +716,11 @@ func (s *Service) notify(ctx context.Context, req db.AppActionRequest, notifType}case NotifConnectRequested:body = fmt.Sprintf("%s asks you to connect %s", agentName, appLabel(req.ToolkitSlug))+ if isTeamConnect(req) {+ body = fmt.Sprintf("%s asks for a team %s account", agentName, appLabel(req.ToolkitSlug))+ } else if _, has := s.agentApp(ctx, req.AgentID, req.ToolkitSlug); !has {+ body = fmt.Sprintf("%s asks you to add %s and connect your account", agentName, appLabel(req.ToolkitSlug))+ }case NotifActionReminder:body = fmt.Sprintf("%s is still waiting for your confirmation on %s · %s; it expires in 2 hours", agentName, appLabel(req.ToolkitSlug), req.ToolSlug)default:@@ -453,7 +734,8 @@ func (s *Service) notify(ctx context.Context, req db.AppActionRequest, notifType"toolkit_slug": req.ToolkitSlug,"tool_slug": req.ToolSlug,"action_class": req.ActionClass,- "agent_id": util.UUIDToString(req.AgentID),+ "agent_id": util.UUIDToPtr(req.AgentID),+ "account_scope": req.AccountScope,"chat_session_id": util.UUIDToPtr(req.ChatSessionID),"summary": req.Summary,"expires_at": util.TimestampToString(req.ExpiresAt),@@ -463,14 +745,14 @@ func (s *Service) notify(ctx context.Context, req db.AppActionRequest, notifTypeID: dbid.NewV7(),WorkspaceID: req.WorkspaceID,RecipientType: "member",- RecipientID: req.ApproverUserID,+ RecipientID: recipient,Type: notifType,Severity: severity,IssueID: req.IssueID,Title: title,Body: pgtype.Text{String: body, Valid: true},ActorType: actorType,- ActorID: req.AgentID,+ ActorID: actorID,Details: details,},IssueStatus: &issueStatus,diff --git a/server/internal/connectedapps/service.go b/server/internal/connectedapps/service.goindex dc2e003114..9c81872b70 100644--- a/server/internal/connectedapps/service.go+++ b/server/internal/connectedapps/service.go@@ -36,6 +36,10 @@ const RequestTTL = 24 * time.Hour// waits longer than a confirmation.const ConnectRequestTTL = 7 * 24 * time.Hour+// TeamAskTTL is how long a member's ask for a team account stays open. No+// run waits on it, so it lasts until an admin gets to it.+const TeamAskTTL = 30 * 24 * time.Hour+// DefaultCallsPerMinute caps the calls one account runs per minute.const DefaultCallsPerMinute = 30@@ -62,6 +66,10 @@ var (// ErrRateLimited: the account used its per-minute budget. The request// stays pending, so approving again a minute later runs it.ErrRateLimited = errors.New("connectedapps: the account is over its per-minute call budget")+ // ErrCannotAddApp: approving a request for an app the agent does not+ // have adds the app, and the approver may not edit the agent or the+ // catalog no longer allows the app. The request is withdrawn.+ ErrCannotAddApp = errors.New("connectedapps: the approver cannot add apps to this agent"))// Resumer continues the agent's work after a person decides on a request: a@@ -72,12 +80,18 @@ type Resumer interface {// 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+ // CanManageAgent reports whether userID may edit agentID, and so add+ // apps to it, by the same rule as the agent settings.+ CanManageAgent(ctx context.Context, workspaceID, agentID, userID pgtype.UUID) bool}// Config wires a Service.type Config struct {- Queries *db.Queries- Composio *composiointeg.Service+ Queries *db.Queries+ // TxStarter writes an app an approval adds to an agent together with+ // the agent's legacy allowlist. Without it, such approvals fail.+ TxStarter TxStarter+ Composio *composiointeg.Service// TokenSecret signs gateway tokens. Derive it with DeriveTokenSecret.TokenSecret []byte// PublicBaseURL is the API's public origin, e.g. "https://api.multica.ai".@@ -100,6 +114,7 @@ type Config struct {// Service is the connected-apps runtime: overlay, gateway, and confirmations.type Service struct {q *db.Queries+ tx TxStartercomposio *composiointeg.Servicesecret []bytegatewayURL string@@ -132,6 +147,7 @@ func New(cfg Config) (*Service, error) {}return &Service{q: cfg.Queries,+ tx: cfg.TxStarter,composio: cfg.Composio,secret: cfg.TokenSecret,gatewayURL: base + GatewayPath,@@ -225,13 +241,15 @@ type gatewayOverlay struct {// BuildTaskOverlay is the enqueue-time overlay for a run of agent. It carries// no credential: only the gateway address and which apps the agent has. The// claim handler adds the run's token (AuthorizeOverlay) once the task id is-// final. A zero result means the agent has no apps.+// final. A run a person started gets the gateway even when the agent has no+// apps, so it can ask that person for its first one. A zero result means+// there is nothing to mount.func (s *Service) BuildTaskOverlay(ctx context.Context, originatorUserID pgtype.UUID, agent db.Agent) (runtimeapps.MCPOverlayResult, error) {apps, err := s.q.ListAgentApps(ctx, agent.ID)if err != nil {return runtimeapps.MCPOverlayResult{}, fmt.Errorf("connectedapps: list agent apps: %w", err)}- if len(apps) == 0 {+ if len(apps) == 0 && !originatorUserID.Valid {return runtimeapps.MCPOverlayResult{}, nil}catalog := s.Catalog(ctx, agent.WorkspaceID)@@ -241,7 +259,7 @@ func (s *Service) BuildTaskOverlay(ctx context.Context, originatorUserID pgtype.}personal := map[string]db.UserComposioConnection{}if originatorUserID.Valid {- if personal, err = s.activePersonalAccounts(ctx, originatorUserID); err != nil {+ if personal, err = s.activePersonalAccounts(ctx, agent.WorkspaceID, originatorUserID); err != nil {return runtimeapps.MCPOverlayResult{}, err}}@@ -285,7 +303,7 @@ func (s *Service) BuildTaskOverlay(ctx context.Context, originatorUserID pgtype.AccountStatus: status,})}- if len(meta) == 0 {+ if len(meta) == 0 && !originatorUserID.Valid {return runtimeapps.MCPOverlayResult{}, nil}raw, err := json.Marshal(gatewayOverlay{MCPServers: servers})@@ -354,8 +372,8 @@ func (s *Service) activeTeamAccounts(ctx context.Context, workspaceID pgtype.UUIreturn out, nil}-func (s *Service) activePersonalAccounts(ctx context.Context, userID pgtype.UUID) (map[string]db.UserComposioConnection, error) {- rows, err := s.q.ListActiveUserComposioConnections(ctx, userID)+func (s *Service) activePersonalAccounts(ctx context.Context, workspaceID, userID pgtype.UUID) (map[string]db.UserComposioConnection, error) {+ rows, err := s.q.ListActiveUserComposioConnections(ctx, db.ListActiveUserComposioConnectionsParams{UserID: userID, WorkspaceID: workspaceID})if err != nil {return nil, fmt.Errorf("connectedapps: list personal accounts: %w", err)}@@ -402,7 +420,7 @@ func (s *Service) resolveAccount(ctx context.Context, workspaceID, triggeredBy pif !triggeredBy.Valid {return account{}, ErrAccountMissing}- personal, err := s.activePersonalAccounts(ctx, triggeredBy)+ personal, err := s.activePersonalAccounts(ctx, workspaceID, triggeredBy)if err != nil {return account{}, err}diff --git a/server/internal/handler/connected_apps.go b/server/internal/handler/connected_apps.goindex 9aab1529c6..7a28efbd3f 100644--- a/server/internal/handler/connected_apps.go+++ b/server/internal/handler/connected_apps.go@@ -45,14 +45,28 @@ type AgentAppResponse struct {Level string `json:"level"`}+// AppTeamRequestResponse is one app members asked the admins to connect a+// team account for.+type AppTeamRequestResponse struct {+ ToolkitSlug string `json:"toolkit_slug"`+ // RequestedBy lists everyone waiting, oldest first: whoever started each+ // waiting run, and members who asked.+ RequestedBy []string `json:"requested_by"`+ // AskedBy is the members who asked themselves, which they can withdraw.+ AskedBy []string `json:"asked_by"`+ AgentIDs []string `json:"agent_ids"`+ LastRequestedAt string `json:"last_requested_at"`+}+// AppsOverviewResponse backs Settings › Apps.type AppsOverviewResponse struct {- CatalogMode string `json:"catalog_mode"`- AllowedToolkits []string `json:"allowed_toolkits"`- CanManage bool `json:"can_manage"`- Team []AppConnectionResponse `json:"team"`- Personal []AppConnectionResponse `json:"personal"`- AgentApps []AgentAppResponse `json:"agent_apps"`+ CatalogMode string `json:"catalog_mode"`+ AllowedToolkits []string `json:"allowed_toolkits"`+ CanManage bool `json:"can_manage"`+ Team []AppConnectionResponse `json:"team"`+ Personal []AppConnectionResponse `json:"personal"`+ AgentApps []AgentAppResponse `json:"agent_apps"`+ TeamRequests []AppTeamRequestResponse `json:"team_requests"`}// AppCatalogEntry is one app in the add-app dialog.@@ -119,7 +133,8 @@ type AppToolCallResponse struct {// AppRequestResponse is one confirmation or connection request. Arguments and// results are shown only to the approver: a personal account's draft email is-// not for everyone who can open the issue.+// not for everyone who can open the issue. AddsApp marks a pending connection+// request whose approval also adds the app to the agent.type AppRequestResponse struct {ID string `json:"id"`Kind string `json:"kind"`@@ -139,10 +154,15 @@ type AppRequestResponse struct {Error *string `json:"error"`Reason *string `json:"reason"`Redacted bool `json:"redacted"`- ExpiresAt string `json:"expires_at"`- DecidedBy *string `json:"decided_by"`- DecidedAt *string `json:"decided_at"`- CreatedAt string `json:"created_at"`+ AddsApp bool `json:"adds_app"`+ // CanDecide is whether the viewer may answer the request: any admin for a+ // team account request, otherwise its approver. The member waiting on a+ // team account request can still withdraw it.+ CanDecide bool `json:"can_decide"`+ ExpiresAt string `json:"expires_at"`+ DecidedBy *string `json:"decided_by"`+ DecidedAt *string `json:"decided_at"`+ CreatedAt string `json:"created_at"`}func (h *Handler) appsReady(w http.ResponseWriter, r *http.Request) bool {@@ -217,17 +237,17 @@ func (h *Handler) GetAppsOverview(w http.ResponseWriter, r *http.Request) {writeError(w, http.StatusInternalServerError, "failed to list team accounts")return}- personal, err := h.Queries.ListUserComposioConnectionsAnyStatus(ctx, member.UserID)+ personal, err := h.Queries.ListUserComposioConnectionsAnyStatus(ctx, db.ListUserComposioConnectionsAnyStatusParams{UserID: member.UserID, WorkspaceID: workspaceID})if err != nil {writeError(w, http.StatusInternalServerError, "failed to list personal accounts")return}- remoteTeam, err := h.remoteConnections(r, connectedapps.ScopeTeam, workspaceID)+ remoteTeam, err := h.remoteConnections(r, connectedapps.ScopeTeam, workspaceID, workspaceID)if err != nil {writeError(w, http.StatusInternalServerError, "failed to list team accounts")return}- remotePersonal, err := h.remoteConnections(r, connectedapps.ScopePersonal, member.UserID)+ remotePersonal, err := h.remoteConnections(r, connectedapps.ScopePersonal, workspaceID, member.UserID)if err != nil {writeError(w, http.StatusInternalServerError, "failed to list personal accounts")return@@ -237,6 +257,11 @@ func (h *Handler) GetAppsOverview(w http.ResponseWriter, r *http.Request) {writeError(w, http.StatusInternalServerError, "failed to list agent apps")return}+ teamRequests, err := h.Queries.ListTeamAccountRequestSummaries(ctx, workspaceID)+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to list team account requests")+ return+ }teamRows := make([]AppConnectionResponse, 0, len(team)+len(remoteTeam))for _, row := range team {teamRows = append(teamRows, connectionFromTeam(row))@@ -279,10 +304,27 @@ func (h *Handler) GetAppsOverview(w http.ResponseWriter, r *http.Request) {Team: make([]AppConnectionResponse, 0, len(teamRows)),Personal: make([]AppConnectionResponse, 0, len(personalRows)),AgentApps: make([]AgentAppResponse, 0, len(agentApps)),+ TeamRequests: make([]AppTeamRequestResponse, 0, len(teamRequests)),}+ activeTeam := map[string]bool{}for _, connection := range teamRows {connection.ActionsBlocked = blocked[uuidToString(pgtype.UUID{})+":"+connection.ToolkitSlug]resp.Team = append(resp.Team, connection)+ if connection.Status == "active" {+ activeTeam[connectedapps.NormalizeSlug(connection.ToolkitSlug)] = true+ }+ }+ for _, row := range teamRequests {+ if activeTeam[row.ToolkitSlug] {+ continue+ }+ resp.TeamRequests = append(resp.TeamRequests, AppTeamRequestResponse{+ ToolkitSlug: row.ToolkitSlug,+ RequestedBy: uniqueStrings(uuidStringsOrEmpty(row.RequestedBy)),+ AskedBy: uniqueStrings(uuidStringsOrEmpty(row.AskedBy)),+ AgentIDs: uniqueStrings(uuidStringsOrEmpty(row.AgentIds)),+ LastRequestedAt: timestampToString(row.LastRequestedAt),+ })}for _, connection := range personalRows {connection.ActionsBlocked = blocked[uuidToString(member.UserID)+":"+connection.ToolkitSlug]@@ -294,6 +336,19 @@ func (h *Handler) GetAppsOverview(w http.ResponseWriter, r *http.Request) {writeJSON(w, http.StatusOK, resp)}+// uniqueStrings drops repeats, keeping the first of each.+func uniqueStrings(in []string) []string {+ seen := make(map[string]bool, len(in))+ out := in[:0]+ for _, v := range in {+ if !seen[v] {+ seen[v] = true+ out = append(out, v)+ }+ }+ return out+}+// ListAppCatalog (GET /api/apps/catalog) is every app the workspace may add.// An admin passing ?view=all gets every connectable app, each marked with// whether the catalog allows it, to edit a custom list.@@ -418,7 +473,7 @@ func (h *Handler) ConnectTeamApp(w http.ResponseWriter, r *http.Request) {var url stringvar err errorif _, remote := h.ConnectedApps.RemoteApp(req.ToolkitSlug); remote {- url, err = h.ConnectedApps.BeginRemoteConnect(r.Context(), req.ToolkitSlug, connectedapps.ScopeTeam, workspaceID, member.UserID, req.ReturnTo)+ url, err = h.ConnectedApps.BeginRemoteConnect(r.Context(), req.ToolkitSlug, connectedapps.ScopeTeam, workspaceID, workspaceID, member.UserID, req.ReturnTo)} else {url, err = h.Composio.BeginTeamConnect(r.Context(), workspaceID, member.UserID, req.ToolkitSlug, req.ReturnTo)}@@ -446,9 +501,9 @@ func (h *Handler) ConnectPersonalApp(w http.ResponseWriter, r *http.Request) {var url stringvar err errorif _, remote := h.ConnectedApps.RemoteApp(req.ToolkitSlug); remote {- url, err = h.ConnectedApps.BeginRemoteConnect(r.Context(), req.ToolkitSlug, connectedapps.ScopePersonal, member.UserID, member.UserID, req.ReturnTo)+ url, err = h.ConnectedApps.BeginRemoteConnect(r.Context(), req.ToolkitSlug, connectedapps.ScopePersonal, workspaceID, member.UserID, member.UserID, req.ReturnTo)} else {- url, err = h.Composio.BeginConnectReturning(r.Context(), member.UserID, req.ToolkitSlug, req.ReturnTo)+ url, err = h.Composio.BeginConnectReturning(r.Context(), member.UserID, workspaceID, req.ToolkitSlug, req.ReturnTo)}if err != nil {writeConnectError(w, r, err)@@ -545,6 +600,109 @@ func (h *Handler) GetTeamAppImpact(w http.ResponseWriter, r *http.Request) {})}+// RequestTeamApp (POST /api/apps/team/requests) asks the workspace's admins+// to connect a team account for an app. Asking again refreshes the ask+// without notifying the admins again.+func (h *Handler) RequestTeamApp(w http.ResponseWriter, r *http.Request) {+ if !h.appsReady(w, r) {+ return+ }+ member, workspaceID, _, ok := h.appsMember(w, r)+ if !ok {+ return+ }+ var req struct {+ ToolkitSlug string `json:"toolkit_slug"`+ AgentID string `json:"agent_id"`+ }+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil {+ writeError(w, http.StatusBadRequest, "invalid request body")+ return+ }+ slug := connectedapps.NormalizeSlug(req.ToolkitSlug)+ if slug == "" {+ writeError(w, http.StatusBadRequest, "toolkit_slug is required")+ return+ }+ ctx := r.Context()+ if !h.ConnectedApps.Catalog(ctx, workspaceID).Allows(slug) {+ writeError(w, http.StatusForbidden, "this workspace does not allow this app")+ return+ }+ var agentID pgtype.UUID+ if req.AgentID != "" {+ id, ok := parseUUIDOrBadRequest(w, req.AgentID, "agent_id")+ if !ok {+ return+ }+ agent, err := h.Queries.GetAgent(ctx, id)+ if err != nil || agent.WorkspaceID != workspaceID || agent.ArchivedAt.Valid {+ writeError(w, http.StatusBadRequest, "agent not found")+ return+ }+ agentID = agent.ID+ }+ team, err := h.Queries.ListWorkspaceComposioConnections(ctx, workspaceID)+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to list team accounts")+ return+ }+ for _, row := range team {+ if row.Status == "active" && connectedapps.NormalizeSlug(row.ToolkitSlug) == slug {+ writeError(w, http.StatusConflict, "the workspace already has a team account for this app")+ return+ }+ }+ remoteTeam, err := h.remoteConnections(r, connectedapps.ScopeTeam, workspaceID, workspaceID)+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to list team accounts")+ return+ }+ for _, row := range remoteTeam {+ if row.Status == "active" && row.AppSlug == slug {+ writeError(w, http.StatusConflict, "the workspace already has a team account for this app")+ return+ }+ }+ if _, err := h.ConnectedApps.AskTeamAccount(ctx, workspaceID, member.UserID, slug, agentID); err != nil {+ writeError(w, http.StatusInternalServerError, "failed to save the request")+ return+ }+ w.WriteHeader(http.StatusNoContent)+}++// DismissTeamAppRequests (DELETE /api/apps/team/requests?toolkit_slug=).+// An admin declines everything waiting for an app's team account: agents+// resume without it and members who asked are told. A member withdraws+// their own ask.+func (h *Handler) DismissTeamAppRequests(w http.ResponseWriter, r *http.Request) {+ if !h.appsReady(w, r) {+ return+ }+ member, workspaceID, isAdmin, ok := h.appsMember(w, r)+ if !ok {+ return+ }+ slug := connectedapps.NormalizeSlug(r.URL.Query().Get("toolkit_slug"))+ if slug == "" {+ writeError(w, http.StatusBadRequest, "toolkit_slug is required")+ return+ }+ if !isAdmin {+ if err := h.ConnectedApps.WithdrawTeamAsk(r.Context(), workspaceID, member.UserID, slug); err != nil {+ writeError(w, http.StatusInternalServerError, "failed to withdraw the request")+ return+ }+ w.WriteHeader(http.StatusNoContent)+ return+ }+ if err := h.ConnectedApps.DeclineTeamConnectRequests(r.Context(), workspaceID, member.UserID, slug); err != nil {+ writeError(w, http.StatusInternalServerError, "failed to decline the requests")+ return+ }+ w.WriteHeader(http.StatusNoContent)+}+// maxAllowedToolkits bounds a custom catalog.const maxAllowedToolkits = 500@@ -1092,7 +1250,7 @@ func syncAgentAppsFromAllowlist(ctx context.Context, q *db.Queries, agent db.Agereturn q.DeleteAgentAppsExcept(ctx, db.DeleteAgentAppsExceptParams{AgentID: agent.ID, Keep: keep})}-func (h *Handler) requestResponse(req db.AppActionRequest, viewer pgtype.UUID) AppRequestResponse {+func (h *Handler) requestResponse(req db.AppActionRequest, viewer pgtype.UUID, viewerIsAdmin bool) AppRequestResponse {out := AppRequestResponse{ID: uuidToString(req.ID), Kind: req.Kind, Status: req.Status, AgentID: uuidToString(req.AgentID),IssueID: uuidToPtr(req.IssueID), ChatSessionID: uuidToPtr(req.ChatSessionID),@@ -1102,6 +1260,11 @@ func (h *Handler) requestResponse(req db.AppActionRequest, viewer pgtype.UUID) AExpiresAt: timestampToString(req.ExpiresAt), DecidedBy: uuidToPtr(req.DecidedBy),DecidedAt: timestampToPtr(req.DecidedAt), CreatedAt: timestampToString(req.CreatedAt),}+ if req.Kind == connectedapps.KindConnect && req.AccountScope == connectedapps.ScopeTeam {+ out.CanDecide = viewerIsAdmin+ } else {+ out.CanDecide = req.ApproverUserID == viewer+ }if req.ApproverUserID == viewer {out.Arguments = json.RawMessage(req.Arguments)if len(req.ApprovedArguments) > 0 {@@ -1124,7 +1287,7 @@ func (h *Handler) ListAppRequests(w http.ResponseWriter, r *http.Request) {if !h.appsReady(w, r) {return}- member, workspaceID, _, ok := h.appsMember(w, r)+ member, workspaceID, isAdmin, ok := h.appsMember(w, r)if !ok {return}@@ -1177,7 +1340,7 @@ func (h *Handler) ListAppRequests(w http.ResponseWriter, r *http.Request) {})}default:- pending, err = h.Queries.ListPendingAppActionRequestsForApprover(ctx, db.ListPendingAppActionRequestsForApproverParams{WorkspaceID: workspaceID, ApproverUserID: member.UserID})+ pending, err = h.Queries.ListPendingAppActionRequestsForApprover(ctx, db.ListPendingAppActionRequestsForApproverParams{WorkspaceID: workspaceID, ApproverUserID: member.UserID, AsAdmin: isAdmin})}if err != nil {writeError(w, http.StatusInternalServerError, "failed to list requests")@@ -1188,17 +1351,50 @@ func (h *Handler) ListAppRequests(w http.ResponseWriter, r *http.Request) {cursor := decided[len(decided)-1].CreatedAt.Time.UTC().Format(time.RFC3339Nano)nextBefore = &cursor}+ agentSlugs, err := h.pendingConnectAgentApps(ctx, pending)+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to list requests")+ return+ }out := make([]AppRequestResponse, 0, len(pending)+len(decided))// Decided rows arrive newest first; the list reads oldest first.for i := len(decided) - 1; i >= 0; i-- {- out = append(out, h.requestResponse(decided[i], member.UserID))+ out = append(out, h.requestResponse(decided[i], member.UserID, isAdmin))}for _, row := range pending {- out = append(out, h.requestResponse(row, member.UserID))+ resp := h.requestResponse(row, member.UserID, isAdmin)+ if slugs, ok := agentSlugs[row.AgentID]; ok {+ resp.AddsApp = !slugs[connectedapps.NormalizeSlug(row.ToolkitSlug)]+ }+ out = append(out, resp)}writeJSON(w, http.StatusOK, map[string]any{"requests": out, "next_before": nextBefore})}+// pendingConnectAgentApps loads, once per agent, the apps of the agents behind+// pending connect requests.+func (h *Handler) pendingConnectAgentApps(ctx context.Context, rows []db.AppActionRequest) (map[pgtype.UUID]map[string]bool, error) {+ out := map[pgtype.UUID]map[string]bool{}+ for _, row := range rows {+ if row.Kind != connectedapps.KindConnect || row.Status != "pending" || !row.TaskID.Valid {+ continue+ }+ if _, done := out[row.AgentID]; done {+ continue+ }+ apps, err := h.Queries.ListAgentApps(ctx, row.AgentID)+ if err != nil {+ return nil, err+ }+ slugs := map[string]bool{}+ for _, app := range apps {+ slugs[connectedapps.NormalizeSlug(app.ToolkitSlug)] = true+ }+ out[row.AgentID] = slugs+ }+ return out, nil+}+// appRequestPageSize is how many decided requests one list page carries.const appRequestPageSize = 50@@ -1214,6 +1410,8 @@ func writeDecisionError(w http.ResponseWriter, err error) {writeError(w, http.StatusConflict, "connect the account first")case errors.Is(err, connectedapps.ErrNoLongerAllowed):writeError(w, http.StatusForbidden, "you can no longer use this agent; the request was withdrawn")+ case errors.Is(err, connectedapps.ErrCannotAddApp):+ writeError(w, http.StatusForbidden, "you cannot add this app to the agent; the request was withdrawn")case errors.Is(err, connectedapps.ErrRateLimited):writeError(w, http.StatusTooManyRequests, "this account reached its per-minute call limit; approve again in a minute")default:@@ -1227,7 +1425,7 @@ func (h *Handler) ApproveAppRequest(w http.ResponseWriter, r *http.Request) {if !h.appsReady(w, r) {return}- member, workspaceID, _, ok := h.appsMember(w, r)+ member, workspaceID, isAdmin, ok := h.appsMember(w, r)if !ok {return}@@ -1249,7 +1447,7 @@ func (h *Handler) ApproveAppRequest(w http.ResponseWriter, r *http.Request) {writeDecisionError(w, err)return}- writeJSON(w, http.StatusOK, h.requestResponse(row, member.UserID))+ writeJSON(w, http.StatusOK, h.requestResponse(row, member.UserID, isAdmin))}// RejectAppRequest (POST /api/app-requests/{id}/reject).@@ -1257,7 +1455,7 @@ func (h *Handler) RejectAppRequest(w http.ResponseWriter, r *http.Request) {if !h.appsReady(w, r) {return}- member, workspaceID, _, ok := h.appsMember(w, r)+ member, workspaceID, isAdmin, ok := h.appsMember(w, r)if !ok {return}@@ -1279,7 +1477,7 @@ func (h *Handler) RejectAppRequest(w http.ResponseWriter, r *http.Request) {writeDecisionError(w, err)return}- writeJSON(w, http.StatusOK, h.requestResponse(row, member.UserID))+ writeJSON(w, http.StatusOK, h.requestResponse(row, member.UserID, isAdmin))}// AppsGateway (POST /api/apps/mcp) is the MCP endpoint runs reach their apps@@ -1306,6 +1504,23 @@ func (h *Handler) CanActFor(ctx context.Context, workspaceID, agentID, userID pgreturn h.canInvokeAgent(ctx, agent, "member", uid, uid, uuidToString(workspaceID))}+// CanManageAgent applies canManageAgent's rule outside a request: the agent's+// owner or a workspace owner/admin may edit it.+func (h *Handler) CanManageAgent(ctx context.Context, workspaceID, agentID, userID pgtype.UUID) bool {+ if !userID.Valid {+ return false+ }+ agent, err := h.Queries.GetAgent(ctx, agentID)+ if err != nil || agent.WorkspaceID != workspaceID || agent.ArchivedAt.Valid {+ return false+ }+ member, err := h.Queries.GetMemberByUserAndWorkspace(ctx, db.GetMemberByUserAndWorkspaceParams{UserID: userID, WorkspaceID: workspaceID})+ if err != nil || !roleAllowed(member.Role, "owner", "admin", "member") {+ return false+ }+ return roleAllowed(member.Role, "owner", "admin") || agent.OwnerID == userID+}+// 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 {diff --git a/server/internal/handler/connected_apps_boundary_test.go b/server/internal/handler/connected_apps_boundary_test.goindex 6c1e097ccd..4416db5015 100644--- a/server/internal/handler/connected_apps_boundary_test.go+++ b/server/internal/handler/connected_apps_boundary_test.go@@ -116,7 +116,7 @@ func TestConnectedApps_DepartedMemberCannotResumeOnConnect(t *testing.T) {t.Cleanup(func() {testPool.Exec(ctx, `DELETE FROM user_composio_connection WHERE connected_account_id=$1`, accountID)})- f.h.ConnectedApps.ResolveConnectRequests(ctx, member.UserID, "gmail")+ f.h.ConnectedApps.ResolveConnectRequests(ctx, member.WorkspaceID, member.UserID, "gmail")var queued intif err := testPool.QueryRow(ctx, `SELECT count(*) FROM agent_task_queue WHERE issue_id=$1 AND status='queued' AND originator_user_id=$2`, f.issueID, f.member).Scan(&queued); err != nil {t.Fatal(err)diff --git a/server/internal/handler/connected_apps_remote.go b/server/internal/handler/connected_apps_remote.goindex d389158c79..2ac0840210 100644--- a/server/internal/handler/connected_apps_remote.go+++ b/server/internal/handler/connected_apps_remote.go@@ -57,7 +57,9 @@ func (h *Handler) AppsOAuthCallback(w http.ResponseWriter, r *http.Request) {return}if result.Scope == connectedapps.ScopePersonal {- h.ConnectedApps.ResolveConnectRequests(r.Context(), result.Owner, result.Slug)+ h.ConnectedApps.ResolveConnectRequests(r.Context(), result.Workspace, result.Owner, result.Slug)+ } else {+ h.ConnectedApps.ResolveTeamConnectRequests(r.Context(), result.Owner, result.Actor, result.Slug)}http.Redirect(w, r, h.Composio.CallbackRedirect(redirect, true), http.StatusFound)}@@ -108,9 +110,9 @@ func connectionFromRemote(row db.RemoteAppConnection) AppConnectionResponse {// remoteConnections lists an owner's remote app accounts, or none when remote// apps are off.-func (h *Handler) remoteConnections(r *http.Request, scope string, owner pgtype.UUID) ([]db.RemoteAppConnection, error) {+func (h *Handler) remoteConnections(r *http.Request, scope string, workspaceID, owner pgtype.UUID) ([]db.RemoteAppConnection, error) {if len(h.ConnectedApps.RemoteApps()) == 0 {return nil, nil}- return h.Queries.ListRemoteAppConnectionsForOwner(r.Context(), db.ListRemoteAppConnectionsForOwnerParams{Scope: scope, OwnerID: owner})+ return h.Queries.ListRemoteAppConnectionsForOwner(r.Context(), db.ListRemoteAppConnectionsForOwnerParams{Scope: scope, OwnerID: owner, WorkspaceID: workspaceID})}diff --git a/server/internal/handler/connected_apps_remote_test.go b/server/internal/handler/connected_apps_remote_test.goindex 9ef8dde367..4498bacffd 100644--- a/server/internal/handler/connected_apps_remote_test.go+++ b/server/internal/handler/connected_apps_remote_test.go@@ -14,6 +14,7 @@ import ("testing""github.com/multica-ai/multica/server/internal/connectedapps"+ "github.com/multica-ai/multica/server/internal/entitlement""github.com/multica-ai/multica/server/internal/util/secretbox""github.com/multica-ai/multica/server/pkg/remotemcp")@@ -503,3 +504,67 @@ func TestRemoteApps_OffWithoutKey(t *testing.T) {t.Fatalf("remote gateway without remote apps: %d, want 404", w.Code)}}++// connectTeam runs the team connect handshake as an admin.+func (f *remoteAppsFixture) connectTeam(t *testing.T) {+ t.Helper()+ w := httptest.NewRecorder()+ f.h.ConnectTeamApp(w, appsReqAs(t, testUserID, http.MethodPost, "/api/apps/team/connect", map[string]string{"toolkit_slug": "mobbin"}))+ if w.Code != http.StatusOK {+ t.Fatalf("team connect: %d %s", w.Code, w.Body.String())+ }+ var init ComposioConnectInitResponse+ json.Unmarshal(w.Body.Bytes(), &init)+ authorize, err := url.Parse(init.RedirectURL)+ if err != nil {+ t.Fatalf("redirect_url = %q", init.RedirectURL)+ }+ f.callback(t, "state="+url.QueryEscape(authorize.Query().Get("state"))+"&code=auth-code")+}++// A connected remote team account is the workspace's account for the app:+// reconnecting it is a reauthorization a plan without team accounts allows,+// and members cannot ask an admin for it again.+func TestRemoteApps_TeamAccountIsTheWorkspaces(t *testing.T) {+ f := newRemoteAppsFixture(t)+ f.connectTeam(t)++ usePaidFeatureOn(t, f.h, entitlement.FeatureTeamAppAccounts, enforced())+ w := httptest.NewRecorder()+ f.h.ConnectTeamApp(w, appsReqAs(t, testUserID, http.MethodPost, "/api/apps/team/connect", map[string]string{"toolkit_slug": "mobbin"}))+ if w.Code != http.StatusOK {+ t.Fatalf("reconnecting the team account under enforcement: %d %s", w.Code, w.Body.String())+ }++ w = httptest.NewRecorder()+ f.h.RequestTeamApp(w, appsReqAs(t, f.member, http.MethodPost, "/api/apps/team/requests", map[string]string{"toolkit_slug": "mobbin"}))+ if w.Code != http.StatusConflict {+ t.Fatalf("asking for a connected team account: %d %s, want 409", w.Code, w.Body.String())+ }+}++// Disconnecting a personal remote account first lists the agents that lose it.+func TestRemoteApps_PersonalDisconnectImpact(t *testing.T) {+ f := newRemoteAppsFixture(t)+ f.connect(t, testUserID)+ f.putAgentApps(t, testUserID, []map[string]string{{"toolkit_slug": "mobbin", "account_scope": "personal", "level": "write"}})+ var id string+ testPool.QueryRow(context.Background(), `SELECT id FROM remote_app_connection WHERE owner_id = $1 AND app_slug = 'mobbin'`, testUserID).Scan(&id)+ impact := func(userID string) *httptest.ResponseRecorder {+ w := httptest.NewRecorder()+ f.h.GetComposioConnectionImpact(w, withURLParam(appsReqAs(t, userID, http.MethodGet, "/api/integrations/composio/connections/"+id+"/impact", nil), "id", id))+ return w+ }++ w := impact(testUserID)+ var resp struct {+ Agents []ComposioImpactAgent `json:"agents"`+ }+ json.Unmarshal(w.Body.Bytes(), &resp)+ if w.Code != http.StatusOK || len(resp.Agents) != 1 || resp.Agents[0].ID != f.agentID || resp.Agents[0].WorkspaceID != testWorkspaceID {+ t.Fatalf("impact: %d %s", w.Code, w.Body.String())+ }+ if w := impact(f.member); w.Code != http.StatusNotFound {+ t.Fatalf("another member's impact check: %d, want 404", w.Code)+ }+}diff --git a/server/internal/handler/connected_apps_requests_test.go b/server/internal/handler/connected_apps_requests_test.gonew file mode 100644index 0000000000..a7dc94a780--- /dev/null+++ b/server/internal/handler/connected_apps_requests_test.go@@ -0,0 +1,374 @@+package handler++import (+ "context"+ "encoding/json"+ "fmt"+ "net/http"+ "strings"+ "testing"++ "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 (f *appsFixture) overview(t *testing.T, userID string) (AppsOverviewResponse, map[string]json.RawMessage) {+ t.Helper()+ res := testutil.Call(t, f.h.GetAppsOverview, appsReqAs(t, userID, http.MethodGet, "/api/apps", nil)).Want(http.StatusOK)+ var typed AppsOverviewResponse+ var raw map[string]json.RawMessage+ res.JSON(&typed).JSON(&raw)+ return typed, raw+}++func (f *appsFixture) requestTeamApp(t *testing.T, userID string, body map[string]any) int {+ t.Helper()+ return testutil.Call(t, f.h.RequestTeamApp, appsReqAs(t, userID, http.MethodPost, "/api/apps/team/requests", body)).Code+}++func (f *appsFixture) dismissTeamRequests(t *testing.T, userID, slug string) int {+ t.Helper()+ return testutil.Call(t, f.h.DismissTeamAppRequests, appsReqAs(t, userID, http.MethodDelete, "/api/apps/team/requests?toolkit_slug="+slug, nil)).Code+}++func (f *appsFixture) teamAccount(t *testing.T, slug string) {+ t.Helper()+ dbfx.Insert(t, "workspace_composio_connection", testutil.Cols{+ "workspace_id": testWorkspaceID, "toolkit_slug": slug, "auth_config_id": "ac_" + slug,+ "connected_account_id": fmt.Sprintf("ca_team_%s_%d", slug, testSeq.Add(1)), "composio_user_id": "team", "connected_by": testUserID,+ })+}++// A member asking for a team account files the same request an agent does:+// the admins get one inbox item per app, and deciding it answers everyone.+func TestConnectedApps_TeamAccountRequests(t *testing.T) {+ f := newAppsFixture(t)++ _, raw := f.overview(t, f.member)+ if string(raw["team_requests"]) != "[]" {+ t.Fatalf("team_requests without asks = %s, want []", raw["team_requests"])+ }++ if code := f.requestTeamApp(t, f.member, map[string]any{"toolkit_slug": " Slack ", "agent_id": f.agentID}); code != http.StatusNoContent {+ t.Fatalf("member asks: %d", code)+ }+ if code := f.requestTeamApp(t, f.member, map[string]any{"toolkit_slug": "slack"}); code != http.StatusNoContent {+ t.Fatalf("member asks again: %d", code)+ }+ if n := dbfx.Count(t, `SELECT count(*) FROM app_action_request WHERE workspace_id=$1 AND approver_user_id=$2 AND status='pending'`, testWorkspaceID, f.member); n != 1 {+ t.Fatalf("pending asks after asking twice = %d, want 1", n)+ }+ if n := f.inboxCount(t, testUserID, connectedapps.NotifConnectRequested); n != 1 {+ t.Fatalf("admin notifications = %d, want 1 for a repeated ask", n)+ }+ if n := f.inboxCount(t, f.member, connectedapps.NotifConnectRequested); n != 0 {+ t.Fatalf("requester notified %d times", n)+ }+ var body, actor string+ dbfx.QueryRow(t, `SELECT body, actor_id FROM inbox_item WHERE workspace_id=$1 AND recipient_id=$2 AND type=$3`,+ testWorkspaceID, testUserID, connectedapps.NotifConnectRequested).Scan(&body, &actor)+ if !strings.Contains(body, "asks for a team Slack account") || actor != f.member {+ t.Fatalf("notification body %q actor %s", body, actor)+ }++ // An admin asking too is listed after the member and notifies nobody new.+ if code := f.requestTeamApp(t, testUserID, map[string]any{"toolkit_slug": "slack", "agent_id": f.agentID}); code != http.StatusNoContent {+ t.Fatalf("admin asks: %d", code)+ }+ if n := f.inboxCount(t, testUserID, connectedapps.NotifConnectRequested); n != 1 {+ t.Fatalf("admin notified again: %d", n)+ }+ got, _ := f.overview(t, f.member)+ if len(got.TeamRequests) != 1 {+ t.Fatalf("team requests = %+v", got.TeamRequests)+ }+ tr := got.TeamRequests[0]+ if tr.ToolkitSlug != "slack" || len(tr.RequestedBy) != 2 || tr.RequestedBy[0] != f.member || tr.RequestedBy[1] != testUserID ||+ len(tr.AskedBy) != 2 || len(tr.AgentIDs) != 1 || tr.AgentIDs[0] != f.agentID || tr.LastRequestedAt == "" {+ t.Fatalf("team request = %+v", tr)+ }++ for name, body := range map[string]map[string]any{+ "no slug": {"toolkit_slug": " "},+ "bad agent": {"toolkit_slug": "slack", "agent_id": "not-a-uuid"},+ "foreign agent": {"toolkit_slug": "slack", "agent_id": "00000000-0000-0000-0000-000000000001"},+ } {+ if code := f.requestTeamApp(t, f.member, body); code != http.StatusBadRequest {+ t.Fatalf("%s: %d, want 400", name, code)+ }+ }++ // A member's DELETE only withdraws their own ask.+ if code := f.dismissTeamRequests(t, f.member, "slack"); code != http.StatusNoContent {+ t.Fatalf("member withdraws: %d", code)+ }+ if got, _ := f.overview(t, f.member); len(got.TeamRequests) != 1 || len(got.TeamRequests[0].RequestedBy) != 1 || got.TeamRequests[0].RequestedBy[0] != testUserID {+ t.Fatalf("team requests after the member withdrew = %+v", got.TeamRequests)+ }+ if n := dbfx.Count(t, `SELECT count(*) FROM inbox_item WHERE workspace_id=$1 AND recipient_id=$2 AND type=$3 AND NOT archived`,+ testWorkspaceID, testUserID, connectedapps.NotifConnectRequested); n != 0 {+ t.Fatalf("admin still has %d open notifications for the withdrawn ask", n)+ }+ if code := f.requestTeamApp(t, f.member, map[string]any{"toolkit_slug": "slack"}); code != http.StatusNoContent {+ t.Fatalf("member asks again: %d", code)+ }+ if code := f.dismissTeamRequests(t, testUserID, "slack"); code != http.StatusNoContent {+ t.Fatalf("admin declines: %d", code)+ }+ if got, _ := f.overview(t, f.member); len(got.TeamRequests) != 0 {+ t.Fatalf("team requests after decline = %+v", got.TeamRequests)+ }+ if n := f.inboxCount(t, f.member, connectedapps.NotifActionResult); n != 1 {+ t.Fatalf("member told about the decline %d times, want 1", n)+ }+ if n := f.inboxCount(t, testUserID, connectedapps.NotifActionResult); n != 0 {+ t.Fatalf("admin told about their own decline %d times", n)+ }++ // Connecting the team account answers every ask for it.+ if code := f.requestTeamApp(t, f.member, map[string]any{"toolkit_slug": "notion"}); code != http.StatusNoContent {+ t.Fatalf("ask for notion: %d", code)+ }+ f.teamAccount(t, "notion")+ f.h.ConnectedApps.ResolveTeamConnectRequests(context.Background(), parseUUID(testWorkspaceID), parseUUID(testUserID), "notion")+ if n := dbfx.Count(t, `SELECT count(*) FROM app_action_request WHERE workspace_id=$1 AND toolkit_slug='notion' AND status='approved' AND decided_by=$2`, testWorkspaceID, testUserID); n != 1 {+ t.Fatalf("approved notion asks = %d, want 1", n)+ }+ if code := f.requestTeamApp(t, f.member, map[string]any{"toolkit_slug": "notion"}); code != http.StatusConflict {+ t.Fatalf("ask with an active team account: %d, want 409", code)+ }++ testutil.Call(t, f.h.UpdateAppSettings, appsReqAs(t, testUserID, http.MethodPut, "/api/apps/settings", map[string]any{"catalog_mode": "curated"})).Want(http.StatusOK)+ if code := f.requestTeamApp(t, f.member, map[string]any{"toolkit_slug": "some_unlisted_app"}); code != http.StatusForbidden {+ t.Fatalf("ask outside the catalog: %d, want 403", code)+ }++ // Leaving the workspace withdraws the member's asks.+ f.requestTeamApp(t, f.member, map[string]any{"toolkit_slug": "linear"})+ member, err := f.h.Queries.GetMemberByUserAndWorkspace(context.Background(), db.GetMemberByUserAndWorkspaceParams{+ UserID: parseUUID(f.member), WorkspaceID: parseUUID(testWorkspaceID),+ })+ if err != nil {+ t.Fatal(err)+ }+ if _, err := f.h.revokeAndRemoveMember(context.Background(), member.WorkspaceID, member.UserID, member.ID, parseUUID(testUserID)); err != nil {+ t.Fatal(err)+ }+ if n := dbfx.Count(t, `SELECT count(*) FROM app_action_request WHERE workspace_id=$1 AND approver_user_id=$2 AND status='pending'`, testWorkspaceID, f.member); n != 0 {+ t.Fatalf("asks of a departed member = %d", n)+ }+}++// An agent missing a team account asks the admins, not the person who+// started the run; any admin connecting it resumes the run as that person.+func TestConnectedApps_AgentTeamConnectRequestGoesToAdmins(t *testing.T) {+ f := newAppsFixture(t)+ if w := f.putAgentApps(t, testUserID, []map[string]string{{"toolkit_slug": "notion", "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)++ _, text, isErr := f.gateway(t, f.token(t), "apps_request_connection", map[string]any{"app": "notion", "summary": "Read the spec"})+ if isErr || !strings.Contains(text, "workspace admins") {+ t.Fatalf("request connection = %s (error %v)", text, isErr)+ }+ if n := f.inboxCount(t, testUserID, connectedapps.NotifConnectRequested); n != 1 {+ t.Fatalf("admin notifications = %d, want 1", n)+ }+ if n := f.inboxCount(t, f.member, connectedapps.NotifConnectRequested); n != 0 {+ t.Fatalf("run starter notified %d times", n)+ }++ adminView := f.listRequests(t, testUserID)+ memberView := f.listRequests(t, f.member)+ if len(adminView) != 1 || !adminView[0].CanDecide || adminView[0].AccountScope != "team" {+ t.Fatalf("admin view = %+v", adminView)+ }+ if len(memberView) != 1 || memberView[0].CanDecide {+ t.Fatalf("member view = %+v", memberView)+ }+ if code := testutil.Call(t, f.h.ApproveAppRequest, withURLParam(appsReqAs(t, f.member, http.MethodPost, "/api/app-requests/"+adminView[0].ID+"/approve", nil), "id", adminView[0].ID)).Code; code == http.StatusOK {+ t.Fatal("member approved a team account request")+ }++ f.teamAccount(t, "notion")+ f.h.ConnectedApps.ResolveTeamConnectRequests(context.Background(), parseUUID(testWorkspaceID), parseUUID(testUserID), "notion")+ if got := f.requestStatus(t, adminView[0].ID); got != "approved" {+ t.Fatalf("request after the admin connected = %s", got)+ }+ var note, originator string+ dbfx.QueryRow(t, `SELECT handoff_note, originator_user_id FROM agent_task_queue+ WHERE agent_id=$1 AND issue_id=$2 AND status='queued' AND trigger_evidence_kind='app_action_request'`, f.agentID, f.issueID).Scan(¬e, &originator)+ if !strings.Contains(note, "admin connected the team Notion account") || originator != f.member {+ t.Fatalf("resume run note %q originator %s, want the run starter", note, originator)+ }+}++func TestConnectedApps_PersonalConnectionImpact(t *testing.T) {+ f := newAppsFixture(t)+ if w := f.putAgentApps(t, testUserID, []map[string]string{{"toolkit_slug": "gmail", "account_scope": "personal"}}); w.Code != http.StatusOK {+ t.Fatalf("attach: %d %s", w.Code, w.Body.String())+ }+ // A private agent of another member acts through whoever runs it, but the+ // caller cannot run it, so it is not theirs to see.+ privateAgent := dbfx.Agent(t, fmt.Sprintf("apps-private-%d", testSeq.Add(1)), handlerTestRuntimeID(t), testutil.Cols{+ "owner_id": f.member, "instructions": "",+ "custom_env": testutil.Raw("'{}'::jsonb"), "custom_args": testutil.Raw("'[]'::jsonb"),+ })+ t.Cleanup(func() { testPool.Exec(context.Background(), `DELETE FROM agent WHERE id = $1`, privateAgent) })+ dbfx.Exec(t, `INSERT INTO agent_app (workspace_id, agent_id, toolkit_slug, account_scope, level) VALUES ($1, $2, 'gmail', 'personal', 'write')`, testWorkspaceID, privateAgent)++ var connectionID string+ dbfx.QueryRow(t, `SELECT id FROM user_composio_connection WHERE user_id=$1 AND toolkit_slug='gmail' AND status='active' ORDER BY created_at DESC LIMIT 1`, testUserID).Scan(&connectionID)+ impact := func(userID string) *testutil.Response {+ req := withURLParam(newRequestAs(userID, http.MethodGet, "/api/integrations/composio/connections/"+connectionID+"/impact", nil), "id", connectionID)+ return testutil.Call(t, f.h.GetComposioConnectionImpact, req)+ }++ var resp struct {+ Agents []ComposioImpactAgent `json:"agents"`+ }+ impact(testUserID).Want(http.StatusOK).JSON(&resp)+ var mine *ComposioImpactAgent+ for i := range resp.Agents {+ switch resp.Agents[i].ID {+ case f.agentID:+ mine = &resp.Agents[i]+ case privateAgent:+ t.Fatalf("impact names a private agent the caller cannot run: %+v", resp.Agents)+ }+ }+ if mine == nil || !mine.Running || mine.WorkspaceID != testWorkspaceID || mine.WorkspaceName == "" || mine.Name == "" {+ t.Fatalf("impact = %+v", resp.Agents)+ }++ dbfx.Exec(t, `UPDATE agent_task_queue SET status='completed', completed_at=now() WHERE id=$1`, f.taskID)+ impact(testUserID).Want(http.StatusOK).JSON(&resp)+ for _, a := range resp.Agents {+ if a.ID == f.agentID && a.Running {+ t.Fatalf("finished run still reported as running: %+v", a)+ }+ }++ impact(f.member).Want(http.StatusNotFound)+}++func TestConnectedApps_AgentAsksForNewApp(t *testing.T) {+ f := newAppsFixture(t)+ ctx := context.Background()++ _, text, isErr := f.gateway(t, f.token(t), "apps_request_connection", map[string]any{"app": "gmail", "summary": "Check my inbox"})+ if isErr || !strings.HasPrefix(text, "requested") || !strings.Contains(text, "add gmail") {+ t.Fatalf("ask for a new app = %s (error %v)", text, isErr)+ }+ reqs := f.listRequests(t, testUserID)+ if len(reqs) != 1 || reqs[0].Kind != "connect" || reqs[0].AccountScope != "personal" || reqs[0].ToolkitSlug != "gmail" || !reqs[0].AddsApp {+ t.Fatalf("requests = %+v", reqs)+ }+ var body string+ dbfx.QueryRow(t, `SELECT body FROM inbox_item WHERE workspace_id=$1 AND recipient_id=$2 AND type=$3`,+ testWorkspaceID, testUserID, connectedapps.NotifConnectRequested).Scan(&body)+ if !strings.Contains(body, "add Gmail") {+ t.Fatalf("notification body = %q", body)+ }++ approved := f.approve(t, reqs[0].ID, nil)+ if approved.Status != "approved" || approved.AddsApp {+ t.Fatalf("approved = %+v", approved)+ }+ var scope, level, createdBy string+ dbfx.QueryRow(t, `SELECT account_scope, level, created_by FROM agent_app WHERE agent_id=$1 AND toolkit_slug='gmail'`, f.agentID).Scan(&scope, &level, &createdBy)+ if scope != "personal" || level != connectedapps.LevelWrite || createdBy != testUserID {+ t.Fatalf("added app = %s/%s by %s", scope, level, createdBy)+ }+ var allowlist []string+ dbfx.QueryRow(t, `SELECT composio_toolkit_allowlist FROM agent WHERE id=$1`, f.agentID).Scan(&allowlist)+ if len(allowlist) != 1 || allowlist[0] != "gmail" {+ t.Fatalf("legacy allowlist = %v", allowlist)+ }+ var note string+ if err := testPool.QueryRow(ctx, `+ SELECT handoff_note FROM agent_task_queue+ WHERE agent_id = $1 AND issue_id = $2 AND status = 'queued' AND trigger_evidence_kind = 'app_action_request'+ `, f.agentID, f.issueID).Scan(¬e); err != nil || !strings.Contains(note, "added Gmail to your apps") {+ t.Fatalf("resume note = %q, %v", note, err)+ }++ // An app the agent already has is a plain connection request.+ f.putAgentApps(t, testUserID, []map[string]string{{"toolkit_slug": "gmail", "account_scope": "personal"}, {"toolkit_slug": "notion", "account_scope": "personal"}})+ if _, text, isErr := f.gateway(t, f.token(t), "apps_request_connection", map[string]any{"app": "notion"}); isErr {+ t.Fatalf("connect notion = %s", text)+ }+ for _, r := range f.listRequests(t, testUserID) {+ if r.ToolkitSlug == "notion" && (r.Status != "pending" || r.AddsApp) {+ t.Fatalf("notion request = %+v", r)+ }+ }+}++func TestConnectedApps_AgentAsksForNewAppRefused(t *testing.T) {+ cases := map[string]struct {+ setup func(f *appsFixture)+ app string+ want string+ }{+ "run starter cannot edit the agent": {+ setup: func(f *appsFixture) {+ dbfx.Exec(t, `UPDATE agent_task_queue SET originator_user_id=$1, accountable_user_id=$1 WHERE id=$2`, f.member, f.taskID)+ },+ app: "gmail", want: "cannot add apps to you",+ },+ "no human originator": {+ setup: func(f *appsFixture) {+ dbfx.Exec(t, `UPDATE agent_task_queue SET originator_user_id=NULL, accountable_user_id=$1 WHERE id=$2`, testUserID, f.taskID)+ },+ app: "gmail", want: "no person triggered this run",+ },+ "unknown app": {app: "no_such_toolkit", want: "there is no app"},+ "outside the catalog": {+ setup: func(f *appsFixture) {+ dbfx.Exec(t, `INSERT INTO workspace_app_setting (workspace_id, catalog_mode, allowed_toolkits) VALUES ($1, 'custom', '{notion}')`, testWorkspaceID)+ },+ app: "gmail", want: "not available in this workspace",+ },+ }+ for name, tc := range cases {+ t.Run(name, func(t *testing.T) {+ f := newAppsFixture(t)+ if tc.setup != nil {+ tc.setup(f)+ }+ _, text, isErr := f.gateway(t, f.token(t), "apps_request_connection", map[string]any{"app": tc.app})+ if !isErr || !strings.Contains(text, tc.want) {+ t.Fatalf("response = %s (error %v), want %q", text, isErr, tc.want)+ }+ if n := dbfx.Count(t, `SELECT count(*) FROM app_action_request WHERE task_id=$1`, f.taskID); n != 0 {+ t.Fatalf("refused ask created %d requests", n)+ }+ })+ }+}++// Approving a request that adds an app re-checks that the approver may edit+// the agent, and withdraws the request when they no longer may.+func TestConnectedApps_AddAppApprovalFailsClosed(t *testing.T) {+ f := newAppsFixture(t)+ dbfx.Exec(t, `UPDATE agent SET owner_id=$1 WHERE id=$2`, f.member, f.agentID)+ dbfx.Exec(t, `UPDATE agent_task_queue SET originator_user_id=$1, accountable_user_id=$1 WHERE id=$2`, f.member, f.taskID)+ if _, text, isErr := f.gateway(t, f.token(t), "apps_request_connection", map[string]any{"app": "notion"}); isErr {+ t.Fatalf("owner asks: %s", text)+ }+ var requestID string+ dbfx.QueryRow(t, `SELECT id FROM app_action_request WHERE task_id=$1 AND kind='connect'`, f.taskID).Scan(&requestID)++ dbfx.Exec(t, `UPDATE agent SET owner_id=$1 WHERE id=$2`, testUserID, f.agentID)+ req := withURLParam(appsReqAs(t, f.member, http.MethodPost, "/api/app-requests/"+requestID+"/approve", nil), "id", requestID)+ testutil.Call(t, f.h.ApproveAppRequest, req).Want(http.StatusForbidden)+ if got := f.requestStatus(t, requestID); got != "cancelled" {+ t.Fatalf("request after a refused approval = %s, want cancelled", got)+ }+ if n := dbfx.Count(t, `SELECT count(*) FROM agent_app WHERE agent_id=$1`, f.agentID); n != 0 {+ t.Fatalf("refused approval attached %d apps", n)+ }+}diff --git a/server/internal/handler/connected_apps_test.go b/server/internal/handler/connected_apps_test.goindex cda714bf7f..b4925d4b63 100644--- a/server/internal/handler/connected_apps_test.go+++ b/server/internal/handler/connected_apps_test.go@@ -117,6 +117,7 @@ func newAppsFixture(t *testing.T) *appsFixture {h.Composio = svcapps, err := connectedapps.New(connectedapps.Config{Queries: h.Queries,+ TxStarter: testPool,Composio: svc,TokenSecret: connectedapps.DeriveTokenSecret([]byte("apps-test-secret")),PublicBaseURL: "https://api.multica.test",@@ -149,7 +150,7 @@ func newAppsFixture(t *testing.T) *appsFixture {t.Cleanup(func() {ctx := context.Background()testPool.Exec(ctx, `DELETE FROM user_composio_connection WHERE connected_account_id = $1`, account)- for _, table := range []string{"app_tool_call", "app_action_request", "app_action_rule", "agent_app", "workspace_app_setting", "app_tool_class_override"} {+ for _, table := range []string{"app_tool_call", "app_action_request", "app_action_rule", "agent_app", "workspace_app_setting", "app_tool_class_override", "workspace_composio_connection"} {testPool.Exec(ctx, `DELETE FROM `+table+` WHERE workspace_id = $1`, testWorkspaceID)}testPool.Exec(ctx, `DELETE FROM inbox_item WHERE workspace_id = $1 AND type LIKE 'app\_%'`, testWorkspaceID)@@ -253,7 +254,7 @@ func (f *appsFixture) legacyRequest(t *testing.T, scope, slug, tool, class strinif err != nil {t.Fatal(err)}- return f.h.requestResponse(req, parseUUID(testUserID))+ return f.h.requestResponse(req, parseUUID(testUserID), true)}func TestConnectedApps_LegacyApprovalResumes(t *testing.T) {@@ -604,7 +605,7 @@ func TestConnectedApps_ConnectRequestResolvesOnConnect(t *testing.T) {t.Cleanup(func() {testPool.Exec(context.Background(), `DELETE FROM user_composio_connection WHERE connected_account_id = $1`, account)})- f.h.ConnectedApps.ResolveConnectRequests(context.Background(), parseUUID(testUserID), "notion")+ f.h.ConnectedApps.ResolveConnectRequests(context.Background(), parseUUID(testWorkspaceID), parseUUID(testUserID), "notion")if reqs := f.listRequests(t, testUserID); len(reqs) != 1 || reqs[0].Status != "approved" {t.Fatalf("connect request after connecting = %+v", reqs)diff --git a/server/internal/handler/integrations_composio.go b/server/internal/handler/integrations_composio.goindex a2e23320cb..726fe0df8b 100644--- a/server/internal/handler/integrations_composio.go+++ b/server/internal/handler/integrations_composio.go@@ -8,9 +8,12 @@ import ("strings""github.com/go-chi/chi/v5"+ "github.com/jackc/pgx/v5"+ "github.com/jackc/pgx/v5/pgtype""github.com/multica-ai/multica/server/internal/connectedapps""github.com/multica-ai/multica/server/internal/featureflags"composio "github.com/multica-ai/multica/server/internal/integrations/composio"+ db "github.com/multica-ai/multica/server/pkg/db/generated")// Composio integration handlers (MUL-3720, Stage 2 MVP). A Composio connection@@ -136,13 +139,116 @@ func (h *Handler) ComposioCallback(w http.ResponseWriter, r *http.Request) {return}if h.ConnectedApps != nil && !result.Team() {- if userID, perr := parseUUIDStrict(result.UserID); perr == nil {- h.ConnectedApps.ResolveConnectRequests(r.Context(), userID, result.ToolkitSlug)+ userID, uerr := parseUUIDStrict(result.UserID)+ workspaceID, werr := parseUUIDStrict(result.PersonalWorkspaceID)+ if uerr == nil && werr == nil {+ h.ConnectedApps.ResolveConnectRequests(r.Context(), workspaceID, userID, result.ToolkitSlug)+ }+ }+ if h.ConnectedApps != nil && result.Team() {+ workspaceID, werr := parseUUIDStrict(result.WorkspaceID)+ adminID, aerr := parseUUIDStrict(result.ConnectedBy)+ if werr == nil && aerr == nil {+ h.ConnectedApps.ResolveTeamConnectRequests(r.Context(), workspaceID, adminID, result.ToolkitSlug)}}http.Redirect(w, r, h.Composio.CallbackRedirect(result, true), http.StatusFound)}+// ComposioImpactAgent is one agent that acts through a personal account.+type ComposioImpactAgent struct {+ ID string `json:"id"`+ Name string `json:"name"`+ WorkspaceID string `json:"workspace_id"`+ WorkspaceName string `json:"workspace_name"`+ // Running is true while a run the caller started on the agent is active.+ Running bool `json:"running"`+}++// GetComposioConnectionImpact (GET+// /api/integrations/composio/connections/{id}/impact) is what disconnecting+// one of the caller's personal accounts would stop: the agents in the+// account's workspace (every workspace, for an account made before accounts+// belonged to one) that act through it when the caller runs them.+func (h *Handler) GetComposioConnectionImpact(w http.ResponseWriter, r *http.Request) {+ if h.Composio == nil || !h.composioMCPAppsEnabled(r.Context()) {+ writeFeatureDisabled(w, "composio_not_configured", "composio integration not configured")+ return+ }+ userID, ok := requireUserID(w, r)+ if !ok {+ return+ }+ userUUID, ok := parseUUIDOrBadRequest(w, userID, "user id")+ if !ok {+ return+ }+ connUUID, ok := parseUUIDOrBadRequest(w, chi.URLParam(r, "id"), "connection id")+ if !ok {+ return+ }+ ctx := r.Context()+ var slug string+ var workspaceID pgtype.UUID+ if conn, err := h.Queries.GetUserComposioConnection(ctx, db.GetUserComposioConnectionParams{ID: connUUID, UserID: userUUID}); err == nil {+ slug, workspaceID = connectedapps.NormalizeSlug(conn.ToolkitSlug), conn.WorkspaceID+ } else if remote, rerr := h.remotePersonalConnection(ctx, connUUID, userUUID); rerr == nil {+ // Personal remote app accounts are disconnected through this API too.+ slug, workspaceID = remote.AppSlug, remote.WorkspaceID+ } else {+ writeError(w, http.StatusNotFound, "composio connection not found")+ return+ }+ rows, err := h.Queries.ListPersonalAppAgentsForUser(ctx, db.ListPersonalAppAgentsForUserParams{+ UserID: userUUID, ToolkitSlug: slug,+ })+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to list agents")+ return+ }+ agents := make([]ComposioImpactAgent, 0, len(rows))+ ids := make([]pgtype.UUID, 0, len(rows))+ for _, row := range rows {+ if workspaceID.Valid && row.WorkspaceID != workspaceID {+ continue+ }+ if !h.CanActFor(ctx, row.WorkspaceID, row.ID, userUUID) {+ continue+ }+ ids = append(ids, row.ID)+ agents = append(agents, ComposioImpactAgent{+ ID: uuidToString(row.ID), Name: row.Name,+ WorkspaceID: uuidToString(row.WorkspaceID), WorkspaceName: row.WorkspaceName,+ })+ }+ if len(ids) > 0 {+ running, err := h.Queries.ListAgentsWithActiveTasksForOriginator(ctx, db.ListAgentsWithActiveTasksForOriginatorParams{+ AgentIds: ids, OriginatorUserID: userUUID,+ })+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to list active runs")+ return+ }+ active := make(map[string]bool, len(running))+ for _, id := range running {+ active[uuidToString(id)] = true+ }+ for i := range agents {+ agents[i].Running = active[agents[i].ID]+ }+ }+ writeJSON(w, http.StatusOK, map[string]any{"agents": agents})+}++func (h *Handler) remotePersonalConnection(ctx context.Context, id, userID pgtype.UUID) (db.RemoteAppConnection, error) {+ if h.ConnectedApps == nil {+ return db.RemoteAppConnection{}, pgx.ErrNoRows+ }+ return h.Queries.GetRemoteAppConnectionForOwner(ctx, db.GetRemoteAppConnectionForOwnerParams{+ ID: id, Scope: connectedapps.ScopePersonal, OwnerID: userID,+ })+}+// ListComposioConnections (GET /api/integrations/composio/connections) returns// the caller's active connections.func (h *Handler) ListComposioConnections(w http.ResponseWriter, r *http.Request) {diff --git a/server/internal/handler/integrations_composio_test.go b/server/internal/handler/integrations_composio_test.goindex e780fe2ce1..101d537d4b 100644--- a/server/internal/handler/integrations_composio_test.go+++ b/server/internal/handler/integrations_composio_test.go@@ -109,7 +109,16 @@ func (s *composioFakeStore) UpsertUserComposioConnection(_ context.Context, args.rows = append(s.rows, row)return row, nil}-func (s *composioFakeStore) ListActiveUserComposioConnections(_ context.Context, userID pgtype.UUID) ([]db.UserComposioConnection, error) {+func (s *composioFakeStore) ListActiveUserComposioConnections(_ context.Context, arg db.ListActiveUserComposioConnectionsParams) ([]db.UserComposioConnection, error) {+ out := []db.UserComposioConnection{}+ for _, r := range s.rows {+ if r.UserID.Bytes == arg.UserID.Bytes && r.Status == "active" && (!r.WorkspaceID.Valid || r.WorkspaceID.Bytes == arg.WorkspaceID.Bytes) {+ out = append(out, r)+ }+ }+ return out, nil+}+func (s *composioFakeStore) ListAllActiveUserComposioConnections(_ context.Context, userID pgtype.UUID) ([]db.UserComposioConnection, error) {out := []db.UserComposioConnection{}for _, r := range s.rows {if r.UserID.Bytes == userID.Bytes && r.Status == "active" {diff --git a/server/internal/handler/reserved_slugs.json b/server/internal/handler/reserved_slugs.jsonindex 4706c72a7e..b15e6f9bae 100644--- a/server/internal/handler/reserved_slugs.json+++ b/server/internal/handler/reserved_slugs.json@@ -290,6 +290,7 @@"usage","runtimes","skills",+ "apps","settings","workspaces","teams"diff --git a/server/internal/handler/team_app_feature.go b/server/internal/handler/team_app_feature.goindex 28c8f33e6f..41d5a1489e 100644--- a/server/internal/handler/team_app_feature.go+++ b/server/internal/handler/team_app_feature.go@@ -56,7 +56,7 @@ func (h *Handler) teamAppHasAccount(ctx context.Context, workspaceID pgtype.UUIDreturn false, nil}remoteRows, err := h.Queries.ListRemoteAppConnectionsForOwner(ctx, db.ListRemoteAppConnectionsForOwnerParams{- Scope: connectedapps.ScopeTeam, OwnerID: workspaceID,+ Scope: connectedapps.ScopeTeam, OwnerID: workspaceID, WorkspaceID: workspaceID,})if err != nil {return false, errdiff --git a/server/internal/handler/workspace_delete_manifest_test.go b/server/internal/handler/workspace_delete_manifest_test.goindex 8887883f13..1ff6ccfd60 100644--- a/server/internal/handler/workspace_delete_manifest_test.go+++ b/server/internal/handler/workspace_delete_manifest_test.go@@ -162,7 +162,7 @@ var workspaceDeletionManifest = map[string]workspaceDeleteAction{"task_usage_hourly_dirty": workspaceDelete,"task_usage_hourly_rollup_state": workspaceDeleteKeep,"user": workspaceDeleteKeep,- "user_composio_connection": workspaceDeleteKeep,+ "user_composio_connection": workspaceDelete, // personal accounts made in the workspace; older rows have no workspace and stay"vcs_commit_status": workspaceDelete,"vcs_connection": workspaceDelete,"vcs_pull_request": workspaceDelete,@@ -172,7 +172,7 @@ var workspaceDeletionManifest = map[string]workspaceDeleteAction{"weixin_login_session": workspaceDelete,"weixin_account_state": workspaceDelete,"workspace_composio_connection": workspaceDelete,- "remote_app_connection": workspaceDelete, // team rows (owner_id = workspace); personal rows are user-owned+ "remote_app_connection": workspaceDelete, // team rows (owner_id = workspace) and personal rows made in the workspace"remote_app_oauth_client": workspaceDeleteKeep,"agent_app": workspaceDelete,"app_action_rule": workspaceDelete,diff --git a/server/internal/integrations/composio/dispatch.go b/server/internal/integrations/composio/dispatch.goindex a8e7bc1cb3..98f9a4165f 100644--- a/server/internal/integrations/composio/dispatch.go+++ b/server/internal/integrations/composio/dispatch.go@@ -100,7 +100,9 @@ func (s *Service) BuildTaskOverlay(ctx context.Context, originatorUserID pgtype.// Resolve the OWNER's active connections and intersect with the allowlist.// The intersection is the canonical input both for filtering the Composio// CreateSession call AND for the early bail-out below.- rows, err := s.store.ListActiveUserComposioConnections(ctx, ownerUserID)+ rows, err := s.store.ListActiveUserComposioConnections(ctx, db.ListActiveUserComposioConnectionsParams{+ UserID: ownerUserID, WorkspaceID: agent.WorkspaceID,+ })if err != nil {return runtimeapps.MCPOverlayResult{}, fmt.Errorf("composio: build task overlay: list connections: %w", err)}diff --git a/server/internal/integrations/composio/service.go b/server/internal/integrations/composio/service.goindex 25382d36b3..a5f90adf50 100644--- a/server/internal/integrations/composio/service.go+++ b/server/internal/integrations/composio/service.go@@ -87,7 +87,8 @@ type SDK interface {// satisfies it; tests use an in-memory fake.type Store interface {UpsertUserComposioConnection(ctx context.Context, arg db.UpsertUserComposioConnectionParams) (db.UserComposioConnection, error)- ListActiveUserComposioConnections(ctx context.Context, userID pgtype.UUID) ([]db.UserComposioConnection, error)+ ListActiveUserComposioConnections(ctx context.Context, arg db.ListActiveUserComposioConnectionsParams) ([]db.UserComposioConnection, error)+ ListAllActiveUserComposioConnections(ctx context.Context, userID pgtype.UUID) ([]db.UserComposioConnection, error)GetUserComposioConnection(ctx context.Context, arg db.GetUserComposioConnectionParams) (db.UserComposioConnection, error)MarkUserComposioConnectionRevoked(ctx context.Context, arg db.MarkUserComposioConnectionRevokedParams) error}@@ -246,12 +247,13 @@ func toolkitLogoURL(slug, upstreamLogoURL string) string {// The composio_user_id sent to Composio is the Multica user id verbatim — the// invariant the rest of the integration relies on.func (s *Service) BeginConnect(ctx context.Context, userID pgtype.UUID, toolkitSlug string) (string, error) {- return s.BeginConnectReturning(ctx, userID, toolkitSlug, "")+ return s.BeginConnectReturning(ctx, userID, pgtype.UUID{}, toolkitSlug, "")}-// BeginConnectReturning is BeginConnect whose callback sends the browser back-// to returnTo, an app path; an unsafe or empty path keeps the settings page.-func (s *Service) BeginConnectReturning(ctx context.Context, userID pgtype.UUID, toolkitSlug, returnTo string) (string, error) {+// BeginConnectReturning is BeginConnect for an account that belongs to+// workspaceID, whose callback sends the browser back to returnTo, an app+// path; an unsafe or empty path keeps the settings page.+func (s *Service) BeginConnectReturning(ctx context.Context, userID, workspaceID pgtype.UUID, toolkitSlug, returnTo string) (string, error) {if !SafeReturnPath(returnTo) {returnTo = ""}@@ -268,13 +270,17 @@ func (s *Service) BeginConnectReturning(ctx context.Context, userID pgtype.UUID,}composioUserID := util.UUIDToString(userID)- state, err := signState(s.secret, stateClaims{+ claims := stateClaims{UserID: composioUserID,ToolkitSlug: slug,AuthConfigID: authConfigID,ReturnTo: returnTo,Exp: s.now().Add(s.stateTTL).Unix(),- })+ }+ if workspaceID.Valid {+ claims.PersonalWorkspaceID = util.UUIDToString(workspaceID)+ }+ state, err := signState(s.secret, claims)if err != nil {return "", fmt.Errorf("composio: sign state: %w", err)}@@ -307,9 +313,9 @@ func (s *Service) CompleteCallback(ctx context.Context, state, status, connectedif err != nil {return CallbackResult{}, err}- result := CallbackResult{ToolkitSlug: claims.ToolkitSlug, WorkspaceID: claims.WorkspaceID, ReturnTo: claims.ReturnTo}+ result := CallbackResult{ToolkitSlug: claims.ToolkitSlug, WorkspaceID: claims.WorkspaceID, ConnectedBy: claims.ConnectedBy, ReturnTo: claims.ReturnTo}if claims.WorkspaceID == "" {- result.UserID = claims.UserID+ result.UserID, result.PersonalWorkspaceID = claims.UserID, claims.PersonalWorkspaceID}if !strings.EqualFold(strings.TrimSpace(status), "success") {@@ -349,8 +355,15 @@ func (s *Service) CompleteCallback(ctx context.Context, state, status, connectedreturn result, err}+ var workspaceID pgtype.UUID+ if claims.PersonalWorkspaceID != "" {+ if workspaceID, err = util.ParseUUID(claims.PersonalWorkspaceID); err != nil {+ return result, fmt.Errorf("composio: state has invalid workspace id: %w", err)+ }+ }if _, err := s.store.UpsertUserComposioConnection(ctx, db.UpsertUserComposioConnectionParams{UserID: userID,+ WorkspaceID: workspaceID,ToolkitSlug: claims.ToolkitSlug,AuthConfigID: authConfigID,ConnectedAccountID: connectedAccountID,@@ -362,9 +375,9 @@ func (s *Service) CompleteCallback(ctx context.Context, state, status, connectedreturn result, nil}-// ListConnections returns the user's active connections.+// ListConnections returns the user's active connections in every workspace.func (s *Service) ListConnections(ctx context.Context, userID pgtype.UUID) ([]Connection, error) {- rows, err := s.store.ListActiveUserComposioConnections(ctx, userID)+ rows, err := s.store.ListAllActiveUserComposioConnections(ctx, userID)if err != nil {return nil, err}@@ -445,7 +458,7 @@ func (s *Service) Disconnect(ctx context.Context, userID, connectionID pgtype.UU// a multi-account request shape. Until then, newest-wins keeps behavior// deterministic rather than order-dependent.func (s *Service) CreateMCPSession(ctx context.Context, userID pgtype.UUID) (*MCPSession, error) {- rows, err := s.store.ListActiveUserComposioConnections(ctx, userID)+ rows, err := s.store.ListAllActiveUserComposioConnections(ctx, userID)if err != nil {return nil, err}diff --git a/server/internal/integrations/composio/service_test.go b/server/internal/integrations/composio/service_test.goindex 9fa47cb22c..64151acabc 100644--- a/server/internal/integrations/composio/service_test.go+++ b/server/internal/integrations/composio/service_test.go@@ -154,6 +154,7 @@ func (s *fakeStore) UpsertUserComposioConnection(_ context.Context, arg db.Upserrow := db.UserComposioConnection{ID: mintUUID(s.nextID),UserID: arg.UserID,+ WorkspaceID: arg.WorkspaceID,ToolkitSlug: arg.ToolkitSlug,AuthConfigID: arg.AuthConfigID,ConnectedAccountID: arg.ConnectedAccountID,@@ -166,7 +167,17 @@ func (s *fakeStore) UpsertUserComposioConnection(_ context.Context, arg db.Upserreturn row, nil}-func (s *fakeStore) ListActiveUserComposioConnections(_ context.Context, userID pgtype.UUID) ([]db.UserComposioConnection, error) {+func (s *fakeStore) ListActiveUserComposioConnections(_ context.Context, arg db.ListActiveUserComposioConnectionsParams) ([]db.UserComposioConnection, error) {+ out := []db.UserComposioConnection{}+ for _, r := range s.rows {+ if uuidEqual(r.UserID, arg.UserID) && r.Status == "active" && (!r.WorkspaceID.Valid || uuidEqual(r.WorkspaceID, arg.WorkspaceID)) {+ out = append(out, r)+ }+ }+ return out, nil+}++func (s *fakeStore) ListAllActiveUserComposioConnections(_ context.Context, userID pgtype.UUID) ([]db.UserComposioConnection, error) {out := []db.UserComposioConnection{}for _, r := range s.rows {if uuidEqual(r.UserID, userID) && r.Status == "active" {@@ -707,7 +718,7 @@ func TestCallbackRedirect(t *testing.T) {}if got := svc.CallbackRedirect(CallbackResult{ToolkitSlug: "notion", WorkspaceID: "w"}, true); got != "https://multica.ai/settings?connected=notion&scope=team&tab=apps" {t.Errorf("team redirect = %q", got)- } // A plan refusal keeps the ordinary failure fields, so older pages still+ } // A plan refusal keeps the ordinary failure fields, so older pages still// report a failure, and adds the reason for pages that show the upgrade.if got := svc.CallbackRedirectFailure(CallbackResult{ToolkitSlug: "notion", WorkspaceID: "w"}, CallbackFeatureLockedReason); got != "https://multica.ai/settings?error=composio_connect_failed&reason=feature_locked&scope=team&tab=apps" {t.Errorf("refused team redirect = %q", got)diff --git a/server/internal/integrations/composio/state.go b/server/internal/integrations/composio/state.goindex 3946b853b4..fa86ff437b 100644--- a/server/internal/integrations/composio/state.go+++ b/server/internal/integrations/composio/state.go@@ -44,6 +44,9 @@ type stateClaims struct {// workspace that owns it and the admin who started the handshake.WorkspaceID string `json:"w,omitempty"`ConnectedBy string `json:"c,omitempty"`+ // PersonalWorkspaceID is the workspace a personal account is made in;+ // empty for the legacy connect, whose accounts count in every workspace.+ PersonalWorkspaceID string `json:"pw,omitempty"`// ReturnTo is the app path the browser goes back to, e.g. the issue whose// connect card started the flow. Validated by SafeReturnPath at sign time.ReturnTo string `json:"r,omitempty"`diff --git a/server/internal/integrations/composio/team.go b/server/internal/integrations/composio/team.goindex 97fdfe511f..5d67b3fd40 100644--- a/server/internal/integrations/composio/team.go+++ b/server/internal/integrations/composio/team.go@@ -61,8 +61,13 @@ type CallbackResult struct {ToolkitSlug string// WorkspaceID is set for a team account.WorkspaceID string- // UserID is the member who connected a personal account.- UserID string+ // UserID is the member who connected a personal account, and+ // PersonalWorkspaceID the workspace it belongs to (empty for a legacy+ // account).+ UserID string+ PersonalWorkspaceID string+ // ConnectedBy is the admin who connected a team account.+ ConnectedBy string// ReturnTo is the app path the flow started from, if any.ReturnTo string}diff --git a/server/migrations/728_app_account_requests.down.sql b/server/migrations/728_app_account_requests.down.sqlnew file mode 100644index 0000000000..d9d9e2052a--- /dev/null+++ b/server/migrations/728_app_account_requests.down.sql@@ -0,0 +1,6 @@+ALTER TABLE remote_app_connection DROP COLUMN IF EXISTS workspace_id;+ALTER TABLE user_composio_connection DROP COLUMN IF EXISTS workspace_id;+DELETE FROM app_action_request WHERE task_id IS NULL OR agent_id IS NULL;+ALTER TABLE app_action_request+ ALTER COLUMN task_id SET NOT NULL,+ ALTER COLUMN agent_id SET NOT NULL;diff --git a/server/migrations/728_app_account_requests.up.sql b/server/migrations/728_app_account_requests.up.sqlnew file mode 100644index 0000000000..ff5ab93102--- /dev/null+++ b/server/migrations/728_app_account_requests.up.sql@@ -0,0 +1,18 @@+-- MUL-8990: one request for every missing account. A member asking the+-- admins for a team account is an app_action_request with no run behind it,+-- so task_id and agent_id become optional; an agent's request still carries+-- both.+ALTER TABLE app_action_request+ ALTER COLUMN task_id DROP NOT NULL,+ ALTER COLUMN agent_id DROP NOT NULL;++-- Personal accounts belong to one workspace. Rows written before this+-- migration have no workspace and keep working in every workspace of their+-- owner; new connections are recorded with the workspace they were made in.+ALTER TABLE user_composio_connection ADD COLUMN IF NOT EXISTS workspace_id UUID;++-- Remote app accounts carry their workspace too, team rows included, so the+-- owner key in 724 can tell one member's accounts in two workspaces apart.+ALTER TABLE remote_app_connection ADD COLUMN IF NOT EXISTS workspace_id UUID;+UPDATE remote_app_connection SET workspace_id = owner_id+WHERE scope = 'team' AND workspace_id IS NULL;diff --git a/server/migrations/729_remote_app_connection_workspace_idx.down.sql b/server/migrations/729_remote_app_connection_workspace_idx.down.sqlnew file mode 100644index 0000000000..e87dfed7ad--- /dev/null+++ b/server/migrations/729_remote_app_connection_workspace_idx.down.sql@@ -0,0 +1 @@+DROP INDEX CONCURRENTLY IF EXISTS uq_remote_app_connection_owner_ws;diff --git a/server/migrations/729_remote_app_connection_workspace_idx.up.sql b/server/migrations/729_remote_app_connection_workspace_idx.up.sqlnew file mode 100644index 0000000000..5f1427b43b--- /dev/null+++ b/server/migrations/729_remote_app_connection_workspace_idx.up.sql@@ -0,0 +1,4 @@+-- One account per owner, app and workspace: a member can hold the same app+-- in two workspaces. Replaces uq_remote_app_connection_owner (dropped in 730).+CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS uq_remote_app_connection_owner_ws+ ON remote_app_connection (scope, owner_id, app_slug, workspace_id);diff --git a/server/migrations/730_drop_remote_app_connection_owner_idx.down.sql b/server/migrations/730_drop_remote_app_connection_owner_idx.down.sqlnew file mode 100644index 0000000000..1dbef656df--- /dev/null+++ b/server/migrations/730_drop_remote_app_connection_owner_idx.down.sql@@ -0,0 +1,4 @@+-- Fails while one member holds the same app in two workspaces; remove the+-- extra accounts before rolling back.+CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS uq_remote_app_connection_owner+ ON remote_app_connection (scope, owner_id, app_slug);diff --git a/server/migrations/730_drop_remote_app_connection_owner_idx.up.sql b/server/migrations/730_drop_remote_app_connection_owner_idx.up.sqlnew file mode 100644index 0000000000..0bed0febd4--- /dev/null+++ b/server/migrations/730_drop_remote_app_connection_owner_idx.up.sql@@ -0,0 +1 @@+DROP INDEX CONCURRENTLY IF EXISTS uq_remote_app_connection_owner;diff --git a/server/pkg/db/generated/composio.sql.go b/server/pkg/db/generated/composio.sql.goindex 4d266afc55..ea9e6b2c5f 100644--- a/server/pkg/db/generated/composio.sql.go+++ b/server/pkg/db/generated/composio.sql.go@@ -12,7 +12,7 @@ import ()const getUserComposioConnection = `-- name: GetUserComposioConnection :one-SELECT id, user_id, toolkit_slug, auth_config_id, connected_account_id, composio_user_id, status, connected_at, last_used_at, created_at, updated_at FROM user_composio_connection+SELECT id, user_id, toolkit_slug, auth_config_id, connected_account_id, composio_user_id, status, connected_at, last_used_at, created_at, updated_at, workspace_id FROM user_composio_connectionWHERE id = $1 AND user_id = $2`@@ -38,18 +38,68 @@ func (q *Queries) GetUserComposioConnection(ctx context.Context, arg GetUserComp&i.LastUsedAt,&i.CreatedAt,&i.UpdatedAt,+ &i.WorkspaceID,)return i, err}const listActiveUserComposioConnections = `-- name: ListActiveUserComposioConnections :many-SELECT id, user_id, toolkit_slug, auth_config_id, connected_account_id, composio_user_id, status, connected_at, last_used_at, created_at, updated_at FROM user_composio_connection+SELECT id, user_id, toolkit_slug, auth_config_id, connected_account_id, composio_user_id, status, connected_at, last_used_at, created_at, updated_at, workspace_id FROM user_composio_connection+WHERE user_id = $1 AND status = 'active'+ AND (workspace_id = $2::uuid OR workspace_id IS NULL)+ORDER BY (workspace_id IS NULL), connected_at DESC+`++type ListActiveUserComposioConnectionsParams struct {+ UserID pgtype.UUID `json:"user_id"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+}++// A member's active personal accounts in one workspace, plus the ones made+// before accounts belonged to a workspace. This workspace's own come first,+// so a reader keeping the first row per app prefers them.+func (q *Queries) ListActiveUserComposioConnections(ctx context.Context, arg ListActiveUserComposioConnectionsParams) ([]UserComposioConnection, error) {+ rows, err := q.db.Query(ctx, listActiveUserComposioConnections, arg.UserID, arg.WorkspaceID)+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ items := []UserComposioConnection{}+ for rows.Next() {+ var i UserComposioConnection+ if err := rows.Scan(+ &i.ID,+ &i.UserID,+ &i.ToolkitSlug,+ &i.AuthConfigID,+ &i.ConnectedAccountID,+ &i.ComposioUserID,+ &i.Status,+ &i.ConnectedAt,+ &i.LastUsedAt,+ &i.CreatedAt,+ &i.UpdatedAt,+ &i.WorkspaceID,+ ); err != nil {+ return nil, err+ }+ items = append(items, i)+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }+ return items, nil+}++const listAllActiveUserComposioConnections = `-- name: ListAllActiveUserComposioConnections :many+SELECT id, user_id, toolkit_slug, auth_config_id, connected_account_id, composio_user_id, status, connected_at, last_used_at, created_at, updated_at, workspace_id FROM user_composio_connectionWHERE user_id = $1 AND status = 'active'ORDER BY connected_at DESC`-func (q *Queries) ListActiveUserComposioConnections(ctx context.Context, userID pgtype.UUID) ([]UserComposioConnection, error) {- rows, err := q.db.Query(ctx, listActiveUserComposioConnections, userID)+// Every active personal account of a member, in any workspace.+func (q *Queries) ListAllActiveUserComposioConnections(ctx context.Context, userID pgtype.UUID) ([]UserComposioConnection, error) {+ rows, err := q.db.Query(ctx, listAllActiveUserComposioConnections, userID)if err != nil {return nil, err}@@ -69,6 +119,7 @@ func (q *Queries) ListActiveUserComposioConnections(ctx context.Context, userID&i.LastUsedAt,&i.CreatedAt,&i.UpdatedAt,+ &i.WorkspaceID,); err != nil {return nil, err}@@ -101,9 +152,9 @@ func (q *Queries) MarkUserComposioConnectionRevoked(ctx context.Context, arg Marconst upsertUserComposioConnection = `-- name: UpsertUserComposioConnection :oneINSERT INTO user_composio_connection (- user_id, toolkit_slug, auth_config_id, connected_account_id, composio_user_id, status+ user_id, toolkit_slug, auth_config_id, connected_account_id, composio_user_id, status, workspace_id) VALUES (- $1, $2, $3, $4, $5, 'active'+ $1, $2, $3, $4, $5, 'active', $6::uuid)ON CONFLICT (user_id, connected_account_id) DO UPDATE SETtoolkit_slug = EXCLUDED.toolkit_slug,@@ -111,7 +162,7 @@ ON CONFLICT (user_id, connected_account_id) DO UPDATE SETcomposio_user_id = EXCLUDED.composio_user_id,status = 'active',updated_at = now()-RETURNING id, user_id, toolkit_slug, auth_config_id, connected_account_id, composio_user_id, status, connected_at, last_used_at, created_at, updated_at+RETURNING id, user_id, toolkit_slug, auth_config_id, connected_account_id, composio_user_id, status, connected_at, last_used_at, created_at, updated_at, workspace_id`type UpsertUserComposioConnectionParams struct {@@ -120,6 +171,7 @@ type UpsertUserComposioConnectionParams struct {AuthConfigID string `json:"auth_config_id"`ConnectedAccountID string `json:"connected_account_id"`ComposioUserID string `json:"composio_user_id"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`}// =====================@@ -136,6 +188,7 @@ func (q *Queries) UpsertUserComposioConnection(ctx context.Context, arg UpsertUsarg.AuthConfigID,arg.ConnectedAccountID,arg.ComposioUserID,+ arg.WorkspaceID,)var i UserComposioConnectionerr := row.Scan(@@ -150,6 +203,7 @@ func (q *Queries) UpsertUserComposioConnection(ctx context.Context, arg UpsertUs&i.LastUsedAt,&i.CreatedAt,&i.UpdatedAt,+ &i.WorkspaceID,)return i, err}diff --git a/server/pkg/db/generated/connected_apps.sql.go b/server/pkg/db/generated/connected_apps.sql.goindex b3782b0fb4..535e0b2e7d 100644--- a/server/pkg/db/generated/connected_apps.sql.go+++ b/server/pkg/db/generated/connected_apps.sql.go@@ -35,6 +35,44 @@ func (q *Queries) AppendQueuedTaskHandoffNote(ctx context.Context, arg AppendQuereturn result.RowsAffected(), nil}+const archiveAppRequestInbox = `-- name: ArchiveAppRequestInbox :many+UPDATE inbox_item SET archived = true, snoozed_until = NULL, snoozed_at = NULL, returned_at = NULL+WHERE workspace_id = $1 AND type = 'app_connect_requested' AND archived = false+ AND details->>'request_id' = $2::text+RETURNING recipient_type, recipient_id+`++type ArchiveAppRequestInboxParams struct {+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ RequestID string `json:"request_id"`+}++type ArchiveAppRequestInboxRow struct {+ RecipientType string `json:"recipient_type"`+ RecipientID pgtype.UUID `json:"recipient_id"`+}++// A withdrawn ask leaves the admins nothing to answer.+func (q *Queries) ArchiveAppRequestInbox(ctx context.Context, arg ArchiveAppRequestInboxParams) ([]ArchiveAppRequestInboxRow, error) {+ rows, err := q.db.Query(ctx, archiveAppRequestInbox, arg.WorkspaceID, arg.RequestID)+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ items := []ArchiveAppRequestInboxRow{}+ for rows.Next() {+ var i ArchiveAppRequestInboxRow+ if err := rows.Scan(&i.RecipientType, &i.RecipientID); err != nil {+ return nil, err+ }+ items = append(items, i)+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }+ return items, nil+}+const cancelAppActionRequest = `-- name: CancelAppActionRequest :oneUPDATE app_action_requestSET status = 'cancelled', updated_at = now()@@ -205,6 +243,7 @@ SET reminded_at = now(), updated_at = now()WHERE id IN (SELECT r.id FROM app_action_request rWHERE r.status = 'pending' AND r.reminded_at IS NULL+ AND NOT (r.kind = 'connect' AND r.account_scope = 'team')AND r.expires_at <= now() + interval '2 hours'AND r.expires_at > now()ORDER BY r.expires_at@@ -425,7 +464,8 @@ SET status = $3,decided_by = $4,decided_at = now(),updated_at = now()-WHERE id = $1 AND workspace_id = $2 AND status = 'pending' AND approver_user_id = $4+WHERE id = $1 AND workspace_id = $2 AND status = 'pending'+ AND (approver_user_id = $4 OR ($7::bool AND kind = 'connect' AND account_scope = 'team'))RETURNING id, workspace_id, kind, status, task_id, agent_id, issue_id, chat_session_id, approver_user_id, account_scope, toolkit_slug, tool_slug, action_class, arguments, summary, approved_arguments, result, error, reason, expires_at, reminded_at, decided_by, decided_at, created_at, updated_at`@@ -436,6 +476,7 @@ type DecideAppActionRequestParams struct {DecidedBy pgtype.UUID `json:"decided_by"`ApprovedArguments []byte `json:"approved_arguments"`Reason pgtype.Text `json:"reason"`+ AsAdmin bool `json:"as_admin"`}// Compare-and-set from pending: a second click, another device, or the expiry@@ -448,6 +489,7 @@ func (q *Queries) DecideAppActionRequest(ctx context.Context, arg DecideAppActioarg.DecidedBy,arg.ApprovedArguments,arg.Reason,+ arg.AsAdmin,)var i AppActionRequesterr := row.Scan(@@ -627,6 +669,53 @@ func (q *Queries) FindPendingAppActionRequest(ctx context.Context, arg FindPendireturn i, err}+const findPendingTeamAsk = `-- name: FindPendingTeamAsk :one+SELECT id, workspace_id, kind, status, task_id, agent_id, issue_id, chat_session_id, approver_user_id, account_scope, toolkit_slug, tool_slug, action_class, arguments, summary, approved_arguments, result, error, reason, expires_at, reminded_at, decided_by, decided_at, created_at, updated_at FROM app_action_request+WHERE workspace_id = $1 AND toolkit_slug = $2 AND approver_user_id = $3+ AND task_id IS NULL AND kind = 'connect' AND account_scope = 'team' AND status = 'pending'+LIMIT 1+`++type FindPendingTeamAskParams struct {+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ ToolkitSlug string `json:"toolkit_slug"`+ ApproverUserID pgtype.UUID `json:"approver_user_id"`+}++// A member's own open ask for a team account, made outside any run.+func (q *Queries) FindPendingTeamAsk(ctx context.Context, arg FindPendingTeamAskParams) (AppActionRequest, error) {+ row := q.db.QueryRow(ctx, findPendingTeamAsk, arg.WorkspaceID, arg.ToolkitSlug, arg.ApproverUserID)+ var i AppActionRequest+ err := row.Scan(+ &i.ID,+ &i.WorkspaceID,+ &i.Kind,+ &i.Status,+ &i.TaskID,+ &i.AgentID,+ &i.IssueID,+ &i.ChatSessionID,+ &i.ApproverUserID,+ &i.AccountScope,+ &i.ToolkitSlug,+ &i.ToolSlug,+ &i.ActionClass,+ &i.Arguments,+ &i.Summary,+ &i.ApprovedArguments,+ &i.Result,+ &i.Error,+ &i.Reason,+ &i.ExpiresAt,+ &i.RemindedAt,+ &i.DecidedBy,+ &i.DecidedAt,+ &i.CreatedAt,+ &i.UpdatedAt,+ )+ return i, err+}+const getAppActionRequest = `-- name: GetAppActionRequest :oneSELECT id, workspace_id, kind, status, task_id, agent_id, issue_id, chat_session_id, approver_user_id, account_scope, toolkit_slug, tool_slug, action_class, arguments, summary, approved_arguments, result, error, reason, expires_at, reminded_at, decided_by, decided_at, created_at, updated_at FROM app_action_requestWHERE id = $1 AND workspace_id = $2@@ -885,6 +974,38 @@ func (q *Queries) ListAgentAppsInWorkspace(ctx context.Context, workspaceID pgtyreturn items, nil}+const listAgentsWithActiveTasksForOriginator = `-- name: ListAgentsWithActiveTasksForOriginator :many+SELECT DISTINCT agent_id FROM agent_task_queue+WHERE agent_id = ANY($1::uuid[])+ AND originator_user_id = $2+ AND status IN ('queued', 'dispatched', 'running')+`++type ListAgentsWithActiveTasksForOriginatorParams struct {+ AgentIds []pgtype.UUID `json:"agent_ids"`+ OriginatorUserID pgtype.UUID `json:"originator_user_id"`+}++func (q *Queries) ListAgentsWithActiveTasksForOriginator(ctx context.Context, arg ListAgentsWithActiveTasksForOriginatorParams) ([]pgtype.UUID, error) {+ rows, err := q.db.Query(ctx, listAgentsWithActiveTasksForOriginator, arg.AgentIds, arg.OriginatorUserID)+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ items := []pgtype.UUID{}+ for rows.Next() {+ var agent_id pgtype.UUID+ if err := rows.Scan(&agent_id); err != nil {+ return nil, err+ }+ items = append(items, agent_id)+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }+ return items, nil+}+const listAppActionRules = `-- name: ListAppActionRules :manySELECT id, workspace_id, owner_user_id, toolkit_slug, action_class, policy, updated_by, updated_at FROM app_action_ruleWHERE workspace_id = $1@@ -1195,7 +1316,8 @@ func (q *Queries) ListIssueAppToolCalls(ctx context.Context, arg ListIssueAppTooconst listPendingAppActionRequestsForApprover = `-- name: ListPendingAppActionRequestsForApprover :manySELECT id, workspace_id, kind, status, task_id, agent_id, issue_id, chat_session_id, approver_user_id, account_scope, toolkit_slug, tool_slug, action_class, arguments, summary, approved_arguments, result, error, reason, expires_at, reminded_at, decided_by, decided_at, created_at, updated_at FROM app_action_request-WHERE workspace_id = $1 AND approver_user_id = $2 AND status = 'pending'+WHERE workspace_id = $1 AND status = 'pending'+ AND (approver_user_id = $2 OR ($3::bool AND kind = 'connect' AND account_scope = 'team'))ORDER BY created_atLIMIT 200`@@ -1203,10 +1325,13 @@ LIMIT 200type ListPendingAppActionRequestsForApproverParams struct {WorkspaceID pgtype.UUID `json:"workspace_id"`ApproverUserID pgtype.UUID `json:"approver_user_id"`+ AsAdmin bool `json:"as_admin"`}+// Requests waiting on the person, and for an admin also every request for a+// team account, which any admin answers.func (q *Queries) ListPendingAppActionRequestsForApprover(ctx context.Context, arg ListPendingAppActionRequestsForApproverParams) ([]AppActionRequest, error) {- rows, err := q.db.Query(ctx, listPendingAppActionRequestsForApprover, arg.WorkspaceID, arg.ApproverUserID)+ rows, err := q.db.Query(ctx, listPendingAppActionRequestsForApprover, arg.WorkspaceID, arg.ApproverUserID, arg.AsAdmin)if err != nil {return nil, err}@@ -1371,11 +1496,12 @@ func (q *Queries) ListPendingAppActionRequestsForIssue(ctx context.Context, argconst listPendingConnectRequestsForUser = `-- name: ListPendingConnectRequestsForUser :manySELECT id, workspace_id, kind, status, task_id, agent_id, issue_id, chat_session_id, approver_user_id, account_scope, toolkit_slug, tool_slug, action_class, arguments, summary, approved_arguments, result, error, reason, expires_at, reminded_at, decided_by, decided_at, created_at, updated_at FROM app_action_request-WHERE approver_user_id = $1 AND toolkit_slug = $2 AND kind = 'connect'+WHERE workspace_id = $1 AND approver_user_id = $2 AND toolkit_slug = $3 AND kind = 'connect'AND status = 'pending' AND account_scope = 'personal'`type ListPendingConnectRequestsForUserParams struct {+ WorkspaceID pgtype.UUID `json:"workspace_id"`ApproverUserID pgtype.UUID `json:"approver_user_id"`ToolkitSlug string `json:"toolkit_slug"`}@@ -1383,7 +1509,68 @@ type ListPendingConnectRequestsForUserParams struct {// Connection requests a member is asked to answer for one app; resolved when// they finish connecting it.func (q *Queries) ListPendingConnectRequestsForUser(ctx context.Context, arg ListPendingConnectRequestsForUserParams) ([]AppActionRequest, error) {- rows, err := q.db.Query(ctx, listPendingConnectRequestsForUser, arg.ApproverUserID, arg.ToolkitSlug)+ rows, err := q.db.Query(ctx, listPendingConnectRequestsForUser, arg.WorkspaceID, arg.ApproverUserID, arg.ToolkitSlug)+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ items := []AppActionRequest{}+ for rows.Next() {+ var i AppActionRequest+ if err := rows.Scan(+ &i.ID,+ &i.WorkspaceID,+ &i.Kind,+ &i.Status,+ &i.TaskID,+ &i.AgentID,+ &i.IssueID,+ &i.ChatSessionID,+ &i.ApproverUserID,+ &i.AccountScope,+ &i.ToolkitSlug,+ &i.ToolSlug,+ &i.ActionClass,+ &i.Arguments,+ &i.Summary,+ &i.ApprovedArguments,+ &i.Result,+ &i.Error,+ &i.Reason,+ &i.ExpiresAt,+ &i.RemindedAt,+ &i.DecidedBy,+ &i.DecidedAt,+ &i.CreatedAt,+ &i.UpdatedAt,+ ); err != nil {+ return nil, err+ }+ items = append(items, i)+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }+ return items, nil+}++const listPendingTeamConnectRequests = `-- name: ListPendingTeamConnectRequests :many+SELECT id, workspace_id, kind, status, task_id, agent_id, issue_id, chat_session_id, approver_user_id, account_scope, toolkit_slug, tool_slug, action_class, arguments, summary, approved_arguments, result, error, reason, expires_at, reminded_at, decided_by, decided_at, created_at, updated_at FROM app_action_request+WHERE workspace_id = $1 AND toolkit_slug = $2 AND kind = 'connect'+ AND account_scope = 'team' AND status = 'pending'+ORDER BY created_at+LIMIT 500+`++type ListPendingTeamConnectRequestsParams struct {+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ ToolkitSlug string `json:"toolkit_slug"`+}++// Everything waiting for the workspace's team account for one app: agents'+// requests and members' asks. Connecting the account answers them all.+func (q *Queries) ListPendingTeamConnectRequests(ctx context.Context, arg ListPendingTeamConnectRequestsParams) ([]AppActionRequest, error) {+ rows, err := q.db.Query(ctx, listPendingTeamConnectRequests, arg.WorkspaceID, arg.ToolkitSlug)if err != nil {return nil, err}@@ -1428,6 +1615,60 @@ func (q *Queries) ListPendingConnectRequestsForUser(ctx context.Context, arg Lisreturn items, nil}+const listPersonalAppAgentsForUser = `-- name: ListPersonalAppAgentsForUser :many+SELECT a.id, a.name, a.workspace_id, w.name AS workspace_name+FROM agent_app aa+JOIN agent a ON a.id = aa.agent_id AND a.workspace_id = aa.workspace_id+JOIN member m ON m.workspace_id = aa.workspace_id AND m.user_id = $1+JOIN workspace w ON w.id = aa.workspace_id+WHERE aa.toolkit_slug = $2+ AND aa.account_scope = 'personal'+ AND a.archived_at IS NULL+ AND a.kind = 'user'+ORDER BY w.name, a.name, a.id+LIMIT 200+`++type ListPersonalAppAgentsForUserParams struct {+ UserID pgtype.UUID `json:"user_id"`+ ToolkitSlug string `json:"toolkit_slug"`+}++type ListPersonalAppAgentsForUserRow struct {+ ID pgtype.UUID `json:"id"`+ Name string `json:"name"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ WorkspaceName string `json:"workspace_name"`+}++// Agents in every workspace the user belongs to that act through the+// personal account of whoever triggers them for one app. The caller still+// filters by who may run each agent.+func (q *Queries) ListPersonalAppAgentsForUser(ctx context.Context, arg ListPersonalAppAgentsForUserParams) ([]ListPersonalAppAgentsForUserRow, error) {+ rows, err := q.db.Query(ctx, listPersonalAppAgentsForUser, arg.UserID, arg.ToolkitSlug)+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ items := []ListPersonalAppAgentsForUserRow{}+ for rows.Next() {+ var i ListPersonalAppAgentsForUserRow+ if err := rows.Scan(+ &i.ID,+ &i.Name,+ &i.WorkspaceID,+ &i.WorkspaceName,+ ); err != nil {+ return nil, err+ }+ items = append(items, i)+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }+ return items, nil+}+const listPersonalAppToolCalls = `-- name: ListPersonalAppToolCalls :manySELECT id, workspace_id, task_id, agent_id, issue_id, chat_session_id, triggered_by, account_scope, account_owner_user_id, toolkit_slug, tool_slug, action_class, outcome, request_id, error, created_at FROM app_tool_callWHERE workspace_id = $1 AND toolkit_slug = $2 AND account_scope = 'personal'@@ -1486,6 +1727,56 @@ func (q *Queries) ListPersonalAppToolCalls(ctx context.Context, arg ListPersonalreturn items, nil}+const listTeamAccountRequestSummaries = `-- name: ListTeamAccountRequestSummaries :many+SELECT toolkit_slug,+ array_agg(approver_user_id ORDER BY created_at)::uuid[] AS requested_by,+ COALESCE(array_agg(approver_user_id ORDER BY created_at) FILTER (WHERE task_id IS NULL), '{}')::uuid[] AS asked_by,+ COALESCE(array_agg(agent_id ORDER BY created_at) FILTER (WHERE agent_id IS NOT NULL), '{}')::uuid[] AS agent_ids,+ max(created_at)::timestamptz AS last_requested_at+FROM app_action_request+WHERE workspace_id = $1 AND kind = 'connect' AND account_scope = 'team' AND status = 'pending'+GROUP BY toolkit_slug+ORDER BY max(created_at) DESC+LIMIT 500+`++type ListTeamAccountRequestSummariesRow struct {+ ToolkitSlug string `json:"toolkit_slug"`+ RequestedBy []pgtype.UUID `json:"requested_by"`+ AskedBy []pgtype.UUID `json:"asked_by"`+ AgentIds []pgtype.UUID `json:"agent_ids"`+ LastRequestedAt pgtype.Timestamptz `json:"last_requested_at"`+}++// One row per app with open requests for a team account: who is waiting and+// which agents, oldest first. A person or agent waiting on several requests+// repeats; callers drop the repeats.+func (q *Queries) ListTeamAccountRequestSummaries(ctx context.Context, workspaceID pgtype.UUID) ([]ListTeamAccountRequestSummariesRow, error) {+ rows, err := q.db.Query(ctx, listTeamAccountRequestSummaries, workspaceID)+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ items := []ListTeamAccountRequestSummariesRow{}+ for rows.Next() {+ var i ListTeamAccountRequestSummariesRow+ if err := rows.Scan(+ &i.ToolkitSlug,+ &i.RequestedBy,+ &i.AskedBy,+ &i.AgentIds,+ &i.LastRequestedAt,+ ); err != nil {+ return nil, err+ }+ items = append(items, i)+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }+ return items, nil+}+const listTeamAppToolCalls = `-- name: ListTeamAppToolCalls :manySELECT id, workspace_id, task_id, agent_id, issue_id, chat_session_id, triggered_by, account_scope, account_owner_user_id, toolkit_slug, tool_slug, action_class, outcome, request_id, error, created_at FROM app_tool_callWHERE workspace_id = $1 AND toolkit_slug = $2 AND account_scope = 'team'@@ -1537,14 +1828,21 @@ func (q *Queries) ListTeamAppToolCalls(ctx context.Context, arg ListTeamAppToolC}const listUserComposioConnectionsAnyStatus = `-- name: ListUserComposioConnectionsAnyStatus :many-SELECT id, user_id, toolkit_slug, auth_config_id, connected_account_id, composio_user_id, status, connected_at, last_used_at, created_at, updated_at FROM user_composio_connection+SELECT id, user_id, toolkit_slug, auth_config_id, connected_account_id, composio_user_id, status, connected_at, last_used_at, created_at, updated_at, workspace_id FROM user_composio_connectionWHERE user_id = $1 AND status <> 'revoked'-ORDER BY connected_at DESC+ AND (workspace_id = $2::uuid OR workspace_id IS NULL)+ORDER BY (workspace_id IS NULL), connected_at DESC`-// A member's personal accounts for the app list: active and expired.-func (q *Queries) ListUserComposioConnectionsAnyStatus(ctx context.Context, userID pgtype.UUID) ([]UserComposioConnection, error) {- rows, err := q.db.Query(ctx, listUserComposioConnectionsAnyStatus, userID)+type ListUserComposioConnectionsAnyStatusParams struct {+ UserID pgtype.UUID `json:"user_id"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+}++// A member's personal accounts in one workspace for the app list: active and+// expired.+func (q *Queries) ListUserComposioConnectionsAnyStatus(ctx context.Context, arg ListUserComposioConnectionsAnyStatusParams) ([]UserComposioConnection, error) {+ rows, err := q.db.Query(ctx, listUserComposioConnectionsAnyStatus, arg.UserID, arg.WorkspaceID)if err != nil {return nil, err}@@ -1564,6 +1862,7 @@ func (q *Queries) ListUserComposioConnectionsAnyStatus(ctx context.Context, user&i.LastUsedAt,&i.CreatedAt,&i.UpdatedAt,+ &i.WorkspaceID,); err != nil {return nil, err}diff --git a/server/pkg/db/generated/models.go b/server/pkg/db/generated/models.goindex 57153b3b3d..f7face36d6 100644--- a/server/pkg/db/generated/models.go+++ b/server/pkg/db/generated/models.go@@ -1814,6 +1814,7 @@ type RemoteAppConnection struct {LastUsedAt pgtype.Timestamptz `json:"last_used_at"`CreatedAt pgtype.Timestamptz `json:"created_at"`UpdatedAt pgtype.Timestamptz `json:"updated_at"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`}type RemoteAppOauthClient struct {@@ -2143,6 +2144,7 @@ type UserComposioConnection struct {LastUsedAt pgtype.Timestamptz `json:"last_used_at"`CreatedAt pgtype.Timestamptz `json:"created_at"`UpdatedAt pgtype.Timestamptz `json:"updated_at"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`}type VcsCommitStatus struct {diff --git a/server/pkg/db/generated/remote_apps.sql.go b/server/pkg/db/generated/remote_apps.sql.goindex 8bb297dc70..070a1d1bd4 100644--- a/server/pkg/db/generated/remote_apps.sql.go+++ b/server/pkg/db/generated/remote_apps.sql.go@@ -23,18 +23,27 @@ func (q *Queries) DeleteRemoteAppOAuthClient(ctx context.Context, id pgtype.UUID}const getActiveRemoteAppConnection = `-- name: GetActiveRemoteAppConnection :one-SELECT id, app_slug, scope, owner_id, connected_by, oauth_client_id, access_token, refresh_token, expires_at, status, connected_at, last_used_at, created_at, updated_at FROM remote_app_connection+SELECT id, app_slug, scope, owner_id, connected_by, oauth_client_id, access_token, refresh_token, expires_at, status, connected_at, last_used_at, created_at, updated_at, workspace_id FROM remote_app_connectionWHERE app_slug = $1 AND scope = $2 AND owner_id = $3 AND status = 'active'+ AND (workspace_id = $4::uuid OR workspace_id IS NULL)+ORDER BY (workspace_id IS NULL)+LIMIT 1`type GetActiveRemoteAppConnectionParams struct {- AppSlug string `json:"app_slug"`- Scope string `json:"scope"`- OwnerID pgtype.UUID `json:"owner_id"`+ AppSlug string `json:"app_slug"`+ Scope string `json:"scope"`+ OwnerID pgtype.UUID `json:"owner_id"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`}func (q *Queries) GetActiveRemoteAppConnection(ctx context.Context, arg GetActiveRemoteAppConnectionParams) (RemoteAppConnection, error) {- row := q.db.QueryRow(ctx, getActiveRemoteAppConnection, arg.AppSlug, arg.Scope, arg.OwnerID)+ row := q.db.QueryRow(ctx, getActiveRemoteAppConnection,+ arg.AppSlug,+ arg.Scope,+ arg.OwnerID,+ arg.WorkspaceID,+ )var i RemoteAppConnectionerr := row.Scan(&i.ID,@@ -51,12 +60,13 @@ func (q *Queries) GetActiveRemoteAppConnection(ctx context.Context, arg GetActiv&i.LastUsedAt,&i.CreatedAt,&i.UpdatedAt,+ &i.WorkspaceID,)return i, err}const getRemoteAppConnection = `-- name: GetRemoteAppConnection :one-SELECT id, app_slug, scope, owner_id, connected_by, oauth_client_id, access_token, refresh_token, expires_at, status, connected_at, last_used_at, created_at, updated_at FROM remote_app_connection+SELECT id, app_slug, scope, owner_id, connected_by, oauth_client_id, access_token, refresh_token, expires_at, status, connected_at, last_used_at, created_at, updated_at, workspace_id FROM remote_app_connectionWHERE id = $1`@@ -78,12 +88,13 @@ func (q *Queries) GetRemoteAppConnection(ctx context.Context, id pgtype.UUID) (R&i.LastUsedAt,&i.CreatedAt,&i.UpdatedAt,+ &i.WorkspaceID,)return i, err}const getRemoteAppConnectionForOwner = `-- name: GetRemoteAppConnectionForOwner :one-SELECT id, app_slug, scope, owner_id, connected_by, oauth_client_id, access_token, refresh_token, expires_at, status, connected_at, last_used_at, created_at, updated_at FROM remote_app_connection+SELECT id, app_slug, scope, owner_id, connected_by, oauth_client_id, access_token, refresh_token, expires_at, status, connected_at, last_used_at, created_at, updated_at, workspace_id FROM remote_app_connectionWHERE id = $1 AND scope = $2 AND owner_id = $3`@@ -112,6 +123,7 @@ func (q *Queries) GetRemoteAppConnectionForOwner(ctx context.Context, arg GetRem&i.LastUsedAt,&i.CreatedAt,&i.UpdatedAt,+ &i.WorkspaceID,)return i, err}@@ -223,19 +235,23 @@ func (q *Queries) InsertRemoteAppOAuthClient(ctx context.Context, arg InsertRemo}const listRemoteAppConnectionsForOwner = `-- name: ListRemoteAppConnectionsForOwner :many-SELECT id, app_slug, scope, owner_id, connected_by, oauth_client_id, access_token, refresh_token, expires_at, status, connected_at, last_used_at, created_at, updated_at FROM remote_app_connection+SELECT id, app_slug, scope, owner_id, connected_by, oauth_client_id, access_token, refresh_token, expires_at, status, connected_at, last_used_at, created_at, updated_at, workspace_id FROM remote_app_connectionWHERE scope = $1 AND owner_id = $2 AND status <> 'revoked'-ORDER BY connected_at DESC+ AND (workspace_id = $3::uuid OR workspace_id IS NULL)+ORDER BY (workspace_id IS NULL), connected_at DESC`type ListRemoteAppConnectionsForOwnerParams struct {- Scope string `json:"scope"`- OwnerID pgtype.UUID `json:"owner_id"`+ Scope string `json:"scope"`+ OwnerID pgtype.UUID `json:"owner_id"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`}-// Every account the owner still sees: active and expired, not disconnected.+// Every account the owner still sees in one workspace: active and expired,+// not disconnected. Accounts made before they belonged to a workspace count+// in every workspace.func (q *Queries) ListRemoteAppConnectionsForOwner(ctx context.Context, arg ListRemoteAppConnectionsForOwnerParams) ([]RemoteAppConnection, error) {- rows, err := q.db.Query(ctx, listRemoteAppConnectionsForOwner, arg.Scope, arg.OwnerID)+ rows, err := q.db.Query(ctx, listRemoteAppConnectionsForOwner, arg.Scope, arg.OwnerID, arg.WorkspaceID)if err != nil {return nil, err}@@ -258,6 +274,7 @@ func (q *Queries) ListRemoteAppConnectionsForOwner(ctx context.Context, arg List&i.LastUsedAt,&i.CreatedAt,&i.UpdatedAt,+ &i.WorkspaceID,); err != nil {return nil, err}@@ -270,7 +287,7 @@ func (q *Queries) ListRemoteAppConnectionsForOwner(ctx context.Context, arg List}const lockRemoteAppConnection = `-- name: LockRemoteAppConnection :one-SELECT id, app_slug, scope, owner_id, connected_by, oauth_client_id, access_token, refresh_token, expires_at, status, connected_at, last_used_at, created_at, updated_at FROM remote_app_connection+SELECT id, app_slug, scope, owner_id, connected_by, oauth_client_id, access_token, refresh_token, expires_at, status, connected_at, last_used_at, created_at, updated_at, workspace_id FROM remote_app_connectionWHERE id = $1FOR UPDATE`@@ -295,6 +312,7 @@ func (q *Queries) LockRemoteAppConnection(ctx context.Context, id pgtype.UUID) (&i.LastUsedAt,&i.CreatedAt,&i.UpdatedAt,+ &i.WorkspaceID,)return i, err}@@ -358,11 +376,11 @@ const upsertRemoteAppConnection = `-- name: UpsertRemoteAppConnection :oneINSERT INTO remote_app_connection (app_slug, scope, owner_id, connected_by, oauth_client_id,- access_token, refresh_token, expires_at, status+ access_token, refresh_token, expires_at, status, workspace_id) VALUES (- $1, $2, $3, $4, $5, $6, $7, $8, 'active'+ $1, $2, $3, $4, $5, $6, $7, $8, 'active', $9)-ON CONFLICT (scope, owner_id, app_slug) DO UPDATE SET+ON CONFLICT (scope, owner_id, app_slug, workspace_id) DO UPDATE SETconnected_by = EXCLUDED.connected_by,oauth_client_id = EXCLUDED.oauth_client_id,access_token = EXCLUDED.access_token,@@ -371,7 +389,7 @@ ON CONFLICT (scope, owner_id, app_slug) DO UPDATE SETstatus = 'active',connected_at = now(),updated_at = now()-RETURNING id, app_slug, scope, owner_id, connected_by, oauth_client_id, access_token, refresh_token, expires_at, status, connected_at, last_used_at, created_at, updated_at+RETURNING id, app_slug, scope, owner_id, connected_by, oauth_client_id, access_token, refresh_token, expires_at, status, connected_at, last_used_at, created_at, updated_at, workspace_id`type UpsertRemoteAppConnectionParams struct {@@ -383,6 +401,7 @@ type UpsertRemoteAppConnectionParams struct {AccessToken []byte `json:"access_token"`RefreshToken []byte `json:"refresh_token"`ExpiresAt pgtype.Timestamptz `json:"expires_at"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`}// =====================@@ -398,6 +417,7 @@ func (q *Queries) UpsertRemoteAppConnection(ctx context.Context, arg UpsertRemotarg.AccessToken,arg.RefreshToken,arg.ExpiresAt,+ arg.WorkspaceID,)var i RemoteAppConnectionerr := row.Scan(@@ -415,6 +435,7 @@ func (q *Queries) UpsertRemoteAppConnection(ctx context.Context, arg UpsertRemot&i.LastUsedAt,&i.CreatedAt,&i.UpdatedAt,+ &i.WorkspaceID,)return i, err}diff --git a/server/pkg/db/generated/workspace_delete.sql.go b/server/pkg/db/generated/workspace_delete.sql.goindex ae98f75ff7..0ddfbfa646 100644--- a/server/pkg/db/generated/workspace_delete.sql.go+++ b/server/pkg/db/generated/workspace_delete.sql.go@@ -541,8 +541,12 @@ deleted_weixin_account_states AS (deleted_workspace_composio_connections AS (DELETE FROM workspace_composio_connection WHERE workspace_id = $1),-deleted_team_remote_app_connections AS (- DELETE FROM remote_app_connection WHERE scope = 'team' AND owner_id = $1+deleted_remote_app_connections AS (+ DELETE FROM remote_app_connection+ WHERE (scope = 'team' AND owner_id = $1) OR workspace_id = $1+),+deleted_personal_composio_connections AS (+ DELETE FROM user_composio_connection WHERE workspace_id = $1),deleted_agent_apps AS (DELETE FROM agent_app WHERE workspace_id = $1diff --git a/server/pkg/db/queries/composio.sql b/server/pkg/db/queries/composio.sqlindex e4674b4b4b..2d6c5cc53b 100644--- a/server/pkg/db/queries/composio.sql+++ b/server/pkg/db/queries/composio.sql@@ -8,9 +8,9 @@-- one. connected_at is preserved on conflict (first-connect time); updated_at-- moves so the reactivation is observable.INSERT INTO user_composio_connection (- user_id, toolkit_slug, auth_config_id, connected_account_id, composio_user_id, status+ user_id, toolkit_slug, auth_config_id, connected_account_id, composio_user_id, status, workspace_id) VALUES (- $1, $2, $3, $4, $5, 'active'+ $1, $2, $3, $4, $5, 'active', sqlc.narg('workspace_id')::uuid)ON CONFLICT (user_id, connected_account_id) DO UPDATE SETtoolkit_slug = EXCLUDED.toolkit_slug,@@ -21,6 +21,16 @@ ON CONFLICT (user_id, connected_account_id) DO UPDATE SETRETURNING *;-- name: ListActiveUserComposioConnections :many+-- A member's active personal accounts in one workspace, plus the ones made+-- before accounts belonged to a workspace. This workspace's own come first,+-- so a reader keeping the first row per app prefers them.+SELECT * FROM user_composio_connection+WHERE user_id = $1 AND status = 'active'+ AND (workspace_id = sqlc.arg('workspace_id')::uuid OR workspace_id IS NULL)+ORDER BY (workspace_id IS NULL), connected_at DESC;++-- name: ListAllActiveUserComposioConnections :many+-- Every active personal account of a member, in any workspace.SELECT * FROM user_composio_connectionWHERE user_id = $1 AND status = 'active'ORDER BY connected_at DESC;diff --git a/server/pkg/db/queries/connected_apps.sql b/server/pkg/db/queries/connected_apps.sqlindex d6f882faf6..dabc09c17d 100644--- a/server/pkg/db/queries/connected_apps.sql+++ b/server/pkg/db/queries/connected_apps.sql@@ -63,10 +63,12 @@ SET status = sqlc.arg('status')::text, updated_at = now()WHERE connected_account_id = sqlc.arg('connected_account_id')::text AND status <> 'revoked';-- name: ListUserComposioConnectionsAnyStatus :many--- A member's personal accounts for the app list: active and expired.+-- A member's personal accounts in one workspace for the app list: active and+-- expired.SELECT * FROM user_composio_connectionWHERE user_id = $1 AND status <> 'revoked'-ORDER BY connected_at DESC;+ AND (workspace_id = sqlc.arg('workspace_id')::uuid OR workspace_id IS NULL)+ORDER BY (workspace_id IS NULL), connected_at DESC;-- name: ListAgentApps :manySELECT * FROM agent_app@@ -179,8 +181,11 @@ WHERE workspace_id = $1 AND approver_user_id = $2 AND status = 'pending'RETURNING *;-- name: ListPendingAppActionRequestsForApprover :many+-- Requests waiting on the person, and for an admin also every request for a+-- team account, which any admin answers.SELECT * FROM app_action_request-WHERE workspace_id = $1 AND approver_user_id = $2 AND status = 'pending'+WHERE workspace_id = $1 AND status = 'pending'+ AND (approver_user_id = $2 OR (sqlc.arg('as_admin')::bool AND kind = 'connect' AND account_scope = 'team'))ORDER BY created_atLIMIT 200;@@ -194,7 +199,8 @@ SET status = $3,decided_by = $4,decided_at = now(),updated_at = now()-WHERE id = $1 AND workspace_id = $2 AND status = 'pending' AND approver_user_id = $4+WHERE id = $1 AND workspace_id = $2 AND status = 'pending'+ AND (approver_user_id = $4 OR (sqlc.arg('as_admin')::bool AND kind = 'connect' AND account_scope = 'team'))RETURNING *;-- name: SetAppActionRequestOutcome :one@@ -224,6 +230,7 @@ SET reminded_at = now(), updated_at = now()WHERE id IN (SELECT r.id FROM app_action_request rWHERE r.status = 'pending' AND r.reminded_at IS NULL+ AND NOT (r.kind = 'connect' AND r.account_scope = 'team')AND r.expires_at <= now() + interval '2 hours'AND r.expires_at > now()ORDER BY r.expires_at@@ -341,9 +348,47 @@ LIMIT 500;-- Connection requests a member is asked to answer for one app; resolved when-- they finish connecting it.SELECT * FROM app_action_request-WHERE approver_user_id = $1 AND toolkit_slug = $2 AND kind = 'connect'+WHERE workspace_id = $1 AND approver_user_id = $2 AND toolkit_slug = $3 AND kind = 'connect'AND status = 'pending' AND account_scope = 'personal';+-- name: ListPendingTeamConnectRequests :many+-- Everything waiting for the workspace's team account for one app: agents'+-- requests and members' asks. Connecting the account answers them all.+SELECT * FROM app_action_request+WHERE workspace_id = $1 AND toolkit_slug = $2 AND kind = 'connect'+ AND account_scope = 'team' AND status = 'pending'+ORDER BY created_at+LIMIT 500;++-- name: FindPendingTeamAsk :one+-- A member's own open ask for a team account, made outside any run.+SELECT * FROM app_action_request+WHERE workspace_id = $1 AND toolkit_slug = $2 AND approver_user_id = $3+ AND task_id IS NULL AND kind = 'connect' AND account_scope = 'team' AND status = 'pending'+LIMIT 1;++-- name: ArchiveAppRequestInbox :many+-- A withdrawn ask leaves the admins nothing to answer.+UPDATE inbox_item SET archived = true, snoozed_until = NULL, snoozed_at = NULL, returned_at = NULL+WHERE workspace_id = $1 AND type = 'app_connect_requested' AND archived = false+ AND details->>'request_id' = sqlc.arg('request_id')::text+RETURNING recipient_type, recipient_id;++-- name: ListTeamAccountRequestSummaries :many+-- One row per app with open requests for a team account: who is waiting and+-- which agents, oldest first. A person or agent waiting on several requests+-- repeats; callers drop the repeats.+SELECT toolkit_slug,+ array_agg(approver_user_id ORDER BY created_at)::uuid[] AS requested_by,+ COALESCE(array_agg(approver_user_id ORDER BY created_at) FILTER (WHERE task_id IS NULL), '{}')::uuid[] AS asked_by,+ COALESCE(array_agg(agent_id ORDER BY created_at) FILTER (WHERE agent_id IS NOT NULL), '{}')::uuid[] AS agent_ids,+ max(created_at)::timestamptz AS last_requested_at+FROM app_action_request+WHERE workspace_id = $1 AND kind = 'connect' AND account_scope = 'team' AND status = 'pending'+GROUP BY toolkit_slug+ORDER BY max(created_at) DESC+LIMIT 500;+-- name: AppendQueuedTaskHandoffNote :execrows-- Folds a decision into a run that has not been claimed yet, so approving a-- batch of requests starts one run instead of one per request.@@ -358,3 +403,25 @@ WHERE id = $1 AND status = 'queued';-- Keeps the legacy allowlist column in step with agent_app for older clients.UPDATE agent SET composio_toolkit_allowlist = sqlc.arg('slugs')::text[], updated_at = now()WHERE id = $1;++-- name: ListPersonalAppAgentsForUser :many+-- Agents in every workspace the user belongs to that act through the+-- personal account of whoever triggers them for one app. The caller still+-- filters by who may run each agent.+SELECT a.id, a.name, a.workspace_id, w.name AS workspace_name+FROM agent_app aa+JOIN agent a ON a.id = aa.agent_id AND a.workspace_id = aa.workspace_id+JOIN member m ON m.workspace_id = aa.workspace_id AND m.user_id = sqlc.arg('user_id')+JOIN workspace w ON w.id = aa.workspace_id+WHERE aa.toolkit_slug = sqlc.arg('toolkit_slug')+ AND aa.account_scope = 'personal'+ AND a.archived_at IS NULL+ AND a.kind = 'user'+ORDER BY w.name, a.name, a.id+LIMIT 200;++-- name: ListAgentsWithActiveTasksForOriginator :many+SELECT DISTINCT agent_id FROM agent_task_queue+WHERE agent_id = ANY(sqlc.arg('agent_ids')::uuid[])+ AND originator_user_id = sqlc.arg('originator_user_id')+ AND status IN ('queued', 'dispatched', 'running');diff --git a/server/pkg/db/queries/remote_apps.sql b/server/pkg/db/queries/remote_apps.sqlindex cbb95b2221..1ac6b5dd32 100644--- a/server/pkg/db/queries/remote_apps.sql+++ b/server/pkg/db/queries/remote_apps.sql@@ -34,11 +34,11 @@ DELETE FROM remote_app_oauth_client WHERE id = $1;-- name: UpsertRemoteAppConnection :oneINSERT INTO remote_app_connection (app_slug, scope, owner_id, connected_by, oauth_client_id,- access_token, refresh_token, expires_at, status+ access_token, refresh_token, expires_at, status, workspace_id) VALUES (- $1, $2, $3, $4, $5, $6, $7, $8, 'active'+ $1, $2, $3, $4, $5, $6, $7, $8, 'active', $9)-ON CONFLICT (scope, owner_id, app_slug) DO UPDATE SET+ON CONFLICT (scope, owner_id, app_slug, workspace_id) DO UPDATE SETconnected_by = EXCLUDED.connected_by,oauth_client_id = EXCLUDED.oauth_client_id,access_token = EXCLUDED.access_token,@@ -50,14 +50,20 @@ ON CONFLICT (scope, owner_id, app_slug) DO UPDATE SETRETURNING *;-- name: ListRemoteAppConnectionsForOwner :many--- Every account the owner still sees: active and expired, not disconnected.+-- Every account the owner still sees in one workspace: active and expired,+-- not disconnected. Accounts made before they belonged to a workspace count+-- in every workspace.SELECT * FROM remote_app_connectionWHERE scope = $1 AND owner_id = $2 AND status <> 'revoked'-ORDER BY connected_at DESC;+ AND (workspace_id = sqlc.arg('workspace_id')::uuid OR workspace_id IS NULL)+ORDER BY (workspace_id IS NULL), connected_at DESC;-- name: GetActiveRemoteAppConnection :oneSELECT * FROM remote_app_connection-WHERE app_slug = $1 AND scope = $2 AND owner_id = $3 AND status = 'active';+WHERE app_slug = $1 AND scope = $2 AND owner_id = $3 AND status = 'active'+ AND (workspace_id = sqlc.arg('workspace_id')::uuid OR workspace_id IS NULL)+ORDER BY (workspace_id IS NULL)+LIMIT 1;-- name: GetRemoteAppConnectionForOwner :one-- Owner-scoped, so an account cannot be changed by guessing its id.diff --git a/server/pkg/db/queries/workspace_delete.sql b/server/pkg/db/queries/workspace_delete.sqlindex 93aa0855c7..eaddf5226b 100644--- a/server/pkg/db/queries/workspace_delete.sql+++ b/server/pkg/db/queries/workspace_delete.sql@@ -515,8 +515,12 @@ deleted_weixin_account_states AS (deleted_workspace_composio_connections AS (DELETE FROM workspace_composio_connection WHERE workspace_id = $1),-deleted_team_remote_app_connections AS (- DELETE FROM remote_app_connection WHERE scope = 'team' AND owner_id = $1+deleted_remote_app_connections AS (+ DELETE FROM remote_app_connection+ WHERE (scope = 'team' AND owner_id = $1) OR workspace_id = $1+),+deleted_personal_composio_connections AS (+ DELETE FROM user_composio_connection WHERE workspace_id = $1),deleted_agent_apps AS (DELETE FROM agent_app WHERE workspace_id = $1