Skip to content

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

Go

fix(apps): show an agent's app toggle at once instead of after save + refetch (MUL-9921) (#11251)

Bohan Jiangff52f8e93464
diff --git a/packages/core/connected-apps/mutations.ts b/packages/core/connected-apps/mutations.ts
index 454d64561d..48b90a3fe6 100644
--- a/packages/core/connected-apps/mutations.ts
+++ b/packages/core/connected-apps/mutations.ts
@@ -1,7 +1,7 @@
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { api } from "../api";
import { useWorkspaceId } from "../hooks";
-import type { AppAccountScope, AppActionClass, UpdateAgentAppsRequest } from "../types";
+import type { AgentApp, AppAccountScope, AppActionClass, AppsOverview, UpdateAgentAppsRequest } from "../types";
import { workspaceKeys } from "../workspace/queries";
import { connectedAppsKeys } from "./queries";
@@ -62,19 +62,48 @@ export function useDismissTeamAppRequests() {
});
}
-/** Replaces an agent's apps. The legacy `composio_toolkit_allowlist` on the
- * agent follows server-side, so the agent list is refreshed too. */
+/** Replaces an agent's apps. The new list shows at once in the agent's apps
+ * and the overview, and rolls back if the save fails. The legacy
+ * `composio_toolkit_allowlist` on the agent follows server-side, so the agent
+ * list is refreshed too, once the last save in flight settles. */
export function useUpdateAgentApps(agentId: string) {
const qc = useQueryClient();
const wsId = useWorkspaceId();
+ const overviewKey = connectedAppsKeys.overview(wsId);
+ const appsKey = connectedAppsKeys.agentApps(wsId, agentId);
+ const showInOverview = (apps: AgentApp[]) =>
+ qc.setQueryData<AppsOverview>(overviewKey, (old) =>
+ old && { ...old, agent_apps: [...old.agent_apps.filter((a) => a.agent_id !== agentId), ...apps] });
return useMutation({
+ mutationKey: ["agent-apps", wsId],
mutationFn: (body: UpdateAgentAppsRequest) => api.updateAgentApps(agentId, body),
+ onMutate: async (body) => {
+ await Promise.all([qc.cancelQueries({ queryKey: overviewKey }), qc.cancelQueries({ queryKey: appsKey })]);
+ const prev = {
+ overview: qc.getQueryData<AppsOverview>(overviewKey)?.agent_apps.filter((a) => a.agent_id === agentId),
+ apps: qc.getQueryData<AgentApp[]>(appsKey),
+ };
+ const next = body.apps.map((a) => ({ agent_id: agentId, ...a }));
+ showInOverview(next);
+ if (prev.apps) qc.setQueryData(appsKey, next);
+ return prev;
+ },
+ onError: (_err, _body, prev) => {
+ // Only this agent's apps roll back; another agent's save stays shown.
+ if (prev?.overview) showInOverview(prev.overview);
+ if (prev?.apps) qc.setQueryData(appsKey, prev.apps);
+ },
onSuccess: (data) => {
- if (data) qc.setQueryData(connectedAppsKeys.agentApps(wsId, agentId), data.apps);
- else void qc.invalidateQueries({ queryKey: connectedAppsKeys.agentApps(wsId, agentId) });
+ if (data) {
+ qc.setQueryData(appsKey, data.apps);
+ showInOverview(data.apps);
+ } else void qc.invalidateQueries({ queryKey: appsKey });
},
onSettled: () => {
- qc.invalidateQueries({ queryKey: connectedAppsKeys.overview(wsId) });
+ // A refetch landing while another agent's save is in flight would
+ // briefly undo that save on screen; the last one to settle refetches.
+ if (qc.isMutating({ mutationKey: ["agent-apps", wsId] }) > 1) return;
+ qc.invalidateQueries({ queryKey: overviewKey });
qc.invalidateQueries({ queryKey: workspaceKeys.agents(wsId) });
},
});
diff --git a/packages/views/apps/components/app-agents-card.tsx b/packages/views/apps/components/app-agents-card.tsx
index aa78b6ba52..387c8711a1 100644
--- a/packages/views/apps/components/app-agents-card.tsx
+++ b/packages/views/apps/components/app-agents-card.tsx
@@ -1,6 +1,5 @@
"use client";
-import { useState } from "react";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { toast } from "sonner";
import {
@@ -13,7 +12,7 @@ import {
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 { 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";
@@ -94,10 +93,9 @@ function AgentAppRow({
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 disabled = !canEdit || update.isPending || teamLocked;
const status = current ? appAccountStatus(overview, current.account_scope, slug) : null;
const readiness = !current || !status
? undefined
@@ -113,18 +111,16 @@ function AgentAppRow({
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.
+ // The switch and source show the new value at once (the mutation writes it
+ // into the overview); the row stays disabled until the save lands so two
+ // saves of the same agent's list cannot race.
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) => {
+ update.mutate(agentAppsWith(overview, agent.id, slug, scope), {
+ onError: (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 (
diff --git a/packages/views/apps/components/app-detail-page.test.tsx b/packages/views/apps/components/app-detail-page.test.tsx
index 8471cabee5..9471eb8b63 100644
--- a/packages/views/apps/components/app-detail-page.test.tsx
+++ b/packages/views/apps/components/app-detail-page.test.tsx
@@ -8,7 +8,7 @@ import { NavigationProvider, type NavigationAdapter } from "../../navigation";
import { renderWithI18n } from "../../test/i18n";
import { AppDetailPage } from "./app-detail-page";
-vi.mock("@multica/core/api", () => ({ api: {
+vi.mock("@multica/core/api", () => ({ ApiError: class ApiError extends Error {}, 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(),
@@ -77,7 +77,7 @@ beforeEach(() => {
...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;
+ return { apps: overview.agent_apps.filter((a) => a.agent_id === agentId) };
});
});
afterEach(() => {
@@ -123,6 +123,35 @@ describe("AppDetailPage", () => {
await waitFor(() => expect(agentSwitch("Mine")).not.toBeChecked());
});
+ it("shows the new value before the save lands and keeps it after", async () => {
+ let finish!: () => void;
+ const saved = new Promise<void>((resolve) => { finish = resolve; });
+ const save = vi.mocked(api.updateAgentApps).getMockImplementation()!;
+ vi.mocked(api.updateAgentApps).mockImplementation(async (agentId, body) => {
+ await saved;
+ return save(agentId, body);
+ });
+ const user = userEvent.setup();
+ renderPage();
+ await waitFor(() => expect(agentSwitch("Mine")).not.toHaveAttribute("aria-disabled", "true"));
+ await user.click(agentSwitch("Mine"));
+ expect(agentSwitch("Mine")).not.toBeChecked();
+ expect(agentSwitch("Mine")).toHaveAttribute("aria-disabled", "true");
+ finish();
+ await waitFor(() => expect(agentSwitch("Mine")).not.toHaveAttribute("aria-disabled", "true"));
+ expect(agentSwitch("Mine")).not.toBeChecked();
+ });
+
+ it("puts the switch back when the save fails", async () => {
+ vi.mocked(api.updateAgentApps).mockRejectedValue(new Error("nope"));
+ const user = userEvent.setup();
+ renderPage();
+ await waitFor(() => expect(agentSwitch("Mine")).not.toHaveAttribute("aria-disabled", "true"));
+ await user.click(agentSwitch("Mine"));
+ await waitFor(() => expect(agentSwitch("Mine")).not.toHaveAttribute("aria-disabled", "true"));
+ expect(agentSwitch("Mine")).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();