Skip to content

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

Go

fix(apps): list only agents that use the viewer's accounts (MUL-9871) (#11206)

Jiayuan Zhang6438066077db
diff --git a/packages/views/agents/components/tabs/agent-apps-tab.test.tsx b/packages/views/agents/components/tabs/agent-apps-tab.test.tsx
index 68c1c91b89..7a5af2418b 100644
--- a/packages/views/agents/components/tabs/agent-apps-tab.test.tsx
+++ b/packages/views/agents/components/tabs/agent-apps-tab.test.tsx
@@ -17,9 +17,13 @@ vi.mock("@multica/core/api", async (importOriginal) => ({
...(await importOriginal<typeof import("@multica/core/api")>()),
api: {
listAgentApps: vi.fn(), getAppsOverview: vi.fn(), listAppCatalog: vi.fn(), updateAgentApps: vi.fn(),
- getWorkspaceFeatures: vi.fn(),
+ getWorkspaceFeatures: vi.fn(), listAgents: vi.fn(), listMembers: vi.fn(),
},
}));
+vi.mock("@multica/core/auth", () => {
+ const state = { user: { id: "me" } };
+ return { useAuthStore: (selector: (s: typeof state) => unknown) => selector(state) };
+});
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", apps: () => "/ws/apps" }) }));
@@ -54,6 +58,8 @@ beforeEach(() => {
});
vi.mocked(api.updateAgentApps).mockImplementation(async (_id, body) => ({ apps: body.apps.map((app) => ({ ...app, agent_id: "a1" })) }));
vi.mocked(api.getWorkspaceFeatures).mockResolvedValue({ features: {} });
+ vi.mocked(api.listAgents).mockResolvedValue([{ id: "a1", owner_id: "me", permission_mode: "private", invocation_targets: [], archived_at: null }] as never);
+ vi.mocked(api.listMembers).mockResolvedValue([{ user_id: "me", role: "member" }] as never);
});
afterEach(() => {
diff --git a/packages/views/apps/components/apps-page.test.tsx b/packages/views/apps/components/apps-page.test.tsx
index c06e589337..d2e85fbd41 100644
--- a/packages/views/apps/components/apps-page.test.tsx
+++ b/packages/views/apps/components/apps-page.test.tsx
@@ -10,7 +10,7 @@ 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(),
+ getAppsOverview: vi.fn(), listAppCatalog: vi.fn(), listAgents: vi.fn(), listMembers: 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(),
} }));
@@ -58,9 +58,10 @@ beforeEach(() => {
{ 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 },
+ { id: "a1", name: "Support", owner_id: "me", permission_mode: "private", invocation_targets: [], archived_at: null },
+ { id: "a2", name: "Triage", owner_id: "u2", permission_mode: "private", invocation_targets: [], archived_at: null },
] as never);
+ vi.mocked(api.listMembers).mockResolvedValue([{ user_id: "me", role: "member" }] as never);
vi.mocked(api.requestTeamApp).mockResolvedValue(undefined as never);
vi.mocked(api.listAppRequests).mockResolvedValue({ requests: [] } as never);
vi.mocked(api.dismissTeamAppRequests).mockResolvedValue(undefined);
@@ -252,6 +253,27 @@ describe("AppsPage › Accounts", () => {
expect(within(yours).queryByText("Slack")).not.toBeInTheDocument();
});
+ it("names only agents that act through the viewer's account under Your accounts", async () => {
+ overview.agent_apps = [
+ ...overview.agent_apps,
+ { agent_id: "shared", toolkit_slug: "gmail", account_scope: "personal", level: "write" },
+ { agent_id: "others-private", toolkit_slug: "gmail", account_scope: "personal", level: "write" },
+ { agent_id: "archived", toolkit_slug: "youtube", account_scope: "personal", level: "write" },
+ ];
+ vi.mocked(api.listAgents).mockResolvedValue([
+ { id: "a1", owner_id: "me", permission_mode: "private", invocation_targets: [], archived_at: null },
+ { id: "a2", owner_id: "u2", permission_mode: "private", invocation_targets: [], archived_at: null },
+ { id: "shared", owner_id: "u2", permission_mode: "public_to", invocation_targets: [{ target_type: "workspace", target_id: "ws-1" }], archived_at: null },
+ { id: "others-private", owner_id: "u2", permission_mode: "private", invocation_targets: [], archived_at: null },
+ { id: "archived", owner_id: "u2", permission_mode: "private", invocation_targets: [], archived_at: "2026-11-01T00:00:00Z" },
+ ] as never);
+ renderPage();
+ await waitFor(() => expect(row("personal", "gmail")).toHaveTextContent("used by Name a1, Name shared"));
+ expect(row("personal", "gmail")).not.toHaveTextContent("others-private");
+ expect(row("personal", "youtube")).toBeNull();
+ expect(screen.getByRole("tab", { name: /Accounts/ })).toHaveTextContent("5");
+ });
+
it("gives an admin Connect and Decline on a requested team account", async () => {
overview.can_manage = true;
const user = userEvent.setup();
diff --git a/packages/views/apps/components/apps-page.tsx b/packages/views/apps/components/apps-page.tsx
index 48d019f9b6..3748203901 100644
--- a/packages/views/apps/components/apps-page.tsx
+++ b/packages/views/apps/components/apps-page.tsx
@@ -17,7 +17,6 @@ import {
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";
@@ -25,6 +24,7 @@ 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 { useViewerAppsOverview } from "../../common/use-viewer-apps-overview";
import { useT } from "../../i18n";
import { useNavigation } from "../../navigation";
import { useAppConnectReturn } from "../hooks/use-app-connect-return";
@@ -73,7 +73,7 @@ function AppsDirectory() {
const overview = useQuery(appsOverviewOptions(wsId));
const teamAccess = useTeamAppAccess(overview.data);
const catalog = useQuery(appCatalogOptions(wsId));
- const agents = useQuery(agentListOptions(wsId));
+ const viewerOverview = useViewerAppsOverview(wsId, overview.data);
const restore = useRestoreAppAccess();
const requestTeam = useRequestTeamApp();
const withdrawTeam = useDismissTeamAppRequests();
@@ -83,7 +83,7 @@ function AppsDirectory() {
const [connecting, setConnecting] = useState<ConnectTarget | null>(null);
const [asking, setAsking] = useState<string | null>(null);
useAppConnectReturn();
- const accountRows = useAccountRows(overview.data, catalog.data?.apps ?? []);
+ const accountRows = useAccountRows(viewerOverview, catalog.data?.apps ?? []);
// The tab lives in the URL so a connect flow started here comes back to it.
const setTab = (next: DirectoryTab) => {
@@ -95,17 +95,9 @@ function AppsDirectory() {
};
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]);
+ if (!viewerOverview) return null;
+ return buildAppDirectory({ overview: viewerOverview, catalog: catalog.data?.apps ?? [], viewerId });
+ }, [viewerOverview, catalog.data, viewerId]);
const handlers: DirectoryCardHandlers = {
asking,
@@ -130,7 +122,7 @@ function AppsDirectory() {
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) {
+ if (overview.isError || !directory || !viewerOverview) {
return (
<CollectionPageState
role="alert"
@@ -175,10 +167,10 @@ function AppsDirectory() {
</p>
</div>
- {overview.data.catalog_mode !== "all" && (
+ {viewerOverview.catalog_mode !== "all" && (
<SavedAppRestriction
kind="catalog"
- onRestore={overview.data.can_manage ? () => restore.mutateAsync({ catalog: true }) : undefined}
+ onRestore={viewerOverview.can_manage ? () => restore.mutateAsync({ catalog: true }) : undefined}
/>
)}
@@ -205,7 +197,7 @@ function AppsDirectory() {
</div>
{tab === "accounts" ? (
- <AccountsList overview={overview.data} rows={accountRows} matches={matchesAccount} />
+ <AccountsList overview={viewerOverview} 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} />)}
diff --git a/packages/views/apps/lib/directory.test.ts b/packages/views/apps/lib/directory.test.ts
index 847ccffba9..dd0b5b5f62 100644
--- a/packages/views/apps/lib/directory.test.ts
+++ b/packages/views/apps/lib/directory.test.ts
@@ -19,8 +19,8 @@ const catalog: AppCatalogEntry[] = [
{ 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 build = (o: AppsOverview, extra: { viewerId?: string } = {}) =>
+ buildAppDirectory({ overview: o, catalog, viewerId: extra.viewerId ?? "me" });
const slugs = (apps: { slug: string }[]) => apps.map((a) => a.slug);
@@ -125,14 +125,8 @@ describe("buildAppDirectory", () => {
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"]) },
- );
+ it("leaves out revoked accounts", () => {
+ const dir = build(overview({ personal: [connection("notion", "revoked")] }));
expect(dir.inUse).toEqual([]);
expect(dir.attention).toEqual([]);
});
diff --git a/packages/views/apps/lib/directory.ts b/packages/views/apps/lib/directory.ts
index 518100033a..7a5d4d4829 100644
--- a/packages/views/apps/lib/directory.ts
+++ b/packages/views/apps/lib/directory.ts
@@ -56,32 +56,30 @@ const SEVERITY: Record<AppAccountStatus, number> = {
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).
+ * Groups the workspace's apps for the Apps page. Agent usage comes from
+ * `overview.agent_apps` as given; callers narrow it to the viewer's
+ * (`agentAppsForViewer`).
*/
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);
+ for (const a of overview.agent_apps) slugs.add(a.toolkit_slug);
const apps = new Map(
[...slugs].map((slug) => [
slug,
- describeApp(slug, entries.get(slug), overview, agentApps, viewerId),
+ describeApp(slug, entries.get(slug), overview, viewerId),
]),
);
const described = [...apps.values()];
@@ -103,10 +101,9 @@ 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 uses = overview.agent_apps.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);
diff --git a/packages/views/common/app-status.test.ts b/packages/views/common/app-status.test.ts
new file mode 100644
index 0000000000..070b806aaf
--- /dev/null
+++ b/packages/views/common/app-status.test.ts
@@ -0,0 +1,47 @@
+// @vitest-environment node
+import { describe, expect, it } from "vitest";
+import type { Agent, AgentApp } from "@multica/core/types";
+import { agentAppsForViewer } from "./app-status";
+
+function agent(id: string, patch: Partial<Agent> = {}): Agent {
+ return {
+ id,
+ owner_id: "someone-else",
+ permission_mode: "private",
+ invocation_targets: [],
+ archived_at: null,
+ ...patch,
+ } as Agent;
+}
+
+const app = (agent_id: string, account_scope: AgentApp["account_scope"]): AgentApp => ({
+ agent_id, toolkit_slug: "gmail", account_scope, level: "write",
+});
+
+const viewer = { userId: "me", role: "member" as const };
+const ids = (apps: AgentApp[]) => apps.map((a) => `${a.agent_id}:${a.account_scope}`);
+
+describe("agentAppsForViewer", () => {
+ it("counts only agents the viewer can run against the viewer's personal accounts", () => {
+ const agents = [
+ agent("mine", { owner_id: "me" }),
+ agent("shared", { permission_mode: "public_to", invocation_targets: [{ target_type: "workspace", target_id: "ws-1" }] }),
+ agent("granted", { permission_mode: "public_to", invocation_targets: [{ target_type: "member", target_id: "me" }] }),
+ agent("others-private"),
+ agent("others-restricted", { permission_mode: "public_to", invocation_targets: [{ target_type: "member", target_id: "u2" }] }),
+ ];
+ const apps = agents.map((a) => app(a.id, "personal"));
+ expect(ids(agentAppsForViewer(apps, agents, viewer))).toEqual(["mine:personal", "shared:personal", "granted:personal"]);
+ });
+
+ it("keeps every live agent on a team account, whoever owns it", () => {
+ const agents = [agent("others-private")];
+ expect(ids(agentAppsForViewer([app("others-private", "team")], agents, viewer))).toEqual(["others-private:team"]);
+ });
+
+ it("leaves out archived agents and agents the list does not have", () => {
+ const agents = [agent("archived", { owner_id: "me", archived_at: "2026-11-01T00:00:00Z" })];
+ const apps = [app("archived", "personal"), app("archived", "team"), app("gone", "team")];
+ expect(agentAppsForViewer(apps, agents, viewer)).toEqual([]);
+ });
+});
diff --git a/packages/views/common/app-status.ts b/packages/views/common/app-status.ts
index 55b00ce330..a581b68ec6 100644
--- a/packages/views/common/app-status.ts
+++ b/packages/views/common/app-status.ts
@@ -1,4 +1,6 @@
-import type { AppAccountScope, AppConnection, AppTeamRequest, AppsOverview } from "@multica/core/types";
+import { canAssignAgentToIssue } from "@multica/core/permissions/rules";
+import type { PermissionContext } from "@multica/core/permissions";
+import type { Agent, AgentApp, AppAccountScope, AppConnection, AppTeamRequest, AppsOverview } from "@multica/core/types";
/**
* Where an account stands. Every Apps surface (the agent page, the app page,
@@ -94,3 +96,23 @@ export function viewerTeamAsk(
if ((request.asked_by ?? request.requested_by).includes(viewerId)) return "asked";
return request.requested_by.includes(viewerId) ? "waiting" : null;
}
+
+/**
+ * The agent apps that involve the viewer's accounts: those of live agents,
+ * and for personal accounts only agents the viewer may run. An agent acts
+ * through the personal account of whoever starts its run, so another
+ * member's private agent never uses the viewer's account. Mirrors the
+ * server's personal disconnect impact.
+ */
+export function agentAppsForViewer(
+ agentApps: AgentApp[],
+ agents: Agent[],
+ viewer: PermissionContext,
+): AgentApp[] {
+ const byId = new Map(agents.map((agent) => [agent.id, agent]));
+ return agentApps.filter((app) => {
+ const agent = byId.get(app.agent_id);
+ if (!agent || agent.archived_at) return false;
+ return app.account_scope === "team" || canAssignAgentToIssue(agent, viewer).allowed;
+ });
+}
diff --git a/packages/views/common/connect-app-dialog.tsx b/packages/views/common/connect-app-dialog.tsx
index bf248b8b05..de36048361 100644
--- a/packages/views/common/connect-app-dialog.tsx
+++ b/packages/views/common/connect-app-dialog.tsx
@@ -20,6 +20,7 @@ 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 { useViewerAppsOverview } from "./use-viewer-apps-overview";
import { usePaidFeatureErrorMessage } from "../billing";
import { useT } from "../i18n";
import { currentPath, useNavigation } from "../navigation";
@@ -57,9 +58,10 @@ export function ConnectAppDialog({
const qc = useQueryClient();
const paidFeatureError = usePaidFeatureErrorMessage();
const overview = useQuery({ ...appsOverviewOptions(wsId), enabled: open });
+ const viewerOverview = useViewerAppsOverview(wsId, overview.data);
const [pending, setPending] = useState(false);
- const agentNames = (overview.data?.agent_apps ?? [])
+ const agentNames = (viewerOverview?.agent_apps ?? [])
.filter((a) => a.toolkit_slug === slug && a.account_scope === scope)
.map((a) => getActorName("agent", a.agent_id));
diff --git a/packages/views/common/use-viewer-apps-overview.ts b/packages/views/common/use-viewer-apps-overview.ts
new file mode 100644
index 0000000000..83434ce54e
--- /dev/null
+++ b/packages/views/common/use-viewer-apps-overview.ts
@@ -0,0 +1,25 @@
+"use client";
+
+import { useMemo } from "react";
+import { useQuery } from "@tanstack/react-query";
+import { useCurrentMember } from "@multica/core/permissions";
+import { agentListOptions } from "@multica/core/workspace/queries";
+import type { AppsOverview } from "@multica/core/types";
+import { agentAppsForViewer } from "./app-status";
+
+/**
+ * The overview with its agent apps narrowed by `agentAppsForViewer`. Until the
+ * agents and the viewer's membership load it lists no agent apps, rather than
+ * naming agents that may not be the viewer's.
+ */
+export function useViewerAppsOverview(wsId: string, overview: AppsOverview | undefined): AppsOverview | undefined {
+ const agents = useQuery({ ...agentListOptions(wsId), enabled: !!wsId });
+ const { userId, role, isLoading } = useCurrentMember(wsId);
+ return useMemo(() => {
+ if (!overview) return undefined;
+ const agentApps = agents.data && !isLoading
+ ? agentAppsForViewer(overview.agent_apps, agents.data, { userId, role })
+ : [];
+ return { ...overview, agent_apps: agentApps };
+ }, [overview, agents.data, isLoading, userId, role]);
+}
diff --git a/packages/views/layout/panels/team-panel.tsx b/packages/views/layout/panels/team-panel.tsx
index 7eda034d2e..be7455fa60 100644
--- a/packages/views/layout/panels/team-panel.tsx
+++ b/packages/views/layout/panels/team-panel.tsx
@@ -29,6 +29,7 @@ import { availabilityConfig } from "../../agents/presence";
import { useT } from "../../i18n";
import { buildAppDirectory } from "../../apps/lib/directory";
import { useComposioAvailable } from "../../common/use-composio-available";
+import { useViewerAppsOverview } from "../../common/use-viewer-apps-overview";
import { buildRuntimeMachines, runtimeMachineCounts } from "../../runtimes/components/runtime-machines";
import {
PanelBody,
@@ -246,17 +247,17 @@ function WorkingAgentRow({
}
/** The Apps link, counting the apps that need someone to act. */
-function AppsPanelLink({ wsId, agents }: { wsId: string; agents: Agent[] }) {
+function AppsPanelLink({ wsId }: { wsId: string }) {
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 { data } = useQuery({ ...appsOverviewOptions(wsId), enabled: !!wsId });
+ const overview = useViewerAppsOverview(wsId, data);
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 buildAppDirectory({ overview, catalog: [], viewerId }).attention.length;
+ }, [overview, viewerId]);
return (
<PanelLink
href={p.apps()}
@@ -453,7 +454,7 @@ export function TeamPanel() {
active={isPathWithin(pathname, p.skills())}
trailing={<PanelCount value={skills.length} />}
/>
- {appsAvailable && <AppsPanelLink wsId={wsId} agents={agents} />}
+ {appsAvailable && <AppsPanelLink wsId={wsId} />}
<PanelLink
href={p.runtimes()}
icon={<Monitor />}
diff --git a/server/internal/handler/connected_apps.go b/server/internal/handler/connected_apps.go
index 7a28efbd3f..6a957cfcbf 100644
--- a/server/internal/handler/connected_apps.go
+++ b/server/internal/handler/connected_apps.go
@@ -12,6 +12,7 @@ import (
"time"
"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/entitlement"
@@ -553,7 +554,8 @@ func (h *Handler) DisconnectTeamApp(w http.ResponseWriter, r *http.Request) {
}
// GetTeamAppImpact (GET /api/apps/team/impact?toolkit_slug=) is what
-// disconnecting a team account would stop. Admins only.
+// disconnecting a team account would stop: the live agents that act as it.
+// Admins only.
func (h *Handler) GetTeamAppImpact(w http.ResponseWriter, r *http.Request) {
if !h.appsReady(w, r) {
return
@@ -579,12 +581,19 @@ func (h *Handler) GetTeamAppImpact(w http.ResponseWriter, r *http.Request) {
if app.ToolkitSlug != slug || app.AccountScope != connectedapps.ScopeTeam {
continue
}
- agentIDs = append(agentIDs, app.AgentID)
- name := ""
- if agent, err := h.Queries.GetAgent(ctx, app.AgentID); err == nil {
- name = agent.Name
+ agent, err := h.Queries.GetAgent(ctx, app.AgentID)
+ if errors.Is(err, pgx.ErrNoRows) {
+ continue
+ }
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to load agents")
+ return
+ }
+ if agent.ArchivedAt.Valid {
+ continue
}
- agents = append(agents, map[string]string{"id": uuidToString(app.AgentID), "name": name})
+ agentIDs = append(agentIDs, app.AgentID)
+ agents = append(agents, map[string]string{"id": uuidToString(app.AgentID), "name": agent.Name})
}
var tasks, autopilots int64
if len(agentIDs) > 0 {
diff --git a/server/internal/handler/connected_apps_test.go b/server/internal/handler/connected_apps_test.go
index b4925d4b63..7763b1032e 100644
--- a/server/internal/handler/connected_apps_test.go
+++ b/server/internal/handler/connected_apps_test.go
@@ -15,6 +15,7 @@ import (
"testing"
"time"
+ "github.com/google/uuid"
"github.com/jackc/pgx/v5/pgtype"
"github.com/multica-ai/multica/server/internal/connectedapps"
composio "github.com/multica-ai/multica/server/internal/integrations/composio"
@@ -507,6 +508,31 @@ func TestConnectedApps_AdminOnlyTeamSurfaces(t *testing.T) {
}
}
+func TestConnectedApps_TeamImpactListsLiveAgents(t *testing.T) {
+ f := newAppsFixture(t)
+ if w := f.putAgentApps(t, testUserID, []map[string]string{{"toolkit_slug": "gmail", "account_scope": "team"}}); w.Code != http.StatusOK {
+ t.Fatalf("attach: %d %s", w.Code, w.Body.String())
+ }
+ archived := dbfx.Agent(t, fmt.Sprintf("apps-archived-%d", testSeq.Add(1)), handlerTestRuntimeID(t), testutil.Cols{
+ "owner_id": testUserID, "instructions": "", "archived_at": testutil.Raw("now()"),
+ "custom_env": testutil.Raw("'{}'::jsonb"), "custom_args": testutil.Raw("'[]'::jsonb"),
+ })
+ t.Cleanup(func() { testPool.Exec(context.Background(), `DELETE FROM agent WHERE id = $1`, archived) })
+ deleted := uuid.NewString()
+ for _, agentID := range []string{archived, deleted} {
+ dbfx.Exec(t, `INSERT INTO agent_app (workspace_id, agent_id, toolkit_slug, account_scope, level) VALUES ($1, $2, 'gmail', 'team', 'write')`, testWorkspaceID, agentID)
+ }
+
+ var resp struct {
+ Agents []map[string]string `json:"agents"`
+ }
+ req := appsReqAs(t, testUserID, http.MethodGet, "/api/apps/team/impact?toolkit_slug=gmail", nil)
+ testutil.Call(t, f.h.GetTeamAppImpact, req).Want(http.StatusOK).JSON(&resp)
+ if len(resp.Agents) != 1 || resp.Agents[0]["id"] != f.agentID || resp.Agents[0]["name"] == "" {
+ t.Fatalf("impact agents = %+v, want only the live agent %s", resp.Agents, f.agentID)
+ }
+}
+
func (f *appsFixture) inboxCount(t *testing.T, recipient, notifType string) int {
t.Helper()
var n int