Skip to content

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

Go

feat(channels): MUL-9008 move messaging connections to agent pages (#10397)

Bohan Jiangf49bccb57da7
diff --git a/packages/core/api/schemas.test.ts b/packages/core/api/schemas.test.ts
index a077e04d03..5b0e658c51 100644
--- a/packages/core/api/schemas.test.ts
+++ b/packages/core/api/schemas.test.ts
@@ -2072,6 +2072,11 @@ describe("SidebarProjectPrefsDocSchema", () => {
// dialog, the "ask your operator" state, the revoked-vs-active badge), so a
// malformed response must degrade to the safe state rather than a broken one.
describe("WeCom installation schemas", () => {
+ it("accepts the bot display name while remaining compatible with older servers", () => {
+ expect(WecomInstallationSchema.parse({ id: "i1", bot_name: "Support Bot" }).bot_name).toBe("Support Bot");
+ expect(WecomInstallationSchema.parse({ id: "i1" }).bot_name).toBeUndefined();
+ expect(WecomInstallationSchema.safeParse({ id: "i1", bot_name: 42 }).success).toBe(false);
+ });
it("parses a well-formed installation", () => {
const parsed = WecomInstallationSchema.parse({
id: "i1",
diff --git a/packages/core/api/schemas.ts b/packages/core/api/schemas.ts
index 640e71a74a..a6dd0923b5 100644
--- a/packages/core/api/schemas.ts
+++ b/packages/core/api/schemas.ts
@@ -3783,6 +3783,7 @@ export const WecomInstallationSchema = z.object({
workspace_id: z.string().default(""),
agent_id: z.string().default(""),
bot_id: z.string().default(""),
+ bot_name: z.string().optional(),
installer_user_id: z.string().default(""),
status: z.string().default("revoked"),
}).loose();
diff --git a/packages/core/types/wecom.ts b/packages/core/types/wecom.ts
index 56f3dea171..6c86e1844b 100644
--- a/packages/core/types/wecom.ts
+++ b/packages/core/types/wecom.ts
@@ -11,6 +11,8 @@ export interface WecomInstallation {
agent_id: string;
/** The smart-bot identifier assigned by the WeCom admin console. */
bot_id: string;
+ /** Chat display name; absent on older backends. */
+ bot_name?: string;
installer_user_id: string;
status: "active" | "revoked" | string;
}
diff --git a/packages/views/agents/components/agent-advanced-settings.test.tsx b/packages/views/agents/components/agent-advanced-settings.test.tsx
index 1b9a13aa6a..60d6f155d2 100644
--- a/packages/views/agents/components/agent-advanced-settings.test.tsx
+++ b/packages/views/agents/components/agent-advanced-settings.test.tsx
@@ -41,9 +41,6 @@ vi.mock("./tabs/mcp-config-tab", () => ({
vi.mock("./tabs/agent-mcp-tab", () => ({
AgentMcpTab: () => <div>agent-mcp-tab</div>,
}));
-vi.mock("./tabs/integrations-tab", () => ({
- IntegrationsTab: () => <div>integrations-tab</div>,
-}));
vi.mock("./tabs/qoder-agent-tab", () => ({
QoderAgentTab: () => <div>qoder-agent-tab</div>,
}));
@@ -224,12 +221,12 @@ describe("AgentAdvancedSettings Integrations section visibility", () => {
// Slack-only deployment was hiding the section (and its bind entry).
["Slack", slackListingRef],
["Telegram", telegramListingRef],
- ])("shows Integrations once %s is configured", async (_name, ref) => {
+ ])("keeps channels out of settings when %s is configured", async (_name, ref) => {
ref.current = { installations: [], configured: true };
renderDialog([makeRuntime("claude")]);
expect(
- await screen.findByRole("tab", { name: /^Integrations$/i }),
- ).toBeInTheDocument();
+ screen.queryByRole("tab", { name: /^Integrations$/i }),
+ ).not.toBeInTheDocument();
});
it("hides Integrations when no channel integration is configured", () => {
@@ -290,20 +287,16 @@ describe("AgentAdvancedSettings section lists", () => {
expect(sectionNames()).toEqual(["General", "Access", "Qoder Cloud Agents"]);
});
- it("keeps Integrations on Qoder, since the bridge runs chat", async () => {
- // An IM message becomes a chat task, which the Qoder bridge runs. Only
- // Integrations comes back: Skills, MCP and connected apps are still
- // rejected by the bridge.
+ it("keeps channel management out of Qoder advanced settings", async () => {
larkListingRef.current = { installations: [], configured: true };
renderDialog([makeRuntime("qoder_cloud")]);
expect(
- await screen.findByRole("tab", { name: /^Integrations$/i }),
- ).toBeInTheDocument();
+ screen.queryByRole("tab", { name: /^Integrations$/i }),
+ ).not.toBeInTheDocument();
expect(sectionNames()).toEqual([
"General",
"Access",
"Qoder Cloud Agents",
- "Integrations",
]);
});
diff --git a/packages/views/agents/components/agent-advanced-settings.tsx b/packages/views/agents/components/agent-advanced-settings.tsx
index cfb20a0215..9f1952242e 100644
--- a/packages/views/agents/components/agent-advanced-settings.tsx
+++ b/packages/views/agents/components/agent-advanced-settings.tsx
@@ -1,17 +1,10 @@
"use client";
import { useMemo, useState } from "react";
-import { useQuery } from "@tanstack/react-query";
import type { Agent, AgentRuntime, MemberWithUser } from "@multica/core/types";
import { providerSupportsMcpConfig } 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 { larkInstallationsOptions } from "@multica/core/lark";
-import { slackInstallationsOptions } from "@multica/core/slack";
-import { dingtalkInstallationsOptions } from "@multica/core/dingtalk";
-import { wecomInstallationsOptions } from "@multica/core/wecom";
-import { telegramInstallationsOptions } from "@multica/core/telegram";
import {
AlertDialog,
AlertDialogAction,
@@ -35,7 +28,6 @@ import { EnvTab } from "./tabs/env-tab";
import { CustomArgsTab } from "./tabs/custom-args-tab";
import { McpConfigTab } from "./tabs/mcp-config-tab";
import { AgentAppsTab } from "./tabs/agent-apps-tab";
-import { IntegrationsTab } from "./tabs/integrations-tab";
import { QoderAgentTab } from "./tabs/qoder-agent-tab";
import { RuntimeConfigTab } from "./tabs/runtime-config-tab";
import { AgentDetailInspector } from "./agent-detail-inspector";
@@ -50,8 +42,7 @@ export type AdvancedSection =
| "runtime_config"
| "skills"
| "mcp_config"
- | "composio_mcp"
- | "integrations";
+ | "composio_mcp";
type SectionLabelKey =
| "general"
@@ -62,8 +53,7 @@ type SectionLabelKey =
| "qoder_agent"
| "skills"
| "mcp_config"
- | "composio_mcp"
- | "integrations";
+ | "composio_mcp";
type SectionDef = { id: AdvancedSection; labelKey: SectionLabelKey };
@@ -79,7 +69,6 @@ const CAPABILITY_SECTIONS: SectionDef[] = [
{ id: "skills", labelKey: "skills" },
{ id: "mcp_config", labelKey: "mcp_config" },
{ id: "composio_mcp", labelKey: "composio_mcp" },
- { id: "integrations", labelKey: "integrations" },
];
const ADVANCED_SECTIONS = new Set<string>(
@@ -120,7 +109,6 @@ export function AgentAdvancedSettings({
onSectionChange,
}: AgentAdvancedSettingsProps) {
const { t } = useT("agents");
- const wsId = useWorkspaceId();
const composioMCPAppsEnabled = useFeatureEnabled(
COMPOSIO_MCP_APPS_FLAG,
false,
@@ -131,37 +119,6 @@ export function AgentAdvancedSettings({
undefined,
);
- const { data: larkListing } = useQuery({
- ...larkInstallationsOptions(wsId),
- enabled: !!wsId,
- });
- const { data: slackListing } = useQuery({
- ...slackInstallationsOptions(wsId),
- enabled: !!wsId,
- });
- const { data: dingtalkListing } = useQuery({
- ...dingtalkInstallationsOptions(wsId),
- });
- const { data: wecomListing } = useQuery({
- ...wecomInstallationsOptions(wsId),
- enabled: !!wsId,
- });
- const { data: telegramListing } = useQuery({
- ...telegramInstallationsOptions(wsId),
- enabled: !!wsId,
- });
-
- const integrationsConfigured =
- larkListing?.configured === true ||
- slackListing?.configured === true ||
- dingtalkListing?.configured === true ||
- wecomListing?.configured === true ||
- telegramListing?.configured === true;
-
- // The Qoder bridge fails every task carrying skills, MCP, connected apps,
- // env, args or a model override. Those editors are not offered; the agent
- // in Qoder Cloud Agents owns that configuration. It does run chat, so IM
- // channels (Integrations) stay available.
const qoderRuntime = runtime?.provider === "qoder_cloud";
const settingsSections = useMemo(
@@ -185,23 +142,17 @@ export function AgentAdvancedSettings({
);
const capabilitySections = useMemo(() => {
- if (qoderRuntime) {
- return CAPABILITY_SECTIONS.filter(
- (item) => item.id === "integrations" && integrationsConfigured,
- );
- }
+ if (qoderRuntime) return [];
const showMcp = runtime ? providerSupportsMcpConfig(runtime.provider) : true;
const showComposioMcp = composioMCPAppsEnabled && canEdit;
return CAPABILITY_SECTIONS.filter((item) => {
if (item.id === "mcp_config") return showMcp;
if (item.id === "composio_mcp") return showComposioMcp;
- if (item.id === "integrations") return integrationsConfigured;
return true;
});
}, [
canEdit,
composioMCPAppsEnabled,
- integrationsConfigured,
qoderRuntime,
runtime,
]);
@@ -371,9 +322,6 @@ export function AgentAdvancedSettings({
/>
)}
{active.id === "composio_mcp" && <AgentAppsTab agent={agent} />}
- {active.id === "integrations" && (
- <IntegrationsTab agent={agent} />
- )}
</div>
</div>
</section>
diff --git a/packages/views/agents/components/agent-channels-section.tsx b/packages/views/agents/components/agent-channels-section.tsx
new file mode 100644
index 0000000000..aad0d3dd72
--- /dev/null
+++ b/packages/views/agents/components/agent-channels-section.tsx
@@ -0,0 +1,389 @@
+"use client";
+
+import { useEffect, useRef, useState } from "react";
+import { useQuery } from "@tanstack/react-query";
+import type { Agent } from "@multica/core/types";
+import { dingtalkAgentGroupsOptions } from "@multica/core/dingtalk";
+import { Button } from "@multica/ui/components/ui/button";
+import { IconButton } from "@multica/ui/components/common/icon-button";
+import { ExternalLink, MoreHorizontal, Plus } from "@multica/ui/icons";
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuSeparator,
+ DropdownMenuTrigger,
+} from "@multica/ui/components/ui/dropdown-menu";
+
+import { docsLocalePrefix } from "../../common/docs-locale";
+import { ObjectSection, ObjectSectionAction } from "../../layout/object-page";
+import { useT, useTimeAgo } from "../../i18n";
+import { openExternal } from "../../platform";
+import { useNavigation } from "../../navigation";
+import { IntegrationChannelIcon } from "../../settings/components/integration-channel-icon";
+import { ChannelDisconnectDialog } from "../../settings/components/channel-disconnect-dialog";
+import { ChannelConnectDialog } from "../../settings/components/channel-connect-dialog";
+import {
+ DingTalkBotGroups,
+ getDingTalkBotIdentity,
+} from "../../settings/components/dingtalk-bot-groups";
+import { CHANNEL_INTEGRATIONS } from "../../settings/components/settings-navigation";
+import {
+ channelChatLink,
+ useMessagingChannels,
+ type ChannelConnection,
+} from "../../settings/components/use-messaging-channels";
+
+const DINGTALK_CHAT_MANAGE_PERMISSION = "qyapi_chat_manage";
+
+export function AgentChannelLinks({ agent }: { agent: Agent }) {
+ const { connections } = useMessagingChannels();
+ const links = connections.filter(
+ (entry) => entry.installation.agent_id === agent.id,
+ );
+ if (links.length === 0) return null;
+ return (
+ <div className="flex flex-wrap gap-2">
+ {links.map((entry) => (
+ <AgentChannelContact key={entry.installation.id} connection={entry} />
+ ))}
+ </div>
+ );
+}
+
+function AgentChannelContact({
+ connection,
+}: {
+ connection: ChannelConnection;
+}) {
+ const { t } = useT("settings");
+ const { channel, installation } = connection;
+ const { data } = useQuery({
+ ...dingtalkAgentGroupsOptions(
+ installation.workspace_id,
+ installation.agent_id,
+ ),
+ enabled: channel === "dingtalk",
+ });
+ const name =
+ connection.channel === "wecom"
+ ? connection.installation.bot_name
+ : (data?.bot_identities?.[installation.id]?.bot_name ??
+ getDingTalkBotIdentity(data?.groups ?? [], installation.id)?.bot_name);
+ const href = channelChatLink(connection);
+ return href ? (
+ <Button variant="outline" size="sm" onClick={() => openExternal(href)}>
+ <IntegrationChannelIcon channel={channel} />
+ {t(($) => $.channels.find_me, {
+ platform: t(($) => $[channel].section_title),
+ })}
+ </Button>
+ ) : name ? (
+ <span className="inline-flex items-center gap-1.5 text-caption text-muted-foreground">
+ <IntegrationChannelIcon channel={channel} />
+ {name}
+ </span>
+ ) : null;
+}
+
+export function AgentChannelsSection({ agent }: { agent: Agent }) {
+ const { t } = useT("settings");
+ const { queries, connections, canManage, available, isAdmin } =
+ useMessagingChannels();
+ const [open, setOpen] = useState(false);
+ const sectionRef = useRef<HTMLDivElement>(null);
+ const { searchParams } = useNavigation();
+ const view = searchParams.get("view") ?? searchParams.get("tab");
+ const installed = connections.filter(
+ (entry) => entry.installation.agent_id === agent.id,
+ );
+ const canAdd =
+ !agent.archived_at &&
+ CHANNEL_INTEGRATIONS.some(
+ (id) =>
+ canManage(id, agent) &&
+ available(id) &&
+ !installed.some((entry) => entry.channel === id),
+ );
+ const unavailable = isAdmin
+ ? CHANNEL_INTEGRATIONS.filter(
+ (id) => queries[id].isSuccess && !queries[id].data.configured,
+ )
+ : [];
+ const failed = CHANNEL_INTEGRATIONS.filter((id) => queries[id].isError);
+ const visible =
+ installed.length > 0 ||
+ canAdd ||
+ unavailable.length > 0 ||
+ failed.length > 0;
+ useEffect(() => {
+ if (visible && (view === "channels" || view === "integrations"))
+ sectionRef.current?.scrollIntoView({ block: "start" });
+ }, [visible, view]);
+ if (!visible) return null;
+
+ return (
+ <div
+ ref={sectionRef}
+ id="messaging-channels"
+ data-settings-anchor="channels"
+ >
+ <ObjectSection
+ title={t(($) => $.page.tabs.channels)}
+ count={installed.length}
+ action={
+ canAdd ? (
+ <ObjectSectionAction icon={Plus} onClick={() => setOpen(true)}>
+ {t(($) => $.channels.add)}
+ </ObjectSectionAction>
+ ) : undefined
+ }
+ >
+ {installed.length ? (
+ <div className="divide-y rounded-lg border">
+ {installed.map((connection) => (
+ <AgentChannelRow
+ key={connection.installation.id}
+ connection={connection}
+ canManage={canManage(connection.channel, agent)}
+ canForget={isAdmin}
+ />
+ ))}
+ </div>
+ ) : canAdd ? (
+ <Button variant="outline" size="sm" onClick={() => setOpen(true)}>
+ <Plus />
+ {t(($) => $.channels.add)}
+ </Button>
+ ) : null}
+ {failed.map((id) => (
+ <div
+ key={id}
+ role="alert"
+ className="mt-2 flex items-center justify-between gap-3 text-caption text-muted-foreground"
+ >
+ <span>
+ {t(($) => $[id].section_title)} ·{" "}
+ {t(($) => $.integrations.status_unknown)}
+ </span>
+ <Button
+ size="xs"
+ variant="outline"
+ onClick={() => void queries[id].refetch()}
+ >
+ {t(($) => $.lark.install_retry)}
+ </Button>
+ </div>
+ ))}
+ {unavailable.length ? (
+ <p className="mt-2 text-caption text-muted-foreground">
+ {t(($) => $.channels.server_unavailable, {
+ platforms: unavailable
+ .map((id) => t(($) => $[id].section_title))
+ .join(", "),
+ })}
+ </p>
+ ) : null}
+ </ObjectSection>
+ <ChannelConnectDialog
+ agents={[agent]}
+ initialAgent={agent}
+ open={open}
+ onOpenChange={setOpen}
+ />
+ </div>
+ );
+}
+
+function AgentChannelRow({
+ connection,
+ canManage,
+ canForget,
+}: {
+ connection: ChannelConnection;
+ canManage: boolean;
+ canForget: boolean;
+}) {
+ const { t, i18n } = useT("settings");
+ const timeAgo = useTimeAgo();
+ const { channel, installation } = connection;
+ const [confirm, setConfirm] = useState(false);
+ const groups = useQuery({
+ ...dingtalkAgentGroupsOptions(
+ installation.workspace_id,
+ installation.agent_id,
+ ),
+ enabled: channel === "dingtalk",
+ });
+ const identity =
+ groups.data?.bot_identities?.[installation.id] ??
+ getDingTalkBotIdentity(groups.data?.groups ?? [], installation.id);
+ const identityIssue =
+ channel === "dingtalk" ? identity?.bot_identity_issue : undefined;
+ const missingChatPermission = identityIssue === "missing_qyapi_chat_manage";
+ const name =
+ channel === "dingtalk"
+ ? identity?.bot_name
+ : connection.channel === "wecom"
+ ? connection.installation.bot_name
+ : connection.channel === "telegram" &&
+ connection.installation.bot_username
+ ? `@${connection.installation.bot_username}`
+ : undefined;
+ const pending =
+ connection.channel === "lark" &&
+ !connection.installation.first_message_received_at;
+ const href = channelChatLink(connection);
+ const larkManageHref =
+ connection.channel === "lark" && connection.installation.app_id
+ ? `https://${connection.installation.region === "lark" ? "open.larksuite.com" : "open.feishu.cn"}/app/${encodeURIComponent(connection.installation.app_id)}`
+ : undefined;
+ const lastMessage = (groups.data?.groups ?? [])
+ .flatMap((group) => group.bots)
+ .filter(
+ (bot) =>
+ bot.installation_id === installation.id &&
+ Date.parse(bot.last_active_at ?? "") > 0,
+ )
+ .map((bot) => bot.last_active_at!)
+ .sort((left, right) => Date.parse(left) - Date.parse(right))
+ .at(-1);
+
+ return (
+ <div className="px-3 py-3">
+ <div className="flex flex-wrap items-center gap-x-3 gap-y-2">
+ <IntegrationChannelIcon channel={channel} />
+ <div className="min-w-0 flex-1">
+ <div className="flex flex-wrap items-baseline gap-x-2 gap-y-1">
+ <span className="text-body font-medium">
+ {t(($) => $[channel].section_title)}
+ </span>
+ {name ? (
+ <span className="truncate text-caption text-muted-foreground">
+ {name}
+ </span>
+ ) : null}
+ </div>
+ <span
+ className={
+ identityIssue
+ ? "text-caption text-warning"
+ : pending
+ ? "text-caption text-muted-foreground"
+ : "text-caption text-success"
+ }
+ >
+ {identityIssue
+ ? t(($) => $.dingtalk.bot_identity_unavailable)
+ : pending
+ ? t(($) => $.channels.waiting_message)
+ : t(($) => $.channels.normal)}
+ {lastMessage ? (
+ <span className="ml-2 text-muted-foreground">
+ {t(($) => $.channels.last_message, {
+ time: timeAgo(lastMessage),
+ })}
+ </span>
+ ) : null}
+ </span>
+ </div>
+ {href ? (
+ <Button size="xs" variant="ghost" onClick={() => openExternal(href)}>
+ <ExternalLink />
+ {t(($) => $.channels.open)}
+ </Button>
+ ) : null}
+ {canManage ? (
+ <DropdownMenu>
+ <DropdownMenuTrigger
+ render={
+ <IconButton
+ label={t(($) => $.channels.manage, {
+ platform: t(($) => $[channel].section_title),
+ })}
+ size="icon-xs"
+ >
+ <MoreHorizontal />
+ </IconButton>
+ }
+ />
+ <DropdownMenuContent align="end">
+ {connection.channel === "lark" ? (
+ <>
+ {larkManageHref ? (
+ <DropdownMenuItem
+ onClick={() => openExternal(larkManageHref)}
+ >
+ <ExternalLink />
+ {connection.installation.region === "lark"
+ ? t(($) => $.lark.agent_bot_manage_link_lark)
+ : t(($) => $.lark.agent_bot_manage_link_feishu)}
+ </DropdownMenuItem>
+ ) : null}
+ <DropdownMenuItem
+ onClick={() =>
+ openExternal(
+ `https://multica.ai/docs${docsLocalePrefix(i18n.language)}/lark-bot-integration`,
+ )
+ }
+ >
+ <ExternalLink />
+ {t(($) => $.lark.agent_bot_silent_hint_link)}
+ </DropdownMenuItem>
+ <DropdownMenuSeparator />
+ </>
+ ) : null}
+ <DropdownMenuItem
+ variant="destructive"
+ onClick={() => setConfirm(true)}
+ >
+ {t(($) => $.channels.disconnect)}
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ ) : null}
+ </div>
+ {missingChatPermission && canManage ? (
+ <p role="status" className="mt-2 text-caption text-muted-foreground">
+ {t(($) => $.dingtalk.bot_permission_tooltip_prefix)}{" "}
+ <code
+ className="rounded-xs bg-muted px-1 py-0.5 font-mono text-micro"
+ translate="no"
+ >
+ {DINGTALK_CHAT_MANAGE_PERMISSION}
+ </code>{" "}
+ {t(($) => $.dingtalk.bot_permission_tooltip_suffix)}
+ </p>
+ ) : null}
+ {channel === "dingtalk" &&
+ (groups.isPending ||
+ groups.isError ||
+ groups.data?.group_discovery_supported) ? (
+ <details className="mt-3">
+ <summary className="cursor-pointer text-caption text-muted-foreground">
+ {t(($) => $.dingtalk.groups_title)}
+ </summary>
+ <DingTalkBotGroups
+ workspaceId={installation.workspace_id}
+ agentId={installation.agent_id}
+ installationId={installation.id}
+ groups={groups.data?.groups ?? []}
+ inactiveCount={
+ groups.data?.inactive_group_counts?.[installation.id] ?? 0
+ }
+ isLoading={groups.isPending}
+ isError={groups.isError}
+ onRetry={() => void groups.refetch()}
+ showDescription={false}
+ canForget={canForget}
+ />
+ </details>
+ ) : null}
+ <ChannelDisconnectDialog
+ connection={connection}
+ open={confirm}
+ onOpenChange={setConfirm}
+ />
+ </div>
+ );
+}
diff --git a/packages/views/agents/components/agent-detail-page.test.tsx b/packages/views/agents/components/agent-detail-page.test.tsx
index 26148fc368..9b33d4231d 100644
--- a/packages/views/agents/components/agent-detail-page.test.tsx
+++ b/packages/views/agents/components/agent-detail-page.test.tsx
@@ -62,6 +62,10 @@ vi.mock("./tabs/activity-tab", () => ({
vi.mock("./agent-instructions-section", () => ({
AgentInstructionsSection: () => <div>instructions-section</div>,
}));
+vi.mock("./agent-channels-section", () => ({
+ AgentChannelLinks: () => <div>channel-links</div>,
+ AgentChannelsSection: () => <div id="messaging-channels">channels-section</div>,
+}));
vi.mock("./agent-skills-section", () => ({
AgentSkillsSection: ({ onManage }: { onManage: () => void }) => (
<button type="button" onClick={onManage}>
@@ -81,7 +85,6 @@ vi.mock("./agent-advanced-settings", () => ({
"skills",
"mcp_config",
"composio_mcp",
- "integrations",
].includes(value),
AgentAdvancedSettings: ({
section,
diff --git a/packages/views/agents/components/agent-detail-page.tsx b/packages/views/agents/components/agent-detail-page.tsx
index a8ca85ce3f..2a4a70300a 100644
--- a/packages/views/agents/components/agent-detail-page.tsx
+++ b/packages/views/agents/components/agent-detail-page.tsx
@@ -89,6 +89,7 @@ import {
import { AgentInstructionsSection } from "./agent-instructions-section";
import { AgentPropertiesPanel } from "./agent-properties-panel";
import { describeCancelImpact } from "./agent-row-actions";
+import { AgentChannelLinks, AgentChannelsSection } from "./agent-channels-section";
import { AgentSkillsSection } from "./agent-skills-section";
import { AgentWorkDialog } from "./agent-work-dialog";
import { AgentWorkSections } from "./tabs/activity-tab";
@@ -173,7 +174,15 @@ export function AgentDetailPage({ agentId }: AgentDetailPageProps) {
const [confirmArchive, setConfirmArchive] = useState(false);
const [confirmCancelRuns, setConfirmCancelRuns] = useState(false);
- const urlView = viewFromParams(navigation.searchParams);
+ const requestedView = viewFromParams(navigation.searchParams);
+ const urlView = requestedView === "integrations" ? "channels" : requestedView;
+ useEffect(() => {
+ if (requestedView !== "integrations" || !agent) return;
+ const params = new URLSearchParams(navigation.searchParams);
+ params.delete("tab");
+ params.set("view", "channels");
+ navigation.replace(`${navigation.pathname}?${params}`);
+ }, [requestedView, navigation, agent]);
const [advancedSection, setAdvancedSection] = useState<AdvancedSection | null>(
() => (isAdvancedSection(urlView) ? urlView : null),
);
@@ -673,6 +682,7 @@ export function AgentDetailPage({ agentId }: AgentDetailPageProps) {
) : null
}
/>
+ <AgentChannelLinks agent={agent} />
{notices.length > 0 && <div className="space-y-2">{notices}</div>}
</div>
@@ -683,6 +693,8 @@ export function AgentDetailPage({ agentId }: AgentDetailPageProps) {
onViewAll={() => openWork(true)}
/>
+ <AgentChannelsSection agent={agent} />
+
<AgentInstructionsSection
agent={agent}
canEdit={canEdit.allowed}
diff --git a/packages/views/agents/components/tabs/integrations-tab.test.tsx b/packages/views/agents/components/tabs/integrations-tab.test.tsx
deleted file mode 100644
index c296666967..0000000000
--- a/packages/views/agents/components/tabs/integrations-tab.test.tsx
+++ /dev/null
@@ -1,590 +0,0 @@
-// @vitest-environment jsdom
-
-import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
-import type { ReactNode } from "react";
-import { cleanup, render, screen } from "@testing-library/react";
-import userEvent from "@testing-library/user-event";
-import type { Agent } from "@multica/core/types";
-import { I18nProvider } from "@multica/core/i18n/react";
-import enCommon from "../../../locales/en/common.json";
-import enAgents from "../../../locales/en/agents.json";
-import enSettings from "../../../locales/en/settings.json";
-
-// IntegrationsTab's job is to pick which copy sits beside the bind entry
-// based on (configured / install_supported / role). The bind entry itself
-// is the shared LarkAgentBindButton, exhaustively covered in
-// lark-tab.test.tsx — here we stub it to a marker so the tests assert the
-// branch selection, not the install flow.
-type MemberRole = "owner" | "admin" | "member";
-
-const membersRef = vi.hoisted(() => ({
- current: [{ user_id: "user-1", role: "owner" as MemberRole }],
-}));
-const installationsRef = vi.hoisted(() => ({
- current: {
- installations: [] as unknown[],
- configured: true,
- install_supported: true,
- },
-}));
-const groupsRef = vi.hoisted(() => ({
- current: {
- data: { groups: [] as unknown[], group_discovery_supported: true },
- isLoading: false,
- isError: false,
- refetch: vi.fn(),
- },
-}));
-
-vi.mock("@tanstack/react-query", () => ({
- useQuery: (opts: { queryKey: unknown[]; enabled?: boolean }) => {
- if (opts.enabled === false) return { data: undefined };
- const key = JSON.stringify(opts.queryKey);
- if (key.includes("members")) return { data: membersRef.current };
- if (key.includes("groups")) return groupsRef.current;
- if (key.includes("installations")) return { data: installationsRef.current };
- return { data: undefined };
- },
- useQueryClient: () => ({ invalidateQueries: vi.fn() }),
- useInfiniteQuery: () => ({
- data: undefined,
- isLoading: false,
- isError: false,
- refetch: vi.fn(),
- hasNextPage: false,
- isFetchingNextPage: false,
- fetchNextPage: vi.fn(),
- }),
- queryOptions: <T,>(opts: T) => opts,
-}));
-
-vi.mock("@multica/core/hooks", () => ({
- useWorkspaceId: () => "ws-1",
-}));
-
-vi.mock("@multica/core/workspace/queries", () => ({
- memberListOptions: () => ({ queryKey: ["members"], queryFn: vi.fn() }),
-}));
-
-vi.mock("@multica/core/lark", () => ({
- larkInstallationsOptions: () => ({
- queryKey: ["lark", "installations"],
- queryFn: vi.fn(),
- }),
-}));
-
-vi.mock("@multica/core/slack", () => ({
- slackInstallationsOptions: () => ({
- queryKey: ["slack", "installations"],
- queryFn: vi.fn(),
- }),
-}));
-
-vi.mock("@multica/core/wecom", () => ({
- wecomInstallationsOptions: () => ({
- queryKey: ["wecom", "installations"],
- queryFn: vi.fn(),
- }),
-}));
-
-vi.mock("@multica/core/telegram", () => ({
- telegramInstallationsOptions: () => ({
- queryKey: ["telegram", "installations"],
- queryFn: vi.fn(),
- }),
-}));
-
-vi.mock("@multica/core/dingtalk", () => ({
- dingtalkInstallationsOptions: () => ({
- queryKey: ["dingtalk", "installations"],
- queryFn: vi.fn(),
- }),
- dingtalkAgentGroupsOptions: (_wsId: string, agentId: string) => ({
- queryKey: ["dingtalk", "groups", "agent", agentId],
- queryFn: vi.fn(),
- }),
- dingtalkKeys: {
- groups: (wsId: string) => ["dingtalk", "groups", wsId],
- inactiveGroups: (wsId: string, installationId: string) =>
- ["dingtalk", "groups", wsId, "inactive", installationId],
- agentInactiveGroups: (wsId: string, agentId: string, installationId: string) =>
- ["dingtalk", "groups", wsId, "agent", agentId, "inactive", installationId],
- },
-}));
-
-vi.mock("@multica/core/workspace/hooks", () => ({
- useActorName: () => ({ getAgentName: (id: string) => `Agent ${id}` }),
-}));
-
-vi.mock("../../../common/actor-avatar", () => ({
- ActorAvatar: ({ actorId }: { actorId: string }) => (
- <span data-testid="actor-avatar" data-actor-id={actorId} />
- ),
-}));
-
-vi.mock("@multica/core/auth", () => {
- const useAuthStore = Object.assign(
- (sel?: (s: { user: { id: string } }) => unknown) =>
- sel ? sel({ user: { id: "user-1" } }) : { user: { id: "user-1" } },
- { getState: () => ({ user: { id: "user-1" } }) },
- );
- return { useAuthStore };
-});
-
-vi.mock("../../../settings/components/lark-tab", () => ({
- LarkAgentBindButton: ({
- agentId,
- agentOwnerId,
- }: {
- agentId: string;
- agentOwnerId?: string | null;
- }) => (
- <div
- data-testid="lark-bind-button"
- data-agent-id={agentId}
- data-agent-owner-id={agentOwnerId ?? ""}
- />
- ),
-}));
-
-// SlackAgentBindButton is the shared bind entry covered in slack-tab.test.tsx;
-// here it is a marker so the tests assert branch selection, not the OAuth flow.
-vi.mock("../../../settings/components/slack-tab", () => ({
- SlackAgentBindButton: ({ agentId }: { agentId: string }) => (
- <div data-testid="slack-bind-button" data-agent-id={agentId} />
- ),
-}));
-
-// Same stubbing rationale for WeCom smart-bot: the shared bind entry has
-// its own coverage in wecom-tab.test.tsx (when added); here it's a marker.
-vi.mock("../../../settings/components/wecom-tab", () => ({
- WecomAgentBindButton: ({ agentId }: { agentId: string }) => (
- <div data-testid="wecom-bind-button" data-agent-id={agentId} />
- ),
-}));
-
-vi.mock("../../../settings/components/telegram-tab", () => ({
- TelegramAgentBindButton: ({ agentId }: { agentId: string }) => (
- <div data-testid="telegram-bind-button" data-agent-id={agentId} />
- ),
-}));
-
-import { IntegrationsTab } from "./integrations-tab";
-
-const TEST_RESOURCES = {
- en: { common: enCommon, agents: enAgents, settings: enSettings },
-};
-
-afterEach(() => {
- cleanup();
- vi.useRealTimers();
-});
-
-const agent: Agent = {
- id: "agent-1",
- workspace_id: "ws-1",
- runtime_id: "runtime-1",
- name: "Agent",
- description: "",
- instructions: "",
- avatar_url: null,
- runtime_mode: "local",
- runtime_config: {},
- custom_args: [],
- visibility: "workspace",
- permission_mode: "public_to",
- invocation_targets: [{ target_type: "workspace", target_id: null }],
- status: "idle",
- max_concurrent_tasks: 1,
- model: "",
- owner_id: "user-1",
- skills: [],
- created_at: "2026-04-16T00:00:00Z",
- updated_at: "2026-04-16T00:00:00Z",
- archived_at: null,
- archived_by: null,
-};
-
-function renderTab(children: ReactNode) {
- return render(
- <I18nProvider locale="en" resources={TEST_RESOURCES}>
- {children}
- </I18nProvider>,
- );
-}
-
-function resetFixtures() {
- vi.clearAllMocks();
- membersRef.current = [{ user_id: "user-1", role: "owner" }];
- installationsRef.current = {
- installations: [],
- configured: true,
- install_supported: true,
- };
- groupsRef.current = {
- data: { groups: [], group_discovery_supported: true },
- isLoading: false,
- isError: false,
- refetch: vi.fn(),
- };
-}
-
-describe("IntegrationsTab", () => {
- beforeEach(resetFixtures);
-
- it.each([
- { role: "owner", ownsAgent: false, permissionMode: "private", canManage: true },
- { role: "owner", ownsAgent: true, permissionMode: "private", canManage: true },
- { role: "admin", ownsAgent: false, permissionMode: "private", canManage: true },
- { role: "admin", ownsAgent: true, permissionMode: "private", canManage: true },
- { role: "member", ownsAgent: false, permissionMode: "private", canManage: false },
- { role: "member", ownsAgent: true, permissionMode: "private", canManage: true },
- { role: "owner", ownsAgent: false, permissionMode: "public_to", canManage: true },
- { role: "owner", ownsAgent: true, permissionMode: "public_to", canManage: true },
- { role: "admin", ownsAgent: false, permissionMode: "public_to", canManage: true },
- { role: "admin", ownsAgent: true, permissionMode: "public_to", canManage: true },
- { role: "member", ownsAgent: false, permissionMode: "public_to", canManage: false },
- { role: "member", ownsAgent: true, permissionMode: "public_to", canManage: true },
- ] as const)(
- "keeps DingTalk management independent of Agent access mode: role=$role ownsAgent=$ownsAgent permissionMode=$permissionMode",
- ({ role, ownsAgent, permissionMode, canManage }) => {
- membersRef.current = [{ user_id: "user-1", role }];
- renderTab(
- <IntegrationsTab
- agent={{
- ...agent,
- owner_id: ownsAgent ? "user-1" : "user-2",
- permission_mode: permissionMode,
- visibility: permissionMode === "private" ? "private" : "workspace",
- }}
- />,
- );
- expect(screen.queryByTestId("dingtalk-agent-connect") !== null).toBe(canManage);
- },
- );
-
- it("does not expose Agent management when the owner is no longer a workspace member", () => {
- membersRef.current = [];
- renderTab(<IntegrationsTab agent={agent} />);
- expect(screen.queryByTestId("dingtalk-agent-connect")).toBeNull();
- expect(screen.queryByTestId("lark-bind-button")).toBeNull();
- });
-
- it("renders the shared bind entries for an owner when configured and supported", () => {
- renderTab(<IntegrationsTab agent={agent} />);
- expect(screen.getByText("Lark")).toBeTruthy();
- expect(screen.getByText("Slack")).toBeTruthy();
- expect(screen.getByText("Telegram")).toBeTruthy();
- expect(screen.getByTestId("lark-bind-button").getAttribute("data-agent-id")).toBe("agent-1");
- expect(screen.getByTestId("slack-bind-button").getAttribute("data-agent-id")).toBe("agent-1");
- expect(screen.getByTestId("telegram-bind-button").getAttribute("data-agent-id")).toBe(
- "agent-1",
- );
- });
-
- it("shows only this Agent's 1:1 bot and its groups", () => {
- vi.useFakeTimers();
- vi.setSystemTime(new Date("2026-08-19T10:00:00Z"));
- installationsRef.current = {
- installations: [
- { id: "inst-1", agent_id: "agent-1", status: "active" },
- ],
- configured: true,
- install_supported: true,
- };
- groupsRef.current.data.groups = [
- {
- conversation_id: "cid-platform",
- conversation_title: "Platform team",
- bots: [
- {
- installation_id: "inst-1",
- agent_id: "agent-1",
- bot_name: "Release Bot",
- bot_identity_issue: "",
- last_active_at: "2026-08-19T08:00:00Z",
- mention_count: 18,
- },
- {
- installation_id: "inst-2",
- agent_id: "agent-2",
- bot_name: "Support Bot",
- bot_identity_issue: "",
- },
- ],
- },
- {
- conversation_id: "cid-unrelated",
- conversation_title: "Unrelated group",
- bots: [
- {
- installation_id: "inst-3",
- agent_id: "agent-3",
- bot_name: "Other Bot",
- bot_identity_issue: "",
- },
- ],
- },
- ];
-
- renderTab(<IntegrationsTab agent={agent} />);
- expect(screen.getByText("Platform team")).toBeTruthy();
- expect(screen.getByText("Release Bot")).toBeTruthy();
- const connectedLabel = screen.getByText("Connected bot:");
- expect(connectedLabel.parentElement?.parentElement?.classList).toContain(
- "text-caption",
- );
- const groupDescription = screen.getByText(
- enSettings.dingtalk.groups_description,
- );
- expect(groupDescription.classList).toContain("text-caption");
- expect(groupDescription.classList).not.toContain("text-micro");
- const groupName = screen.getByText("Platform team");
- expect(groupName.classList).toContain("min-w-0");
- expect(groupName.parentElement?.classList).toContain("flex-1");
- const conversationId = screen.getByLabelText(
- "DingTalk group conversation ID cid-platform",
- );
- expect(conversationId.textContent).toBe("cid-platform");
- expect(conversationId.classList).toContain("text-micro");
- expect(conversationId.classList).toContain("text-faint-foreground");
- expect(conversationId.classList).toContain("group-hover:text-muted-foreground");
- const activity = screen.getByTestId("dingtalk-group-activity");
- expect(activity.textContent).toBe("Last active 2h ago·18 mentions");
- expect(activity.classList).toContain("tabular-nums");
- expect(activity.classList).not.toContain("whitespace-nowrap");
- expect(conversationId.parentElement?.parentElement).toBe(
- groupName.parentElement?.parentElement,
- );
- expect(activity.parentElement).not.toBe(screen.getByText("Platform team").parentElement);
- expect(screen.queryByText("Support Bot")).toBeNull();
- expect(screen.queryByText("Unrelated group")).toBeNull();
- });
-
- it("keeps the member-visible group list available to a non-owner member", () => {
- membersRef.current = [{ user_id: "user-1", role: "member" }];
- installationsRef.current = {
- installations: [
- { id: "inst-1", agent_id: "agent-1", status: "active" },
- ],
- configured: true,
- install_supported: true,
- };
- groupsRef.current.data.groups = [
- {
- conversation_id: "cid-platform",
- conversation_title: "Platform team",
- bots: [
- {
- installation_id: "inst-1",
- agent_id: "agent-1",
- bot_name: "Release Bot",
- bot_identity_issue: "",
- },
- ],
- },
- ];
-
- renderTab(<IntegrationsTab agent={{ ...agent, owner_id: "user-2" }} />);
- expect(screen.getByText("Platform team")).toBeTruthy();
- expect(screen.getByText("Release Bot")).toBeTruthy();
- expect(screen.getByText("Connected bot:")).toBeTruthy();
- expect(screen.queryByText(/Connected to Agent/i)).toBeNull();
- expect(screen.queryByText("Lark")).toBeNull();
- });
-
- it("shows the latest permission remediation to an Agent owner even when a cached bot name remains", async () => {
- membersRef.current = [{ user_id: "user-1", role: "member" }];
- installationsRef.current = {
- installations: [
- { id: "inst-1", agent_id: "agent-1", status: "active" },
- ],
- configured: true,
- install_supported: true,
- };
- groupsRef.current.data.groups = [
- {
- conversation_id: "cid-named",
- conversation_title: "Release room",
- bots: [
- {
- installation_id: "inst-1",
- agent_id: "agent-1",
- bot_name: "Release Bot",
- bot_identity_issue: "",
- },
- ],
- },
- {
- conversation_id: "cid-unnamed",
- conversation_title: "",
- bots: [
- {
- installation_id: "inst-1",
- agent_id: "agent-1",
- bot_name: "",
- bot_identity_issue: "missing_qyapi_chat_manage",
- },
- ],
- },
- ];
- renderTab(<IntegrationsTab agent={agent} />);
- expect(screen.getByText("Untitled DingTalk group")).toBeTruthy();
- expect(screen.getByText("Release Bot")).toBeTruthy();
- const info = screen.getByRole("button", { name: /qyapi_chat_manage/ });
- await userEvent.click(info);
- const permissionCode = await screen.findByText("qyapi_chat_manage", {
- selector: "code",
- });
- expect(permissionCode.closest('[data-slot="tooltip-content"]')?.textContent).toContain(
- "grant this bot's app the qyapi_chat_manage permission, then @mention the bot again in a DingTalk group where it has been added.",
- );
- });
-
- it("hides permission remediation from a read-only Agent viewer", () => {
- membersRef.current = [{ user_id: "user-1", role: "member" }];
- installationsRef.current = {
- installations: [
- { id: "inst-1", agent_id: "agent-1", status: "active" },
- ],
- configured: true,
- install_supported: true,
- };
- groupsRef.current.data.groups = [
- {
- conversation_id: "cid-unnamed",
- conversation_title: "Visible group",
- bots: [
- {
- installation_id: "inst-1",
- agent_id: "agent-1",
- bot_name: "",
- bot_identity_issue: "missing_qyapi_chat_manage",
- },
- ],
- },
- ];
-
- renderTab(<IntegrationsTab agent={{ ...agent, owner_id: "user-2" }} />);
- expect(screen.getByText("Identity unavailable")).toBeTruthy();
- expect(screen.queryByRole("button", { name: /qyapi_chat_manage/ })).toBeNull();
- });
-
- it("renders group loading, empty, and retryable error states", async () => {
- installationsRef.current = {
- installations: [
- { id: "inst-1", agent_id: "agent-1", status: "active" },
- ],
- configured: true,
- install_supported: true,
- };
- groupsRef.current.isLoading = true;
- groupsRef.current.data = undefined as never;
- const loading = renderTab(<IntegrationsTab agent={agent} />);
- expect(screen.getByText("Loading groups…")).toBeTruthy();
- loading.unmount();
-
- groupsRef.current.isLoading = false;
- groupsRef.current.data = {
- groups: [],
- group_discovery_supported: true,
- };
- const empty = renderTab(<IntegrationsTab agent={agent} />);
- expect(screen.getByText("No group messages observed yet.")).toBeTruthy();
- empty.unmount();
-
- groupsRef.current.isError = true;
- groupsRef.current.data = undefined as never;
- renderTab(<IntegrationsTab agent={agent} />);
- await userEvent.click(screen.getByRole("button", { name: "Retry" }));
- expect(groupsRef.current.refetch).toHaveBeenCalledOnce();
- });
-
- it("renders discovery UI only when the backend explicitly supports it", () => {
- installationsRef.current = {
- installations: [
- { id: "inst-1", agent_id: "agent-1", status: "active" },
- ],
- configured: true,
- install_supported: true,
- };
- groupsRef.current.data = {
- groups: [],
- group_discovery_supported: false,
- };
-
- renderTab(<IntegrationsTab agent={agent} />);
- expect(screen.getByText("Connected bot:")).toBeTruthy();
- expect(screen.queryByText("Identity unavailable")).toBeNull();
- expect(screen.queryByTestId("dingtalk-bot-groups")).toBeNull();
- });
-
- it("shows the coming-soon notice when the install transport is not wired", () => {
- installationsRef.current = {
- installations: [],
- configured: true,
- install_supported: false,
- };
- renderTab(<IntegrationsTab agent={agent} />);
- expect(screen.getByText(/installation coming soon/i)).toBeTruthy();
- expect(screen.queryByTestId("lark-bind-button")).toBeNull();
- });
-
- it("shows the not-enabled notice when the deployment has no Lark key", () => {
- installationsRef.current = {
- installations: [],
- configured: false,
- install_supported: false,
- };
- renderTab(<IntegrationsTab agent={agent} />);
- expect(screen.getByText(/Lark integration not enabled/i)).toBeTruthy();
- expect(screen.queryByTestId("lark-bind-button")).toBeNull();
- });
-
- it("points members at Settings when they are neither an admin nor the agent owner", () => {
- // A plain member viewing an agent owned by someone else can manage
- // neither platform, so the read-only note replaces both sections.
- membersRef.current = [{ user_id: "user-1", role: "member" }];
- renderTab(<IntegrationsTab agent={{ ...agent, owner_id: "user-2" }} />);
- expect(
- screen.getAllByText(/Only workspace owners and admins can manage this connection/i).length,
- ).toBeGreaterThanOrEqual(1);
- expect(screen.queryByTestId("lark-bind-button")).toBeNull();
- expect(screen.queryByTestId("slack-bind-button")).toBeNull();
- expect(screen.queryByTestId("wecom-bind-button")).toBeNull();
- expect(screen.queryByTestId("telegram-bind-button")).toBeNull();
- });
-
- it("lets a non-admin agent owner bind Lark and DingTalk", () => {
- // The agent's owner (user-1) is only a plain workspace member. Lark and
- // DingTalk both authorize the target agent's owner through canManageAgent;
- // Slack, WeCom and Telegram remain workspace owner/admin-only.
- membersRef.current = [{ user_id: "user-1", role: "member" }];
- renderTab(<IntegrationsTab agent={agent} />);
- const larkButton = screen.getByTestId("lark-bind-button");
- expect(larkButton.getAttribute("data-agent-id")).toBe("agent-1");
- expect(larkButton.getAttribute("data-agent-owner-id")).toBe("user-1");
- expect(screen.getByTestId("dingtalk-agent-connect")).toBeTruthy();
- expect(screen.queryByTestId("slack-bind-button")).toBeNull();
- expect(screen.queryByTestId("wecom-bind-button")).toBeNull();
- expect(screen.queryByTestId("telegram-bind-button")).toBeNull();
- // The Slack, WeCom and Telegram sections fall back to the shared members note.
- expect(
- screen.getAllByText(/Only workspace owners and admins can manage this connection/i),
- ).toHaveLength(3);
- });
-
- it("renders the bind entry (not coming-soon) when installs are unavailable but the agent is already bound", () => {
- // install_supported governs only NEW installs; an already-bound agent
- // must still surface its connected state instead of "coming soon"
- // (regression for the must-fix on MUL-2988).
- installationsRef.current = {
- installations: [{ agent_id: "agent-1", status: "active" }],
- configured: true,
- install_supported: false,
- };
- renderTab(<IntegrationsTab agent={agent} />);
- expect(screen.getByTestId("lark-bind-button")).toBeTruthy();
- expect(screen.queryByText(/installation coming soon/i)).toBeNull();
- });
-});
diff --git a/packages/views/agents/components/tabs/integrations-tab.tsx b/packages/views/agents/components/tabs/integrations-tab.tsx
deleted file mode 100644
index 9db4340ac5..0000000000
--- a/packages/views/agents/components/tabs/integrations-tab.tsx
+++ /dev/null
@@ -1,443 +0,0 @@
-"use client";
-
-import { useQuery } from "@tanstack/react-query";
-import type { Agent } from "@multica/core/types";
-import { useAuthStore } from "@multica/core/auth";
-import { useWorkspaceId } from "@multica/core/hooks";
-import { larkInstallationsOptions } from "@multica/core/lark";
-import { slackInstallationsOptions } from "@multica/core/slack";
-import {
- dingtalkAgentGroupsOptions,
- dingtalkInstallationsOptions,
-} from "@multica/core/dingtalk";
-import { wecomInstallationsOptions } from "@multica/core/wecom";
-import { telegramInstallationsOptions } from "@multica/core/telegram";
-import { memberListOptions } from "@multica/core/workspace/queries";
-import { LarkAgentBindButton } from "../../../settings/components/lark-tab";
-import { LarkMark } from "../../../settings/components/lark-mark";
-import { SlackAgentBindButton } from "../../../settings/components/slack-tab";
-import { SlackMark } from "../../../settings/components/slack-mark";
-import {
- DingTalkAgentBindButton,
- DingTalkBotGroups,
- DingTalkConnectionLabel,
- getDingTalkBotIdentity,
-} from "../../../settings/components/dingtalk-tab";
-import { DingTalkMark } from "../../../settings/components/dingtalk-mark";
-import { WecomAgentBindButton } from "../../../settings/components/wecom-tab";
-import { WecomMark } from "../../../settings/components/wecom-mark";
-import { TelegramAgentBindButton } from "../../../settings/components/telegram-tab";
-import { TelegramMark } from "../../../settings/components/telegram-mark";
-import { useT } from "../../../i18n";
-
-/**
- * Integrations tab on the agent detail page. Surfaces the same external-
- * channel bind entry point as the inspector's "Integrations" section
- * (Lark Bot today) — scan-to-bind when unbound, connected info when bound —
- * but with the room a tab affords for a heading, a description, and the
- * not-configured / coming-soon / members-only states the cramped sidebar
- * section has no space for.
- *
- * The actionable affordance is the shared `LarkAgentBindButton`, the single
- * source of truth for "scan to bind vs. already connected". This tab only
- * adds the explanatory chrome around it, so the two entry points can never
- * drift.
- */
-export function IntegrationsTab({ agent }: { agent: Agent }) {
- const { t } = useT("agents");
- const { t: ts } = useT("settings");
- const wsId = useWorkspaceId();
- const user = useAuthStore((s) => s.user);
-
- // Both queries are already issued by LarkAgentBindButton (and keyed per
- // workspace), so re-reading them here is free — TanStack dedupes by key.
- // We only need the derived booleans to pick which copy sits next to the
- // button, mirroring the branch order LarkTab uses in Settings.
- const { data: listing } = useQuery({
- ...larkInstallationsOptions(wsId),
- enabled: !!wsId,
- });
- const { data: slackListing } = useQuery({
- ...slackInstallationsOptions(wsId),
- enabled: !!wsId,
- });
- const { data: dingtalkListing } = useQuery({
- ...dingtalkInstallationsOptions(wsId),
- });
- const { data: wecomListing } = useQuery({
- ...wecomInstallationsOptions(wsId),
- enabled: !!wsId,
- });
- const { data: telegramListing } = useQuery({
- ...telegramInstallationsOptions(wsId),
- enabled: !!wsId,
- });
- const { data: members = [] } = useQuery({
- ...memberListOptions(wsId),
- enabled: !!wsId,
- });
-
- const configured = listing?.configured === true;
- const installSupported = listing?.install_supported === true;
- const currentMember = members.find((m) => m.user_id === user?.id) ?? null;
- const isWorkspaceAdmin =
- currentMember?.role === "owner" || currentMember?.role === "admin";
- const isAgentOwner =
- currentMember != null &&
- !!user?.id &&
- agent.owner_id != null &&
- agent.owner_id === user.id;
- // Lark bind/manage is authorized for the agent's owner OR a workspace
- // owner/admin (server/internal/handler/lark.go canManageAgent, MUL-4213).
- // Slack's install/revoke routes are still workspace owner/admin-only, so
- // its gate stays admin-only — the agent owner must not see a Slack CTA the
- // backend would 403.
- const canManageLark = isWorkspaceAdmin || isAgentOwner;
- const canManageSlack = isWorkspaceAdmin;
- const canManageWecom = isWorkspaceAdmin;
- const canManageTelegram = isWorkspaceAdmin;
- const hasActiveInstall =
- listing?.installations.some(
- (inst) => inst.agent_id === agent.id && inst.status === "active",
- ) ?? false;
-
- const slackConfigured = slackListing?.configured === true;
- const slackInstallSupported = slackListing?.install_supported === true;
- const slackHasActiveInstall =
- slackListing?.installations.some(
- (inst) => inst.agent_id === agent.id && inst.status === "active",
- ) ?? false;
-
- const dingtalkConfigured = dingtalkListing?.configured === true;
- const dingtalkInstallation = dingtalkListing?.installations.find(
- (inst) => inst.agent_id === agent.id && inst.status === "active",
- );
- const dingtalkHasActiveInstall = !!dingtalkInstallation;
- const {
- data: dingtalkGroupsListing,
- isLoading: dingtalkGroupsLoading,
- isError: dingtalkGroupsError,
- refetch: retryDingtalkGroups,
- } = useQuery({
- ...dingtalkAgentGroupsOptions(wsId, agent.id),
- enabled: !!wsId && dingtalkHasActiveInstall,
- });
- const dingtalkGroups = dingtalkGroupsListing?.groups ?? [];
- const dingtalkGroupDiscoverySupported =
- dingtalkGroupsListing?.group_discovery_supported === true;
- const showDingtalkGroupDiscovery =
- dingtalkGroupDiscoverySupported ||
- dingtalkGroupsLoading ||
- dingtalkGroupsError;
- const dingtalkBotIdentity = dingtalkInstallation
- ? dingtalkGroupsListing?.bot_identities?.[dingtalkInstallation.id] ??
- getDingTalkBotIdentity(dingtalkGroups, dingtalkInstallation.id)
- : undefined;
- // DingTalk uses the same per-agent management rule as Lark: the target
- // agent's owner or a workspace owner/admin may connect and disconnect it.
- const canManageDingtalk = isWorkspaceAdmin || isAgentOwner;
-
- const wecomConfigured = wecomListing?.configured === true;
- const wecomInstallSupported = wecomListing?.install_supported === true;
- const wecomHasActiveInstall =
- wecomListing?.installations.some(
- (inst) => inst.agent_id === agent.id && inst.status === "active",
- ) ?? false;
-
- const telegramConfigured = telegramListing?.configured === true;
- const telegramInstallSupported = telegramListing?.install_supported === true;
- const telegramHasActiveInstall =
- telegramListing?.installations.some(
- (inst) => inst.agent_id === agent.id && inst.status === "active",
- ) ?? false;
-
- // Preserve the established Integrations management gate: a member who can
- // manage no platform gets the read-only note instead of install controls.
- // The agent-scoped DingTalk relationship remains visible because reaching
- // this Agent detail already passed the server's Agent view permission gate.
- if (
- !canManageLark &&
- !canManageSlack &&
- !canManageDingtalk &&
- !canManageWecom &&
- !canManageTelegram
- ) {
- return (
- <div className="space-y-6">
- {dingtalkInstallation ? (
- <section className="rounded-lg border">
- <div className="flex items-start gap-3 p-4">
- <span className="flex h-9 w-9 shrink-0 items-center justify-center rounded-md border bg-muted/40 text-muted-foreground">
- <DingTalkMark className="h-5 w-5" />
- </span>
- <div className="min-w-0 flex-1 space-y-1">
- <h3 className="text-body font-medium">
- {ts(($) => $.dingtalk.section_title)}
- </h3>
- <p className="text-caption leading-relaxed text-muted-foreground">
- {ts(($) => $.dingtalk.agent_page_description)}
- </p>
- </div>
- </div>
- <div className="border-t px-4 py-3">
- <DingTalkConnectionLabel
- botName={dingtalkBotIdentity?.bot_name ?? ""}
- botIdentityIssue={dingtalkBotIdentity?.bot_identity_issue ?? ""}
- showBotIdentity={
- dingtalkGroupDiscoverySupported && !dingtalkGroupsLoading
- }
- showPermissionHelp={false}
- />
- </div>
- {showDingtalkGroupDiscovery && (
- <div className="border-t px-4 pb-4">
- <DingTalkBotGroups
- workspaceId={wsId}
- agentId={agent.id}
- installationId={dingtalkInstallation.id}
- groups={dingtalkGroups}
- inactiveCount={dingtalkGroupsListing?.inactive_group_counts?.[dingtalkInstallation.id] ?? 0}
- isLoading={dingtalkGroupsLoading}
- isError={dingtalkGroupsError}
- onRetry={() => void retryDingtalkGroups()}
- />
- </div>
- )}
- </section>
- ) : (
- <p className="text-caption text-muted-foreground">
- {t(($) => $.tab_body.integrations.members_note)}
- </p>
- )}
- </div>
- );
- }
-
- return (
- <div className="space-y-6">
-
- <section className="rounded-lg border">
- <div className="flex items-start gap-3 p-4">
- <span className="flex h-9 w-9 shrink-0 items-center justify-center rounded-md border bg-muted/40 text-muted-foreground">
- <LarkMark className="h-4 w-4" />
- </span>
- <div className="min-w-0 flex-1 space-y-1">
- <h3 className="text-body font-medium">{ts(($) => $.lark.section_title)}</h3>
- <p className="text-caption leading-relaxed text-muted-foreground">
- {ts(($) => $.lark.page_description)}
- </p>
- </div>
- </div>
- <div className="border-t px-4 py-3">
- {!configured ? (
- // No at-rest key on this deployment. The tab is only mounted
- // when the feature is configured, so this is the rare "key was
- // removed after an install existed" race.
- <p className="text-caption text-muted-foreground">
- {ts(($) => $.lark.not_enabled_title)}
- </p>
- ) : !installSupported && !hasActiveInstall ? (
- // Key is set but the device-flow transport isn't wired in this
- // build — a fresh scan would fail at the post-poll bot-info step,
- // so we surface the "coming soon" notice instead of a broken CTA.
- // An agent that is ALREADY bound is exempt: install_supported only
- // governs NEW installs, so the bound state must still render below
- // (server/internal/handler/lark.go).
- <div className="space-y-1">
- <p className="text-caption font-medium">{ts(($) => $.lark.preview_title)}</p>
- <p className="text-caption text-muted-foreground">
- {ts(($) => $.lark.preview_description)}
- </p>
- </div>
- ) : (
- // Agent owner or workspace owner/admin with either a supported
- // transport or an existing bot: the shared button renders the
- // scan-to-bind CTA or the already-connected "Manage in Lark"
- // badge. It self-authorizes on agentOwnerId + role.
- <LarkAgentBindButton
- agentId={agent.id}
- agentName={agent.name}
- agentOwnerId={agent.owner_id}
- />
- )}
- </div>
- </section>
-
- <section className="rounded-lg border">
- <div className="flex items-start gap-3 p-4">
- <span className="flex h-9 w-9 shrink-0 items-center justify-center rounded-md border bg-muted/40 text-muted-foreground">
- <SlackMark className="h-4 w-4" />
- </span>
- <div className="min-w-0 flex-1 space-y-1">
- <h3 className="text-body font-medium">{ts(($) => $.slack.section_title)}</h3>
- <p className="text-caption leading-relaxed text-muted-foreground">
- {ts(($) => $.slack.page_description)}
- </p>
- </div>
- </div>
- <div className="border-t px-4 py-3">
- {!canManageSlack ? (
- // Slack install/revoke stay workspace owner/admin-only, so an
- // agent owner who is not an admin only gets the read-only note
- // here (unlike Lark above). Reuses the shared members note.
- <p className="text-caption text-muted-foreground">
- {t(($) => $.tab_body.integrations.members_note)}
- </p>
- ) : !slackConfigured ? (
- <p className="text-caption text-muted-foreground">
- {ts(($) => $.slack.not_enabled_title)}
- </p>
- ) : !slackInstallSupported && !slackHasActiveInstall ? (
- // Secret key is set but the OAuth client credentials aren't, so a
- // fresh "Connect Slack" would be rejected. Surface the "coming soon"
- // notice instead of a broken CTA; an already-bound agent still renders.
- <div className="space-y-1">
- <p className="text-caption font-medium">{ts(($) => $.slack.preview_title)}</p>
- <p className="text-caption text-muted-foreground">
- {ts(($) => $.slack.preview_description)}
- </p>
- </div>
- ) : (
- <SlackAgentBindButton agentId={agent.id} agentName={agent.name} />
- )}
- </div>
- </section>
-
- <section className="rounded-lg border">
- <div className="flex items-start gap-3 p-4">
- <span className="flex h-9 w-9 shrink-0 items-center justify-center rounded-md border bg-muted/40 text-muted-foreground">
- <DingTalkMark className="h-5 w-5" />
- </span>
- <div className="min-w-0 flex-1 space-y-1">
- <h3 className="text-body font-medium">{ts(($) => $.dingtalk.section_title)}</h3>
- <p className="text-caption leading-relaxed text-muted-foreground">
- {ts(($) => $.dingtalk.agent_page_description)}
- </p>
- </div>
- </div>
- <div className="border-t px-4 py-3">
- {!canManageDingtalk ? (
- // Viewers who cannot manage this agent still see its connected
- // DingTalk identity and discovered groups as read-only details.
- dingtalkInstallation ? (
- <DingTalkConnectionLabel
- botName={dingtalkBotIdentity?.bot_name ?? ""}
- botIdentityIssue={dingtalkBotIdentity?.bot_identity_issue ?? ""}
- showBotIdentity={
- dingtalkGroupDiscoverySupported && !dingtalkGroupsLoading
- }
- showPermissionHelp={false}
- />
- ) : (
- <p className="text-caption text-muted-foreground">
- {t(($) => $.tab_body.integrations.members_note)}
- </p>
- )
- ) : !dingtalkConfigured ? (
- <p className="text-caption text-muted-foreground">
- {ts(($) => $.dingtalk.not_enabled_title)}
- </p>
- ) : (
- <DingTalkAgentBindButton
- agentId={agent.id}
- agentName={agent.name}
- agentOwnerId={agent.owner_id}
- botName={
- dingtalkGroupsLoading || !dingtalkGroupDiscoverySupported
- ? undefined
- : (dingtalkBotIdentity?.bot_name ?? "")
- }
- botIdentityIssue={
- dingtalkGroupsLoading || !dingtalkGroupDiscoverySupported
- ? undefined
- : (dingtalkBotIdentity?.bot_identity_issue ?? "")
- }
- />
- )}
- </div>
- {dingtalkInstallation && showDingtalkGroupDiscovery && (
- <div className="border-t px-4 pb-4">
- <DingTalkBotGroups
- workspaceId={wsId}
- agentId={agent.id}
- installationId={dingtalkInstallation.id}
- groups={dingtalkGroups}
- inactiveCount={dingtalkGroupsListing?.inactive_group_counts?.[dingtalkInstallation.id] ?? 0}
- isLoading={dingtalkGroupsLoading}
- isError={dingtalkGroupsError}
- onRetry={() => void retryDingtalkGroups()}
- />
- </div>
- )}
- </section>
-
- <section className="rounded-lg border">
- <div className="flex items-start gap-3 p-4">
- <span className="flex h-9 w-9 shrink-0 items-center justify-center rounded-md border bg-muted/40 text-muted-foreground">
- <WecomMark className="h-4 w-4" />
- </span>
- <div className="min-w-0 flex-1 space-y-1">
- <h3 className="text-body font-medium">{ts(($) => $.wecom.section_title)}</h3>
- <p className="text-caption leading-relaxed text-muted-foreground">
- {ts(($) => $.wecom.page_description)}
- </p>
- </div>
- </div>
- <div className="border-t px-4 py-3">
- {!canManageWecom ? (
- <p className="text-caption text-muted-foreground">
- {t(($) => $.tab_body.integrations.members_note)}
- </p>
- ) : !wecomConfigured ? (
- <p className="text-caption text-muted-foreground">
- {ts(($) => $.wecom.not_enabled_title)}
- </p>
- ) : !wecomInstallSupported && !wecomHasActiveInstall ? (
- <div className="space-y-1">
- <p className="text-caption font-medium">{ts(($) => $.wecom.preview_title)}</p>
- <p className="text-caption text-muted-foreground">
- {ts(($) => $.wecom.preview_description)}
- </p>
- </div>
- ) : (
- <WecomAgentBindButton agentId={agent.id} agentName={agent.name} />
- )}
- </div>
- </section>
-
- <section className="rounded-lg border">
- <div className="flex items-start gap-3 p-4">
- <span className="flex h-9 w-9 shrink-0 items-center justify-center rounded-md border bg-muted/40 text-muted-foreground">
- <TelegramMark className="h-4 w-4" />
- </span>
- <div className="min-w-0 flex-1 space-y-1">
- <h3 className="text-body font-medium">{ts(($) => $.telegram.section_title)}</h3>
- <p className="text-caption leading-relaxed text-muted-foreground">
- {ts(($) => $.telegram.page_description)}
- </p>
- </div>
- </div>
- <div className="border-t px-4 py-3">
- {!canManageTelegram ? (
- <p className="text-caption text-muted-foreground">
- {t(($) => $.tab_body.integrations.members_note)}
- </p>
- ) : !telegramConfigured ? (
- <p className="text-caption text-muted-foreground">
- {ts(($) => $.telegram.not_enabled_title)}
- </p>
- ) : !telegramInstallSupported && !telegramHasActiveInstall ? (
- <div className="space-y-1">
- <p className="text-caption font-medium">{ts(($) => $.telegram.preview_title)}</p>
- <p className="text-caption text-muted-foreground">
- {ts(($) => $.telegram.preview_description)}
- </p>
- </div>
- ) : (
- <TelegramAgentBindButton agentId={agent.id} agentName={agent.name} />
- )}
- </div>
- </section>
- </div>
- );
-}
diff --git a/packages/views/locales/en/agents.json b/packages/views/locales/en/agents.json
index 1ee2f2f7f1..8152bb7fee 100644
--- a/packages/views/locales/en/agents.json
+++ b/packages/views/locales/en/agents.json
@@ -752,7 +752,7 @@
"add_failed_toast": "Failed to add skill"
},
"integrations": {
- "members_note": "Only workspace owners and admins can manage this connection. You can view connected bots in Settings → Integrations."
+ "members_note": "View and manage messaging channels on the agent page."
},
"activity": {
"status": {
diff --git a/packages/views/locales/en/settings.json b/packages/views/locales/en/settings.json
index 488c296bc8..a1fab946d5 100644
--- a/packages/views/locales/en/settings.json
+++ b/packages/views/locales/en/settings.json
@@ -1618,7 +1618,42 @@
"github_actions": "GitHub actions"
},
"channels": {
- "breadcrumb": "Breadcrumb"
+ "breadcrumb": "Breadcrumb",
+ "add": "Add messaging channel",
+ "connect": "Connect",
+ "disconnect": "Disconnect",
+ "open": "Open",
+ "normal": "Connected",
+ "waiting_message": "Waiting for first message",
+ "disconnected": "Disconnected",
+ "find_me": "Find me on {{platform}}",
+ "manage": "Manage {{platform}}",
+ "last_message": "Last message {{time}}",
+ "ask_admin": "Ask an admin",
+ "unavailable": "Connection unavailable",
+ "server_unavailable": "Not enabled on this server: {{platforms}}",
+ "permissions_title": "Who can connect",
+ "owner_or_admin": "Agent owner or workspace admin",
+ "admin_only": "Workspace admins only",
+ "connect_title": "Connect messaging channel",
+ "choose_description": "Choose an agent and a platform.",
+ "authorize_description": "Connect {{agent}} to {{platform}}.",
+ "agent_label": "Agent",
+ "choose_agent": "Choose an agent",
+ "platform_label": "Platform",
+ "region_label": "Region",
+ "method_label": "Connection method",
+ "continue": "Continue",
+ "feishu": "Feishu (China)",
+ "lark": "Lark (International)",
+ "setup_guide": "Setup guide",
+ "connection_changed": "This connection is no longer available. Close this dialog and try again.",
+ "connect_failed": "Could not connect the bot.",
+ "connect_success": "Messaging channel connected.",
+ "disconnect_failed": "Could not disconnect the bot.",
+ "disconnect_title": "Disconnect messaging channel?",
+ "disconnect_description": "This agent will stop receiving messages from {{platform}}.",
+ "agent_unavailable": "Agent unavailable"
},
"mcp_usage": {
"agent_count_one": "Used by {{count}} agent",
diff --git a/packages/views/locales/es/agents.json b/packages/views/locales/es/agents.json
index 9bf38d21da..f5786ed312 100644
--- a/packages/views/locales/es/agents.json
+++ b/packages/views/locales/es/agents.json
@@ -734,7 +734,7 @@
"add_failed_toast": "No se ha podido añadir la skill"
},
"integrations": {
- "members_note": "Solo los propietarios y administradores del espacio de trabajo pueden gestionar esta conexión. Puedes ver los bots conectados en Ajustes → Integraciones."
+ "members_note": "Consulta y gestiona los canales de mensajería en la página del agente."
},
"activity": {
"status": {
diff --git a/packages/views/locales/es/settings.json b/packages/views/locales/es/settings.json
index 62d0fcb5d7..087027d878 100644
--- a/packages/views/locales/es/settings.json
+++ b/packages/views/locales/es/settings.json
@@ -1593,7 +1593,42 @@
"status_unknown": "Estado no disponible"
},
"channels": {
- "breadcrumb": "Migas de pan"
+ "breadcrumb": "Migas de pan",
+ "add": "Añadir canal de mensajería",
+ "connect": "Conectar",
+ "disconnect": "Desconectar",
+ "open": "Abrir",
+ "normal": "Conectado",
+ "waiting_message": "Esperando el primer mensaje",
+ "disconnected": "Desconectado",
+ "find_me": "Encuéntrame en {{platform}}",
+ "manage": "Gestionar {{platform}}",
+ "last_message": "Último mensaje: {{time}}",
+ "ask_admin": "Pide ayuda a un administrador",
+ "unavailable": "Conexión no disponible",
+ "server_unavailable": "No habilitado en este servidor: {{platforms}}",
+ "permissions_title": "Quién puede conectar",
+ "owner_or_admin": "Propietario del agente o administrador del espacio",
+ "admin_only": "Solo administradores del espacio",
+ "connect_title": "Conectar canal de mensajería",
+ "choose_description": "Elige un agente y una plataforma.",
+ "authorize_description": "Conectar {{agent}} a {{platform}}.",
+ "agent_label": "Agente",
+ "choose_agent": "Elegir agente",
+ "platform_label": "Plataforma",
+ "region_label": "Región",
+ "method_label": "Método de conexión",
+ "continue": "Continuar",
+ "feishu": "Feishu (China)",
+ "lark": "Lark (internacional)",
+ "setup_guide": "Guía de configuración",
+ "connection_changed": "Esta conexión ya no está disponible. Cierra esta ventana y vuelve a intentarlo.",
+ "connect_failed": "No se pudo conectar el bot.",
+ "connect_success": "Canal de mensajería conectado.",
+ "disconnect_failed": "No se pudo desconectar el bot.",
+ "disconnect_title": "¿Desconectar el canal de mensajería?",
+ "disconnect_description": "Este agente dejará de recibir mensajes de {{platform}}.",
+ "agent_unavailable": "Agente no disponible"
},
"code": {
"github_actions": "Acciones de GitHub",
diff --git a/packages/views/locales/fr/agents.json b/packages/views/locales/fr/agents.json
index 75dee69299..8d7512c789 100644
--- a/packages/views/locales/fr/agents.json
+++ b/packages/views/locales/fr/agents.json
@@ -752,7 +752,7 @@
"add_failed_toast": "Échec de l'ajout du skill"
},
"integrations": {
- "members_note": "Seuls les propriétaires et administrateurs de l'espace de travail peuvent gérer cette connexion. Vous pouvez voir les bots connectés dans Paramètres → Intégrations."
+ "members_note": "Consultez et gérez les canaux de messagerie sur la page de l’agent."
},
"activity": {
"status": {
diff --git a/packages/views/locales/fr/settings.json b/packages/views/locales/fr/settings.json
index c97f195e89..a56ec5a892 100644
--- a/packages/views/locales/fr/settings.json
+++ b/packages/views/locales/fr/settings.json
@@ -1618,7 +1618,42 @@
"github_actions": "Actions GitHub"
},
"channels": {
- "breadcrumb": "Fil d'Ariane"
+ "breadcrumb": "Fil d'Ariane",
+ "add": "Ajouter un canal de messagerie",
+ "connect": "Connecter",
+ "disconnect": "Déconnecter",
+ "open": "Ouvrir",
+ "normal": "Connecté",
+ "waiting_message": "En attente du premier message",
+ "disconnected": "Déconnecté",
+ "find_me": "Me trouver sur {{platform}}",
+ "manage": "Gérer {{platform}}",
+ "last_message": "Dernier message : {{time}}",
+ "ask_admin": "Contacter un administrateur",
+ "unavailable": "Connexion indisponible",
+ "server_unavailable": "Non activé sur ce serveur : {{platforms}}",
+ "permissions_title": "Qui peut connecter",
+ "owner_or_admin": "Propriétaire de l’agent ou administrateur de l’espace",
+ "admin_only": "Administrateurs de l’espace uniquement",
+ "connect_title": "Connecter un canal de messagerie",
+ "choose_description": "Choisissez un agent et une plateforme.",
+ "authorize_description": "Connecter {{agent}} à {{platform}}.",
+ "agent_label": "Agent",
+ "choose_agent": "Choisir un agent",
+ "platform_label": "Plateforme",
+ "region_label": "Région",
+ "method_label": "Méthode de connexion",
+ "continue": "Continuer",
+ "feishu": "Feishu (Chine)",
+ "lark": "Lark (international)",
+ "setup_guide": "Guide de configuration",
+ "connection_changed": "Cette connexion n’est plus disponible. Fermez cette fenêtre et réessayez.",
+ "connect_failed": "Impossible de connecter le bot.",
+ "connect_success": "Canal de messagerie connecté.",
+ "disconnect_failed": "Impossible de déconnecter le bot.",
+ "disconnect_title": "Déconnecter le canal de messagerie ?",
+ "disconnect_description": "Cet agent ne recevra plus de messages de {{platform}}.",
+ "agent_unavailable": "Agent indisponible"
},
"mcp_usage": {
"agent_count_one": "Utilisé par {{count}} agent",
diff --git a/packages/views/locales/ja/agents.json b/packages/views/locales/ja/agents.json
index 8efac6eac9..400858bf88 100644
--- a/packages/views/locales/ja/agents.json
+++ b/packages/views/locales/ja/agents.json
@@ -592,7 +592,7 @@
"add_failed_toast": "スキルを追加できませんでした"
},
"integrations": {
- "members_note": "この接続を管理できるのはワークスペースのオーナーと管理者のみです。接続済みの Bot は「設定 → 連携」で確認できます。"
+ "members_note": "エージェントのページでメッセージチャネルを確認・管理できます。"
},
"activity": {
"status": {
diff --git a/packages/views/locales/ja/settings.json b/packages/views/locales/ja/settings.json
index a8c94f62a3..456459232d 100644
--- a/packages/views/locales/ja/settings.json
+++ b/packages/views/locales/ja/settings.json
@@ -1603,7 +1603,42 @@
"github_actions": "GitHub の操作"
},
"channels": {
- "breadcrumb": "パンくずリスト"
+ "breadcrumb": "パンくずリスト",
+ "add": "メッセージチャネルを追加",
+ "connect": "接続",
+ "disconnect": "接続を解除",
+ "open": "開く",
+ "normal": "接続済み",
+ "waiting_message": "最初のメッセージを待機中",
+ "disconnected": "未接続",
+ "find_me": "{{platform}} で話す",
+ "manage": "{{platform}} を管理",
+ "last_message": "最終メッセージ:{{time}}",
+ "ask_admin": "管理者に依頼",
+ "unavailable": "接続できません",
+ "server_unavailable": "サーバーで未有効:{{platforms}}",
+ "permissions_title": "接続できるユーザー",
+ "owner_or_admin": "エージェント所有者またはワークスペース管理者",
+ "admin_only": "ワークスペース管理者のみ",
+ "connect_title": "メッセージチャネルを接続",
+ "choose_description": "エージェントとプラットフォームを選択してください。",
+ "authorize_description": "{{agent}} を {{platform}} に接続します。",
+ "agent_label": "エージェント",
+ "choose_agent": "エージェントを選択",
+ "platform_label": "プラットフォーム",
+ "region_label": "地域",
+ "method_label": "接続方法",
+ "continue": "続行",
+ "feishu": "Feishu(中国)",
+ "lark": "Lark(国際版)",
+ "setup_guide": "設定ガイド",
+ "connection_changed": "この接続は利用できなくなりました。閉じて再試行してください。",
+ "connect_failed": "ボットを接続できませんでした。",
+ "connect_success": "メッセージチャネルを接続しました。",
+ "disconnect_failed": "ボットの接続を解除できませんでした。",
+ "disconnect_title": "メッセージチャネルの接続を解除しますか?",
+ "disconnect_description": "このエージェントは {{platform}} からのメッセージを受信しなくなります。",
+ "agent_unavailable": "エージェントを利用できません"
},
"mcp_usage": {
"agent_count_other": "{{count}} 個のエージェントが使用中",
diff --git a/packages/views/locales/ko/agents.json b/packages/views/locales/ko/agents.json
index 0901d4b599..1562137dbb 100644
--- a/packages/views/locales/ko/agents.json
+++ b/packages/views/locales/ko/agents.json
@@ -592,7 +592,7 @@
"add_failed_toast": "스킬을 추가하지 못했습니다"
},
"integrations": {
- "members_note": "이 연결을 관리할 수 있는 사람은 워크스페이스 소유자와 관리자뿐입니다. 연결된 봇은 설정 → 연동에서 확인할 수 있습니다."
+ "members_note": "에이전트 페이지에서 메시지 채널을 확인하고 관리하세요."
},
"activity": {
"status": {
diff --git a/packages/views/locales/ko/settings.json b/packages/views/locales/ko/settings.json
index fabe24c037..b7b53e32eb 100644
--- a/packages/views/locales/ko/settings.json
+++ b/packages/views/locales/ko/settings.json
@@ -1603,7 +1603,42 @@
"github_actions": "GitHub 작업"
},
"channels": {
- "breadcrumb": "탐색 경로"
+ "breadcrumb": "탐색 경로",
+ "add": "메시지 채널 추가",
+ "connect": "연결",
+ "disconnect": "연결 해제",
+ "open": "열기",
+ "normal": "연결됨",
+ "waiting_message": "첫 메시지 대기 중",
+ "disconnected": "연결 안 됨",
+ "find_me": "{{platform}}에서 대화하기",
+ "manage": "{{platform}} 관리",
+ "last_message": "최근 메시지: {{time}}",
+ "ask_admin": "관리자에게 요청",
+ "unavailable": "연결할 수 없음",
+ "server_unavailable": "서버에서 활성화되지 않음: {{platforms}}",
+ "permissions_title": "연결 권한",
+ "owner_or_admin": "에이전트 소유자 또는 워크스페이스 관리자",
+ "admin_only": "워크스페이스 관리자만",
+ "connect_title": "메시지 채널 연결",
+ "choose_description": "에이전트와 플랫폼을 선택하세요.",
+ "authorize_description": "{{agent}}을(를) {{platform}}에 연결합니다.",
+ "agent_label": "에이전트",
+ "choose_agent": "에이전트 선택",
+ "platform_label": "플랫폼",
+ "region_label": "지역",
+ "method_label": "연결 방식",
+ "continue": "계속",
+ "feishu": "Feishu(중국)",
+ "lark": "Lark(국제)",
+ "setup_guide": "설정 가이드",
+ "connection_changed": "이 연결을 더 이상 사용할 수 없습니다. 닫고 다시 시도하세요.",
+ "connect_failed": "봇을 연결할 수 없습니다.",
+ "connect_success": "메시지 채널이 연결되었습니다.",
+ "disconnect_failed": "봇 연결을 해제할 수 없습니다.",
+ "disconnect_title": "메시지 채널 연결을 해제할까요?",
+ "disconnect_description": "이 에이전트는 {{platform}}의 메시지를 더 이상 받지 않습니다.",
+ "agent_unavailable": "에이전트를 사용할 수 없음"
},
"mcp_usage": {
"agent_count_other": "에이전트 {{count}}개가 사용 중",
diff --git a/packages/views/locales/ru/agents.json b/packages/views/locales/ru/agents.json
index db359632d0..53fc144ff0 100644
--- a/packages/views/locales/ru/agents.json
+++ b/packages/views/locales/ru/agents.json
@@ -790,7 +790,7 @@
"add_dialog_confirm_many": "Добавить навыков: {{count}}"
},
"integrations": {
- "members_note": "Управлять этим подключением могут только владельцы и администраторы рабочего пространства. Просмотреть подключённых ботов можно в настройках → Интеграции."
+ "members_note": "Просматривайте каналы сообщений и управляйте ими на странице агента."
},
"activity": {
"status": {
diff --git a/packages/views/locales/ru/settings.json b/packages/views/locales/ru/settings.json
index 97897c9844..60d1557dc4 100644
--- a/packages/views/locales/ru/settings.json
+++ b/packages/views/locales/ru/settings.json
@@ -1647,7 +1647,42 @@
"github_actions": "GitHub Actions"
},
"channels": {
- "breadcrumb": "Хлебные крошки"
+ "breadcrumb": "Хлебные крошки",
+ "add": "Добавить канал сообщений",
+ "connect": "Подключить",
+ "disconnect": "Отключить",
+ "open": "Открыть",
+ "normal": "Подключено",
+ "waiting_message": "Ожидание первого сообщения",
+ "disconnected": "Отключено",
+ "find_me": "Найти меня в {{platform}}",
+ "manage": "Управление {{platform}}",
+ "last_message": "Последнее сообщение: {{time}}",
+ "ask_admin": "Обратитесь к администратору",
+ "unavailable": "Подключение недоступно",
+ "server_unavailable": "Не включено на сервере: {{platforms}}",
+ "permissions_title": "Кто может подключать",
+ "owner_or_admin": "Владелец агента или администратор пространства",
+ "admin_only": "Только администраторы пространства",
+ "connect_title": "Подключить канал сообщений",
+ "choose_description": "Выберите агента и платформу.",
+ "authorize_description": "Подключить {{agent}} к {{platform}}.",
+ "agent_label": "Агент",
+ "choose_agent": "Выберите агента",
+ "platform_label": "Платформа",
+ "region_label": "Регион",
+ "method_label": "Способ подключения",
+ "continue": "Продолжить",
+ "feishu": "Feishu (Китай)",
+ "lark": "Lark (международный)",
+ "setup_guide": "Руководство по настройке",
+ "connection_changed": "Это подключение больше недоступно. Закройте окно и повторите попытку.",
+ "connect_failed": "Не удалось подключить бота.",
+ "connect_success": "Канал сообщений подключён.",
+ "disconnect_failed": "Не удалось отключить бота.",
+ "disconnect_title": "Отключить канал сообщений?",
+ "disconnect_description": "Этот агент перестанет получать сообщения из {{platform}}.",
+ "agent_unavailable": "Агент недоступен"
},
"mcp_usage": {
"agent_count_one": "Используется {{count}} агентом",
diff --git a/packages/views/locales/zh-Hans/agents.json b/packages/views/locales/zh-Hans/agents.json
index b4236155cc..bee7a14668 100644
--- a/packages/views/locales/zh-Hans/agents.json
+++ b/packages/views/locales/zh-Hans/agents.json
@@ -733,7 +733,7 @@
"add_failed_toast": "添加 skill 失败"
},
"integrations": {
- "members_note": "只有工作区的所有者和管理员可以管理此连接。你可以在\"设置 → 集成\"中查看已连接的 Bot。"
+ "members_note": "在智能体主页查看和管理消息渠道。"
},
"activity": {
"status": {
diff --git a/packages/views/locales/zh-Hans/settings.json b/packages/views/locales/zh-Hans/settings.json
index 416ea3edcc..dad0b88d87 100644
--- a/packages/views/locales/zh-Hans/settings.json
+++ b/packages/views/locales/zh-Hans/settings.json
@@ -1603,7 +1603,42 @@
"github_actions": "GitHub 操作"
},
"channels": {
- "breadcrumb": "路径"
+ "breadcrumb": "路径",
+ "add": "添加消息渠道",
+ "connect": "连接",
+ "disconnect": "断开连接",
+ "open": "打开",
+ "normal": "正常",
+ "waiting_message": "等待第一条消息",
+ "disconnected": "已断开",
+ "find_me": "在 {{platform}} 中找我",
+ "manage": "管理 {{platform}}",
+ "last_message": "最近消息:{{time}}",
+ "ask_admin": "找管理员",
+ "unavailable": "暂不可连接",
+ "server_unavailable": "服务器尚未启用:{{platforms}}",
+ "permissions_title": "谁可以连接",
+ "owner_or_admin": "智能体所有者或工作区管理员",
+ "admin_only": "仅工作区管理员",
+ "connect_title": "连接消息渠道",
+ "choose_description": "选择智能体和平台。",
+ "authorize_description": "将 {{agent}} 连接到 {{platform}}。",
+ "agent_label": "智能体",
+ "choose_agent": "选择智能体",
+ "platform_label": "平台",
+ "region_label": "区域",
+ "method_label": "连接方式",
+ "continue": "继续",
+ "feishu": "飞书(中国)",
+ "lark": "Lark(国际)",
+ "setup_guide": "配置指南",
+ "connection_changed": "此连接已不可用。关闭后重试。",
+ "connect_failed": "无法连接机器人。",
+ "connect_success": "消息渠道已连接。",
+ "disconnect_failed": "无法断开机器人连接。",
+ "disconnect_title": "断开消息渠道?",
+ "disconnect_description": "此智能体将不再接收来自 {{platform}} 的消息。",
+ "agent_unavailable": "智能体已不可用"
},
"mcp_usage": {
"agent_count_other": "已分配给 {{count}} 个智能体",
diff --git a/packages/views/locales/zh-Hant/agents.json b/packages/views/locales/zh-Hant/agents.json
index 89f44ff2c0..59a4a12d38 100644
--- a/packages/views/locales/zh-Hant/agents.json
+++ b/packages/views/locales/zh-Hant/agents.json
@@ -733,7 +733,7 @@
"add_failed_toast": "新增 skill 失敗"
},
"integrations": {
- "members_note": "只有工作區的所有者和管理員可以管理此連線。你可以在\"設定 → 整合\"中檢視已連線的 Bot。"
+ "members_note": "在 AI 代理首頁查看和管理訊息管道。"
},
"activity": {
"status": {
diff --git a/packages/views/locales/zh-Hant/settings.json b/packages/views/locales/zh-Hant/settings.json
index 97c48f2036..91cd97cefb 100644
--- a/packages/views/locales/zh-Hant/settings.json
+++ b/packages/views/locales/zh-Hant/settings.json
@@ -1603,7 +1603,42 @@
"github_actions": "GitHub 操作"
},
"channels": {
- "breadcrumb": "路徑"
+ "breadcrumb": "路徑",
+ "add": "新增訊息管道",
+ "connect": "連接",
+ "disconnect": "中斷連接",
+ "open": "開啟",
+ "normal": "正常",
+ "waiting_message": "等待第一則訊息",
+ "disconnected": "已中斷",
+ "find_me": "在 {{platform}} 中找我",
+ "manage": "管理 {{platform}}",
+ "last_message": "最近訊息:{{time}}",
+ "ask_admin": "請找管理員",
+ "unavailable": "暫時無法連接",
+ "server_unavailable": "伺服器尚未啟用:{{platforms}}",
+ "permissions_title": "誰可以連接",
+ "owner_or_admin": "AI 代理擁有者或工作區管理員",
+ "admin_only": "僅工作區管理員",
+ "connect_title": "連接訊息管道",
+ "choose_description": "選擇 AI 代理和平台。",
+ "authorize_description": "將 {{agent}} 連接到 {{platform}}。",
+ "agent_label": "AI 代理",
+ "choose_agent": "選擇 AI 代理",
+ "platform_label": "平台",
+ "region_label": "地區",
+ "method_label": "連接方式",
+ "continue": "繼續",
+ "feishu": "飛書(中國)",
+ "lark": "Lark(國際)",
+ "setup_guide": "設定指南",
+ "connection_changed": "此連接已無法使用。請關閉後重試。",
+ "connect_failed": "無法連接機器人。",
+ "connect_success": "訊息管道已連接。",
+ "disconnect_failed": "無法中斷機器人連接。",
+ "disconnect_title": "中斷訊息管道?",
+ "disconnect_description": "此 AI 代理將不再接收來自 {{platform}} 的訊息。",
+ "agent_unavailable": "AI 代理已無法使用"
},
"mcp_usage": {
"agent_count_other": "已分配給 {{count}} 個 AI 代理",
diff --git a/packages/views/package.json b/packages/views/package.json
index 2d4ba1c38b..8ab82da886 100644
--- a/packages/views/package.json
+++ b/packages/views/package.json
@@ -62,7 +62,6 @@
"./chat": "./chat/index.ts",
"./chat/floating-chat": "./chat/floating-chat.tsx",
"./settings": "./settings/index.ts",
- "./settings/lark-tab": "./settings/components/lark-tab.tsx",
"./lark": "./lark/index.ts",
"./slack": "./slack/index.ts",
"./dingtalk": "./dingtalk/index.ts",
diff --git a/packages/views/settings/components/channel-connect-dialog.tsx b/packages/views/settings/components/channel-connect-dialog.tsx
new file mode 100644
index 0000000000..5b89bcd90c
--- /dev/null
+++ b/packages/views/settings/components/channel-connect-dialog.tsx
@@ -0,0 +1,488 @@
+"use client";
+
+import { useState } from "react";
+import { useQueryClient } from "@tanstack/react-query";
+import { toast } from "sonner";
+import type { Agent } from "@multica/core/types";
+import { api, errorCode } from "@multica/core/api";
+import { Button } from "@multica/ui/components/ui/button";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from "@multica/ui/components/ui/dialog";
+import { Input } from "@multica/ui/components/ui/input";
+import { Label } from "@multica/ui/components/ui/label";
+import { useT } from "../../i18n";
+import { docsLocalePrefix } from "../../common/docs-locale";
+import { openExternal } from "../../platform";
+import { IntegrationChannelIcon } from "./integration-channel-icon";
+import {
+ CHANNEL_INTEGRATIONS,
+ type ChannelIntegration,
+} from "./settings-navigation";
+import { useMessagingChannels } from "./use-messaging-channels";
+import { LarkChannelAuthorization } from "./lark-channel-authorization";
+import { WecomChannelAuthorization } from "./wecom-channel-authorization";
+
+export function ChannelConnectDialog({
+ agents,
+ initialAgent,
+ initialChannel,
+ open,
+ onOpenChange,
+}: {
+ agents: Agent[];
+ initialAgent?: Agent;
+ initialChannel?: ChannelIntegration;
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+}) {
+ const { t } = useT("settings");
+ const [busy, setBusy] = useState(false);
+ return (
+ <Dialog
+ open={open}
+ onOpenChange={(next) => {
+ if (!busy) onOpenChange(next);
+ }}
+ >
+ <DialogContent className="sm:max-w-lg" showCloseButton={!busy}>
+ <DialogHeader>
+ <DialogTitle>{t(($) => $.channels.connect_title)}</DialogTitle>
+ </DialogHeader>
+ {open ? (
+ <ChannelConnectSteps
+ agents={agents}
+ initialAgent={initialAgent}
+ initialChannel={initialChannel}
+ onClose={() => onOpenChange(false)}
+ onBusyChange={setBusy}
+ />
+ ) : null}
+ </DialogContent>
+ </Dialog>
+ );
+}
+
+function ChannelConnectSteps({
+ agents,
+ initialAgent,
+ initialChannel,
+ onClose,
+ onBusyChange,
+}: {
+ agents: Agent[];
+ initialAgent?: Agent;
+ initialChannel?: ChannelIntegration;
+ onClose: () => void;
+ onBusyChange: (busy: boolean) => void;
+}) {
+ const { t, i18n } = useT("settings");
+ const { wsId, queries, connections, isAdmin, canManage, available } =
+ useMessagingChannels();
+ const [agentId, setAgentId] = useState(initialAgent?.id ?? "");
+ const [channel, setChannel] = useState<ChannelIntegration | undefined>(
+ initialChannel,
+ );
+ const [authorizing, setAuthorizing] = useState(false);
+ const [wecomMethod, setWecomMethod] = useState<"scan" | "credentials">(
+ "scan",
+ );
+ const agent =
+ initialAgent ?? agents.find((candidate) => candidate.id === agentId);
+ const connected = (id: ChannelIntegration) =>
+ connections.some(
+ (entry) =>
+ entry.channel === id && entry.installation.agent_id === agent?.id,
+ );
+ const allowed =
+ !!agent &&
+ !!channel &&
+ canManage(channel, agent) &&
+ available(channel) &&
+ !connected(channel) &&
+ !agent.archived_at;
+ const scanWecom =
+ channel === "wecom" &&
+ queries.wecom.data?.scan_install_supported === true &&
+ wecomMethod === "scan";
+
+ return (
+ <>
+ <DialogDescription>
+ {authorizing && agent && channel
+ ? t(($) => $.channels.authorize_description, {
+ agent: agent.name,
+ platform:
+ channel === "lark"
+ ? t(($) => $.lark.region_feishu)
+ : t(($) => $[channel].section_title),
+ })
+ : t(($) => $.channels.choose_description)}
+ </DialogDescription>
+ {!authorizing ? (
+ <>
+ <div className="space-y-4">
+ <div className="space-y-1.5">
+ <Label htmlFor="channel-agent">
+ {t(($) => $.channels.agent_label)}
+ </Label>
+ {initialAgent ? (
+ <p className="text-body">{initialAgent.name}</p>
+ ) : (
+ <select
+ id="channel-agent"
+ className="h-9 w-full rounded-md border bg-background px-3 text-body"
+ value={agentId}
+ onChange={(event) => setAgentId(event.target.value)}
+ >
+ <option value="">{t(($) => $.channels.choose_agent)}</option>
+ {agents
+ .filter(
+ (candidate) =>
+ !candidate.archived_at &&
+ (isAdmin ||
+ CHANNEL_INTEGRATIONS.some((id) =>
+ canManage(id, candidate),
+ )),
+ )
+ .map((candidate) => (
+ <option key={candidate.id} value={candidate.id}>
+ {candidate.name}
+ </option>
+ ))}
+ </select>
+ )}
+ </div>
+ <div
+ className="space-y-1.5"
+ role="group"
+ aria-label={t(($) => $.channels.platform_label)}
+ >
+ <Label>{t(($) => $.channels.platform_label)}</Label>
+ {CHANNEL_INTEGRATIONS.filter(
+ (id) => queries[id].data?.configured || isAdmin,
+ )
+ .filter((id) => !connected(id))
+ .map((id) => {
+ const permitted = !!agent && canManage(id, agent);
+ return (
+ <Button
+ key={id}
+ variant={channel === id ? "secondary" : "outline"}
+ className="w-full justify-start"
+ aria-pressed={channel === id}
+ disabled={!available(id) || (!!agent && !permitted)}
+ onClick={() => setChannel(id)}
+ >
+ <IntegrationChannelIcon channel={id} />
+ <span>
+ {id === "lark"
+ ? t(($) => $.lark.region_feishu)
+ : t(($) => $[id].section_title)}
+ </span>{" "}
+ <span className="ml-auto text-caption text-muted-foreground">
+ {queries[id].isError
+ ? t(($) => $.integrations.status_unknown)
+ : !available(id)
+ ? t(($) => $.channels.unavailable)
+ : agent && !permitted
+ ? t(($) => $.channels.ask_admin)
+ : null}
+ </span>
+ </Button>
+ );
+ })}
+ </div>
+ {channel === "wecom" &&
+ queries.wecom.data?.scan_install_supported ? (
+ <div className="space-y-1.5">
+ <Label htmlFor="channel-method">
+ {t(($) => $.channels.method_label)}
+ </Label>
+ <select
+ id="channel-method"
+ value={wecomMethod}
+ onChange={(event) =>
+ setWecomMethod(
+ event.target.value === "scan" ? "scan" : "credentials",
+ )
+ }
+ className="h-9 w-full rounded-md border bg-background px-3 text-body"
+ >
+ <option value="scan">
+ {t(($) => $.wecom.scan_option_title)}
+ </option>
+ <option value="credentials">
+ {t(($) => $.wecom.byo_dialog_title)}
+ </option>
+ </select>
+ </div>
+ ) : null}
+ </div>
+ <DialogFooter>
+ <Button variant="outline" onClick={onClose}>
+ {t(($) => $.lark.install_close)}
+ </Button>
+ <Button disabled={!allowed} onClick={() => setAuthorizing(true)}>
+ {t(($) => $.channels.continue)}
+ </Button>
+ </DialogFooter>
+ </>
+ ) : !agent ||
+ !channel ||
+ !canManage(channel, agent) ||
+ !available(channel) ? (
+ <>
+ <p role="alert" className="text-body text-muted-foreground">
+ {t(($) => $.channels.connection_changed)}
+ </p>
+ <DialogFooter>
+ <Button variant="outline" onClick={onClose}>
+ {t(($) => $.lark.install_close)}
+ </Button>
+ </DialogFooter>
+ </>
+ ) : (
+ <>
+ <Button
+ variant="link"
+ className="w-fit p-0"
+ onClick={() =>
+ openExternal(
+ `https://multica.ai/docs${docsLocalePrefix(i18n.language)}/${channel === "lark" ? "lark" : channel}-bot-integration`,
+ )
+ }
+ >
+ {t(($) => $.channels.setup_guide)}
+ </Button>
+ {channel === "lark" ? (
+ <LarkChannelAuthorization
+ wsId={wsId}
+ agentId={agent.id}
+ // International installs remain disabled until the persistence
+ // issue is fixed; existing Lark bots stay manageable.
+ region="feishu"
+ onClose={onClose}
+ />
+ ) : scanWecom ? (
+ <WecomChannelAuthorization
+ wsId={wsId}
+ agentId={agent.id}
+ onClose={onClose}
+ />
+ ) : (
+ <ChannelCredentials
+ channel={channel}
+ wsId={wsId}
+ agentId={agent.id}
+ onClose={onClose}
+ onBusyChange={onBusyChange}
+ />
+ )}
+ </>
+ )}
+ </>
+ );
+}
+
+function ChannelCredentials({
+ channel,
+ wsId,
+ agentId,
+ onClose,
+ onBusyChange,
+}: {
+ channel: Exclude<ChannelIntegration, "lark">;
+ wsId: string;
+ agentId: string;
+ onClose: () => void;
+ onBusyChange: (busy: boolean) => void;
+}) {
+ const { t } = useT("settings");
+ const qc = useQueryClient();
+ const [values, setValues] = useState({
+ token: "",
+ appToken: "",
+ clientId: "",
+ clientSecret: "",
+ botId: "",
+ secret: "",
+ botName: "",
+ });
+ const [submitting, setSubmitting] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+ const fields: {
+ key: keyof typeof values;
+ label: string;
+ secret?: boolean;
+ optional?: boolean;
+ }[] =
+ channel === "slack"
+ ? [
+ {
+ key: "token",
+ label: t(($) => $.slack.byo_bot_token_label),
+ secret: true,
+ },
+ {
+ key: "appToken",
+ label: t(($) => $.slack.byo_app_token_label),
+ secret: true,
+ },
+ ]
+ : channel === "dingtalk"
+ ? [
+ {
+ key: "clientId",
+ label: t(($) => $.dingtalk.byo_appkey_label),
+ secret: true,
+ },
+ {
+ key: "clientSecret",
+ label: t(($) => $.dingtalk.byo_appsecret_label),
+ secret: true,
+ },
+ ]
+ : channel === "wecom"
+ ? [
+ { key: "botId", label: t(($) => $.wecom.byo_bot_id_label) },
+ {
+ key: "secret",
+ label: t(($) => $.wecom.byo_secret_label),
+ secret: true,
+ },
+ {
+ key: "botName",
+ label: t(($) => $.wecom.byo_bot_name_label),
+ optional: true,
+ },
+ ]
+ : [
+ {
+ key: "token",
+ label: t(($) => $.telegram.bot_token_label),
+ secret: true,
+ },
+ ];
+
+ const submit = async (event: React.FormEvent) => {
+ event.preventDefault();
+ if (submitting) return;
+ setSubmitting(true);
+ onBusyChange(true);
+ setError(null);
+ try {
+ const v = Object.fromEntries(
+ Object.entries(values).map(([key, value]) => [key, value.trim()]),
+ ) as typeof values;
+ const installation =
+ channel === "slack"
+ ? await api.registerSlackBYO(wsId, agentId, {
+ bot_token: v.token,
+ app_token: v.appToken,
+ })
+ : channel === "dingtalk"
+ ? await api.registerDingTalkBYO(wsId, agentId, {
+ client_id: v.clientId,
+ client_secret: v.clientSecret,
+ })
+ : channel === "wecom"
+ ? await api.registerWecomBYO(wsId, agentId, {
+ bot_id: v.botId,
+ secret: v.secret,
+ bot_name: v.botName || undefined,
+ })
+ : await api.registerTelegramBot(wsId, agentId, {
+ bot_token: v.token,
+ });
+ if (!installation.id || installation.status !== "active")
+ throw new Error(t(($) => $.channels.connect_failed));
+ await qc.invalidateQueries({
+ queryKey: [channel, wsId, "installations"],
+ });
+ toast.success(t(($) => $.channels.connect_success));
+ onClose();
+ } catch (reason) {
+ const code = errorCode(reason);
+ const wecomErrors: Record<string, string> = {
+ wecom_bot_owned_by_same_workspace: t(
+ ($) => $.wecom.byo_conflict_same_workspace,
+ ),
+ wecom_bot_owned_by_archived_agent: t(
+ ($) => $.wecom.byo_conflict_archived_agent,
+ ),
+ wecom_bot_owned_by_another_workspace: t(
+ ($) => $.wecom.byo_conflict_other_workspace,
+ ),
+ wecom_install_rejected: t(($) => $.wecom.byo_rejected),
+ wecom_credentials_rejected: t(($) => $.wecom.byo_credentials_rejected),
+ wecom_credentials_unverifiable: t(
+ ($) => $.wecom.byo_credentials_unverifiable,
+ ),
+ wecom_install_failed: t(($) => $.wecom.byo_install_failed),
+ };
+ setError(
+ (code && wecomErrors[code]) ||
+ (reason instanceof Error
+ ? reason.message
+ : t(($) => $.channels.connect_failed)),
+ );
+ } finally {
+ setSubmitting(false);
+ onBusyChange(false);
+ }
+ };
+
+ return (
+ <form onSubmit={submit} className="grid gap-4" aria-busy={submitting}>
+ {fields.map((field) => (
+ <div key={field.key} className="space-y-1.5">
+ <Label htmlFor={`channel-${field.key}`}>{field.label}</Label>
+ <Input
+ id={`channel-${field.key}`}
+ type={field.secret ? "password" : "text"}
+ autoComplete="off"
+ spellCheck={false}
+ required={!field.optional}
+ disabled={submitting}
+ value={values[field.key]}
+ onChange={(event) =>
+ setValues((old) => ({ ...old, [field.key]: event.target.value }))
+ }
+ />
+ </div>
+ ))}
+ {error ? (
+ <p role="alert" className="text-caption text-destructive">
+ {error}
+ </p>
+ ) : null}
+ <DialogFooter>
+ <Button
+ type="button"
+ variant="outline"
+ disabled={submitting}
+ onClick={onClose}
+ >
+ {t(($) => $.lark.install_close)}
+ </Button>
+ <Button
+ type="submit"
+ disabled={
+ submitting ||
+ fields.some((field) => !field.optional && !values[field.key].trim())
+ }
+ >
+ {submitting
+ ? t(($) => $.integrations.status_loading)
+ : t(($) => $.channels.connect)}
+ </Button>
+ </DialogFooter>
+ </form>
+ );
+}
diff --git a/packages/views/settings/components/channel-disconnect-dialog.tsx b/packages/views/settings/components/channel-disconnect-dialog.tsx
new file mode 100644
index 0000000000..9e0577805f
--- /dev/null
+++ b/packages/views/settings/components/channel-disconnect-dialog.tsx
@@ -0,0 +1,88 @@
+"use client";
+
+import { useState } from "react";
+import { useQueryClient } from "@tanstack/react-query";
+import { toast } from "sonner";
+import { api } from "@multica/core/api";
+import {
+ AlertDialog,
+ AlertDialogAction,
+ AlertDialogCancel,
+ AlertDialogContent,
+ AlertDialogDescription,
+ AlertDialogFooter,
+ AlertDialogHeader,
+ AlertDialogTitle,
+} from "@multica/ui/components/ui/alert-dialog";
+import type { ChannelConnection } from "./use-messaging-channels";
+import { useT } from "../../i18n";
+
+export function ChannelDisconnectDialog({
+ connection,
+ open,
+ onOpenChange,
+}: {
+ connection: ChannelConnection;
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+}) {
+ const { t } = useT("settings");
+ const qc = useQueryClient();
+ const { channel, installation } = connection;
+ const [disconnecting, setDisconnecting] = useState(false);
+ const disconnect = async () => {
+ if (disconnecting) return;
+ setDisconnecting(true);
+ try {
+ const revoke = {
+ lark: api.deleteLarkInstallation.bind(api),
+ slack: api.deleteSlackInstallation.bind(api),
+ dingtalk: api.deleteDingTalkInstallation.bind(api),
+ wecom: api.deleteWecomInstallation.bind(api),
+ telegram: api.deleteTelegramInstallation.bind(api),
+ }[channel];
+ await revoke(installation.workspace_id, installation.id);
+ await qc.invalidateQueries({
+ queryKey: [channel, installation.workspace_id],
+ });
+ onOpenChange(false);
+ } catch (error) {
+ toast.error(
+ error instanceof Error
+ ? error.message
+ : t(($) => $.channels.disconnect_failed),
+ );
+ } finally {
+ setDisconnecting(false);
+ }
+ };
+ return (
+ <AlertDialog
+ open={open}
+ onOpenChange={(next) => {
+ if (!disconnecting) onOpenChange(next);
+ }}
+ >
+ <AlertDialogContent>
+ <AlertDialogHeader>
+ <AlertDialogTitle>
+ {t(($) => $.channels.disconnect_title)}
+ </AlertDialogTitle>
+ <AlertDialogDescription>
+ {t(($) => $.channels.disconnect_description, {
+ platform: t(($) => $[channel].section_title),
+ })}
+ </AlertDialogDescription>
+ </AlertDialogHeader>
+ <AlertDialogFooter>
+ <AlertDialogCancel disabled={disconnecting}>
+ {t(($) => $.lark.install_close)}
+ </AlertDialogCancel>
+ <AlertDialogAction disabled={disconnecting} onClick={disconnect}>
+ {t(($) => $.channels.disconnect)}
+ </AlertDialogAction>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
+ );
+}
diff --git a/packages/views/settings/components/channels-tab.test.tsx b/packages/views/settings/components/channels-tab.test.tsx
deleted file mode 100644
index da338fdda0..0000000000
--- a/packages/views/settings/components/channels-tab.test.tsx
+++ /dev/null
@@ -1,146 +0,0 @@
-import { beforeEach, describe, expect, it, vi } from "vitest";
-import { fireEvent, screen } from "@testing-library/react";
-import { renderWithI18n } from "../../test/i18n";
-
-const state = vi.hoisted(() => ({
- search: "",
- connectionError: false,
- pending: false,
- // The IM channels keep revoked rows for audit, so the fixture carries a real
- // status — a row without one is not evidence of a live connection (#8496).
- installationStatus: "active" as string,
- larkInstallations: null as { status: string; first_message_received_at?: string }[] | null,
- push: vi.fn(),
-}));
-vi.mock("../../navigation/context", async (importOriginal) => ({
- ...(await importOriginal<typeof import("../../navigation/context")>()),
- useNavigation: () => ({
- pathname: "/acme/settings",
- searchParams: new URLSearchParams(state.search),
- push: state.push,
- }),
-}));
-vi.mock("@multica/core/hooks", () => ({ useWorkspaceId: () => "ws-1" }));
-vi.mock("@multica/core/paths", () => ({
- useCurrentWorkspace: () => ({ id: "ws-1", name: "Acme" }),
-}));
-vi.mock("@multica/core/permissions", () => ({
- useCurrentMember: () => ({ member: { role: "admin" } }),
-}));
-vi.mock("@tanstack/react-query", () => ({
- queryOptions: <T,>(opts: T) => opts,
- useQuery: (opts: { queryKey?: readonly unknown[]; select?: (data: unknown) => unknown }) => ({
- data: opts.select?.({
- installations: opts.queryKey?.[0] === "lark" && state.larkInstallations
- ? state.larkInstallations
- : [{ id: "one", status: state.installationStatus }],
- }),
- isPending: state.pending,
- isError: state.connectionError,
- }),
-}));
-vi.mock("./lark-tab", () => ({ LarkTab: () => <div>Lark detail</div> }));
-vi.mock("./slack-tab", () => ({ SlackTab: () => <div>Slack detail</div> }));
-vi.mock("./dingtalk-tab", () => ({ DingTalkTab: () => <div>DingTalk detail</div> }));
-vi.mock("./wecom-tab", () => ({ WecomTab: () => <div>WeCom detail</div> }));
-vi.mock("./telegram-tab", () => ({ TelegramTab: () => <div>Telegram detail</div> }));
-
-import { ChannelsTab } from "./channels-tab";
-
-beforeEach(() => {
- state.search = "tab=channels";
- state.connectionError = false;
- state.pending = false;
- state.installationStatus = "active";
- state.larkInstallations = null;
- state.push.mockClear();
-});
-
-describe("ChannelsTab", () => {
- it("lists only messaging channels, each with its own mark and status", () => {
- renderWithI18n(<ChannelsTab />);
-
- expect(screen.getByRole("link", { name: /Slack Connected/ })).toBeInTheDocument();
- expect(screen.queryByRole("link", { name: /GitHub/ })).toBeNull();
- expect(screen.queryByRole("link", { name: /Composio/ })).toBeNull();
- expect(screen.queryByText("Slack detail")).toBeNull();
- const shapes = ["lark", "slack", "dingtalk", "wecom", "telegram"].map(
- (channel) => screen.getByTestId(`integration-channel-icon-${channel}`).innerHTML,
- );
- expect(new Set(shapes).size).toBe(5);
-
- fireEvent.click(screen.getByRole("link", { name: /Slack Connected/ }));
- expect(state.push).toHaveBeenCalledWith("/acme/settings?tab=channels&integration=slack");
- });
-
- it("does not report a revoked bot as connected", () => {
- state.installationStatus = "revoked";
- renderWithI18n(<ChannelsTab />);
- expect(screen.getByRole("link", { name: /Slack Not connected/ })).toBeInTheDocument();
- });
-
- it.each([
- ["pending", "Checking..."],
- ["error", "Status unavailable"],
- ] as const)("never reports a %s read as disconnected", (kind, label) => {
- if (kind === "pending") state.pending = true;
- else state.connectionError = true;
- renderWithI18n(<ChannelsTab />);
- expect(screen.getByRole("link", { name: new RegExp(`Slack ${label}`) })).toBeInTheDocument();
- });
-
- it("opens one channel with a breadcrumb back to the list", () => {
- state.search = "tab=channels&integration=slack";
- renderWithI18n(<ChannelsTab />);
-
- expect(screen.getByText("Slack detail")).toBeInTheDocument();
- expect(screen.queryByText("Lark detail")).toBeNull();
- expect(screen.getByRole("link", { name: "Messaging" })).toHaveAttribute(
- "href",
- "/acme/settings?tab=channels",
- );
- });
-
- it("opens the retired Lark bookmark on the Lark page", () => {
- state.search = "tab=lark";
- renderWithI18n(<ChannelsTab />);
- expect(screen.getByText("Lark detail")).toBeInTheDocument();
- });
-});
-
-
-it("labels an installed Feishu bot as bound without claiming connectivity", () => {
- renderWithI18n(<ChannelsTab />);
- expect(screen.getByRole("link", { name: /Lark Bound/ })).toBeInTheDocument();
- expect(screen.queryByRole("link", { name: /Lark Connected/ })).toBeNull();
-});
-
-
-it("updates the Lark overview from pending to verified and back on rebind/revoke", () => {
- state.larkInstallations = [{ status: "active" }];
- const { rerender } = renderWithI18n(<ChannelsTab />);
- const status = () => screen.getByRole("link", { name: /^Lark / });
- expect(status()).toHaveTextContent("Bound");
- expect(status().querySelector(".bg-success")).toBeNull();
-
- state.larkInstallations = [{ status: "active" }, { status: "active", first_message_received_at: "2026-10-30T00:00:00Z" }];
- rerender(<ChannelsTab />);
- expect(status()).toHaveTextContent("Message reception verified");
- expect(status().querySelector(".bg-success")).not.toBeNull();
-
- state.larkInstallations[1]!.first_message_received_at = undefined;
- rerender(<ChannelsTab />);
- expect(status()).toHaveTextContent("Bound");
- expect(status().querySelector(".bg-success")).toBeNull();
-
- state.larkInstallations[1]!.first_message_received_at = "2026-10-30T00:00:00Z";
- state.larkInstallations[1]!.status = "revoked";
- rerender(<ChannelsTab />);
- expect(status()).toHaveTextContent("Bound");
- expect(status().querySelector(".bg-success")).toBeNull();
-
- state.larkInstallations = [{ status: "revoked", first_message_received_at: "2026-10-30T00:00:00Z" }];
- rerender(<ChannelsTab />);
- expect(status()).toHaveTextContent("Not connected");
- expect(status().querySelector(".bg-success")).toBeNull();
-});
diff --git a/packages/views/settings/components/channels-tab.tsx b/packages/views/settings/components/channels-tab.tsx
index 3e781ac36e..703a156d25 100644
--- a/packages/views/settings/components/channels-tab.tsx
+++ b/packages/views/settings/components/channels-tab.tsx
@@ -1,236 +1,212 @@
"use client";
-import type { ReactNode } from "react";
-import { ChevronRight } from "@multica/ui/icons";
+import { useEffect, useState } from "react";
import { useQuery } from "@tanstack/react-query";
-import { useWorkspaceId } from "@multica/core/hooks";
-import { useCurrentMember } from "@multica/core/permissions";
-import { larkInstallationsOptions } from "@multica/core/lark";
-import { slackInstallationsOptions } from "@multica/core/slack";
-import { dingtalkInstallationsOptions } from "@multica/core/dingtalk";
-import { wecomInstallationsOptions } from "@multica/core/wecom";
-import { telegramInstallationsOptions } from "@multica/core/telegram";
-import { cn } from "@multica/ui/lib/utils";
+import { agentListOptions } from "@multica/core/workspace/queries";
+import { useWorkspacePaths } from "@multica/core/paths";
+import { Button } from "@multica/ui/components/ui/button";
+import { ActorAvatar } from "../../common/actor-avatar";
import { AppLink, useNavigation } from "../../navigation";
import { useT } from "../../i18n";
-import { LarkTab } from "./lark-tab";
-import { SlackTab } from "./slack-tab";
-import { DingTalkTab } from "./dingtalk-tab";
-import { WecomTab } from "./wecom-tab";
-import { TelegramTab } from "./telegram-tab";
-import { SettingsCard, SettingsTab } from "./settings-layout";
+import { ChannelConnectDialog } from "./channel-connect-dialog";
+import { ChannelDisconnectDialog } from "./channel-disconnect-dialog";
import { IntegrationChannelIcon } from "./integration-channel-icon";
+import { SettingsCard, SettingsSection, SettingsTab } from "./settings-layout";
import {
- resolveSettingsLocation,
- settingsHref,
+ CHANNEL_INTEGRATIONS,
type ChannelIntegration,
+ settingsHref,
} from "./settings-navigation";
+import {
+ useMessagingChannels,
+ type ChannelConnection,
+} from "./use-messaging-channels";
-interface ConnectionState {
- data?: boolean;
- isPending: boolean;
- isError: boolean;
-}
-
-interface ChannelEntry {
- id: ChannelIntegration;
- label: string;
- description: string;
- content: ReactNode;
- state: ConnectionState;
- boundLabel?: string;
- connectedLabel?: string;
-}
-
-// The IM channels soft-revoke: the row survives with status 'revoked', so a row
-// count never falls back to zero and would report a torn-down bot as connected
-// forever (#8496).
-const hasActiveInstallation = (data: {
- installations?: { status: string }[];
-}) => data.installations?.some((inst) => inst.status === "active") ?? false;
-
-/**
- * Messaging channels: a directory of the chat apps agents can be reached
- * from, each opening its own detail page. Code hosting lives on the Code page
- * and account-level app connections on Connected apps.
- */
export function ChannelsTab() {
const { t } = useT("settings");
const navigation = useNavigation();
- const wsId = useWorkspaceId();
- const { member } = useCurrentMember(wsId);
- const canView = !!wsId && !!member;
-
- // Reuse the detail pages' query caches. Never report a failed or pending
- // read as disconnected.
- const lark = useQuery({
- ...larkInstallationsOptions(wsId),
- enabled: canView,
- select: (data) => {
- const active = data.installations.filter((inst) => inst.status === "active");
- return {
- active: active.length > 0,
- verified: active.some((inst) => !!inst.first_message_received_at),
- };
- },
- });
- const slack = useQuery({
- ...slackInstallationsOptions(wsId),
- enabled: canView,
- select: hasActiveInstallation,
- });
- const dingtalk = useQuery({
- ...dingtalkInstallationsOptions(wsId),
- enabled: canView,
- select: hasActiveInstallation,
- });
- const wecom = useQuery({
- ...wecomInstallationsOptions(wsId),
- enabled: canView,
- select: hasActiveInstallation,
- });
- const telegram = useQuery({
- ...telegramInstallationsOptions(wsId),
- enabled: canView,
- select: hasActiveInstallation,
- });
- const channels: ChannelEntry[] = [
- {
- id: "lark",
- label: t(($) => $.lark.section_title),
- description: t(($) => $.lark.page_description),
- content: <LarkTab />,
- state: { ...lark, data: lark.data?.active },
- boundLabel: lark.data?.verified ? undefined : t(($) => $.lark.bound_label),
- connectedLabel: t(($) => $.lark.inbound_verified),
- },
- {
- id: "slack",
- label: t(($) => $.slack.section_title),
- description: t(($) => $.slack.page_description),
- content: <SlackTab />,
- state: slack,
- },
- {
- id: "dingtalk",
- label: t(($) => $.dingtalk.section_title),
- description: t(($) => $.dingtalk.page_description),
- content: <DingTalkTab />,
- state: dingtalk,
- },
- {
- id: "wecom",
- label: t(($) => $.wecom.section_title),
- description: t(($) => $.wecom.page_description),
- content: <WecomTab />,
- state: wecom,
- },
- {
- id: "telegram",
- label: t(($) => $.telegram.section_title),
- description: t(($) => $.telegram.page_description),
- content: <TelegramTab />,
- state: telegram,
- },
- ];
- const requested = resolveSettingsLocation(navigation.searchParams).integration;
- const selected = channels.find((channel) => channel.id === requested);
- const href = (integration?: string) =>
- settingsHref(navigation.pathname, navigation.searchParams, "channels", {
- integration,
- });
-
- if (selected) {
- return (
- <SettingsTab
- title={selected.label}
- description={selected.description}
- scope="workspace"
- breadcrumb={
- <nav
- aria-label={t(($) => $.channels.breadcrumb)}
- className="flex items-center gap-1.5 text-caption text-muted-foreground"
- >
- <AppLink
- href={href()}
- className="rounded-sm hover:text-foreground focus-visible:outline-2 focus-visible:outline-ring"
- >
- {t(($) => $.page.tabs.channels)}
- </AppLink>
- <ChevronRight aria-hidden="true" className="size-3" />
- <span aria-current="page" className="text-foreground">
- {selected.label}
- </span>
- </nav>
- }
- >
- {selected.content}
- </SettingsTab>
- );
- }
+ const paths = useWorkspacePaths();
+ const { wsId, queries, connections, isAdmin, available } =
+ useMessagingChannels();
+ const agentsQuery = useQuery(agentListOptions(wsId));
+ const agents = agentsQuery.data ?? [];
+ const [connecting, setConnecting] = useState<ChannelIntegration | null>(null);
+ const [disconnecting, setDisconnecting] = useState<ChannelConnection | null>(
+ null,
+ );
+ const legacyDetail = navigation.searchParams.get("integration");
+ useEffect(() => {
+ if (legacyDetail)
+ navigation.replace(
+ settingsHref(navigation.pathname, navigation.searchParams, "channels"),
+ );
+ }, [legacyDetail, navigation]);
return (
<SettingsTab title={t(($) => $.page.tabs.channels)} scope="workspace">
<SettingsCard>
- {channels.map((channel) => (
- <AppLink
- key={channel.id}
- href={href(channel.id)}
- className="group flex items-center gap-4 px-4 py-4 first:rounded-t-xl last:rounded-b-xl hover:bg-surface-hover focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-ring"
- >
- <span
- aria-hidden="true"
- className="flex size-10 shrink-0 items-center justify-center rounded-xl border border-surface-border bg-background text-foreground"
+ {CHANNEL_INTEGRATIONS.filter(
+ (id) =>
+ isAdmin ||
+ queries[id].data?.configured ||
+ queries[id].isPending ||
+ queries[id].isError,
+ ).map((id) => {
+ const query = queries[id];
+ const orphaned =
+ isAdmin && agentsQuery.isSuccess
+ ? connections.filter(
+ (entry) =>
+ entry.channel === id &&
+ !agents.some(
+ (agent) => agent.id === entry.installation.agent_id,
+ ),
+ )
+ : [];
+ const connectedAgents = agents.filter((agent) =>
+ connections.some(
+ (entry) =>
+ entry.channel === id &&
+ entry.installation.agent_id === agent.id,
+ ),
+ );
+ return (
+ <div
+ key={id}
+ className="flex flex-wrap items-center gap-3 px-4 py-4"
>
- <IntegrationChannelIcon channel={channel.id} />
- </span>
- <span className="min-w-0 flex-1">
- <span className="flex flex-wrap items-center gap-x-3 gap-y-1">
- <span className="text-body font-medium text-foreground">
- {channel.label}
- </span>{" "}
- <ConnectionBadge state={channel.state} boundLabel={channel.boundLabel} connectedLabel={channel.connectedLabel} />
- </span>
- <span className="mt-1 block text-caption leading-5 text-muted-foreground">
- {channel.description}
+ <IntegrationChannelIcon channel={id} />
+ <span className="w-24 shrink-0 text-body font-medium">
+ {t(($) => $[id].section_title)}
</span>
- </span>
- <ChevronRight
- className="size-4 shrink-0 text-muted-foreground group-hover:text-foreground"
- aria-hidden="true"
- />
- </AppLink>
- ))}
+ <div className="flex min-w-0 flex-1 flex-wrap items-center gap-2">
+ {query.isError || agentsQuery.isError ? (
+ <span
+ role="alert"
+ className="text-caption text-muted-foreground"
+ >
+ {t(($) => $.integrations.status_unknown)}
+ </span>
+ ) : query.isPending || agentsQuery.isPending ? (
+ <span className="text-caption text-muted-foreground">
+ {t(($) => $.integrations.status_loading)}
+ </span>
+ ) : connectedAgents.length || orphaned.length ? (
+ connectedAgents.map((agent) => (
+ <AppLink
+ key={agent.id}
+ href={`${paths.agentDetail(agent.id)}?view=channels`}
+ className="flex min-w-0 items-center gap-1.5 rounded-md px-1 py-0.5 text-caption hover:bg-surface-hover focus-visible:outline-2 focus-visible:outline-ring"
+ >
+ <ActorAvatar
+ actorType="agent"
+ actorId={agent.id}
+ size="xs"
+ profileLink={false}
+ />
+ <span className="max-w-32 truncate">{agent.name}</span>
+ </AppLink>
+ ))
+ ) : (
+ <span className="text-caption text-muted-foreground">
+ {t(($) => $.channels.disconnected)}
+ </span>
+ )}
+ {orphaned.map((entry) => (
+ <span
+ key={entry.installation.id}
+ className="inline-flex items-center gap-2 text-caption text-muted-foreground"
+ >
+ {t(($) => $.channels.agent_unavailable)}
+ <Button
+ size="xs"
+ variant="ghost"
+ onClick={() => setDisconnecting(entry)}
+ >
+ {t(($) => $.channels.disconnect)}
+ </Button>
+ </span>
+ ))}
+ {!query.isPending &&
+ !query.isError &&
+ !query.data?.configured &&
+ isAdmin ? (
+ <span className="text-caption text-muted-foreground">
+ {t(($) => $.channels.unavailable)}
+ </span>
+ ) : null}
+ </div>
+ {query.isError ? (
+ <Button
+ size="xs"
+ variant="outline"
+ onClick={() => void query.refetch()}
+ >
+ {t(($) => $.lark.install_retry)}
+ </Button>
+ ) : isAdmin && available(id) ? (
+ <Button
+ size="sm"
+ variant="outline"
+ disabled={
+ !agents.some(
+ (agent) =>
+ !agent.archived_at &&
+ !connectedAgents.some(
+ (connected) => connected.id === agent.id,
+ ),
+ )
+ }
+ onClick={() => setConnecting(id)}
+ >
+ {t(($) => $.channels.connect)}
+ </Button>
+ ) : null}
+ </div>
+ );
+ })}
</SettingsCard>
+ <SettingsSection title={t(($) => $.channels.permissions_title)}>
+ <SettingsCard>
+ <div className="flex flex-wrap justify-between gap-2 px-4 py-3 text-caption">
+ <span>
+ {t(($) => $.lark.section_title)},{" "}
+ {t(($) => $.dingtalk.section_title)}
+ </span>
+ <span className="text-muted-foreground">
+ {t(($) => $.channels.owner_or_admin)}
+ </span>
+ </div>
+ <div className="flex flex-wrap justify-between gap-2 px-4 py-3 text-caption">
+ <span>
+ {t(($) => $.slack.section_title)},{" "}
+ {t(($) => $.wecom.section_title)},{" "}
+ {t(($) => $.telegram.section_title)}
+ </span>
+ <span className="text-muted-foreground">
+ {t(($) => $.channels.admin_only)}
+ </span>
+ </div>
+ </SettingsCard>
+ </SettingsSection>
+ <ChannelConnectDialog
+ key={connecting ?? "closed"}
+ agents={agents}
+ initialChannel={connecting ?? undefined}
+ open={connecting !== null}
+ onOpenChange={(open) => {
+ if (!open) setConnecting(null);
+ }}
+ />
+ {disconnecting ? (
+ <ChannelDisconnectDialog
+ connection={disconnecting}
+ open
+ onOpenChange={(open) => {
+ if (!open) setDisconnecting(null);
+ }}
+ />
+ ) : null}
</SettingsTab>
);
}
-
-export function ConnectionBadge({ state, boundLabel, connectedLabel }: {
- state: ConnectionState;
- boundLabel?: string;
- connectedLabel?: string;
-}) {
- const { t } = useT("settings");
- const connected = !state.isError && !state.isPending && state.data === true;
- const label = state.isError
- ? t(($) => $.integrations.status_unknown)
- : state.isPending
- ? t(($) => $.integrations.status_loading)
- : connected
- ? (boundLabel ?? connectedLabel ?? t(($) => $.integrations.status_connected))
- : t(($) => $.integrations.status_not_connected);
- return (
- <span
- className={cn(
- "inline-flex items-center gap-1.5 text-caption",
- connected && !boundLabel ? "text-success" : "text-muted-foreground",
- )}
- >
- {connected && !boundLabel && (
- <span aria-hidden="true" className="size-1.5 rounded-full bg-success" />
- )}
- {label}
- </span>
- );
-}
diff --git a/packages/views/settings/components/dingtalk-bot-groups.test.tsx b/packages/views/settings/components/dingtalk-bot-groups.test.tsx
new file mode 100644
index 0000000000..29df84d7d1
--- /dev/null
+++ b/packages/views/settings/components/dingtalk-bot-groups.test.tsx
@@ -0,0 +1,173 @@
+import type { ReactNode } from "react";
+import { describe, it, expect, beforeEach, vi } from "vitest";
+import { render, screen } from "@testing-library/react";
+import userEvent from "@testing-library/user-event";
+import { I18nProvider } from "@multica/core/i18n/react";
+import type { DingTalkGroup } from "@multica/core/types";
+import enSettings from "../../locales/en/settings.json";
+import { DingTalkBotGroups } from "./dingtalk-bot-groups";
+const groupsRef = {
+ current: {
+ data: {
+ groups: [] as unknown[],
+ group_discovery_supported: true,
+ inactive_group_counts: {} as Record<string, number>,
+ },
+ },
+};
+const inactiveGroupsRef = vi.hoisted(() => ({
+ current: {
+ data: undefined as
+ | undefined
+ | { pages: Array<{ groups: unknown[]; next_offset: number | null }> },
+ isLoading: false,
+ isError: false,
+ refetch: vi.fn(),
+ hasNextPage: false,
+ isFetchingNextPage: false,
+ fetchNextPage: vi.fn(),
+ },
+}));
+vi.mock("@tanstack/react-query", () => ({
+ useQueryClient: () => ({ invalidateQueries: vi.fn() }),
+ useInfiniteQuery: () => inactiveGroupsRef.current,
+}));
+function GroupList() {
+ return (
+ <DingTalkBotGroups
+ workspaceId="workspace-1"
+ installationId="i1"
+ groups={groupsRef.current.data.groups as DingTalkGroup[]}
+ inactiveCount={groupsRef.current.data.inactive_group_counts?.i1 ?? 0}
+ isLoading={false}
+ isError={false}
+ onRetry={vi.fn()}
+ />
+ );
+}
+function renderUI(children: ReactNode) {
+ return render(
+ <I18nProvider locale="en" resources={{ en: { settings: enSettings } }}>
+ {children}
+ </I18nProvider>,
+ );
+}
+function resetFixtures() {
+ vi.clearAllMocks();
+ groupsRef.current.data = {
+ groups: [],
+ group_discovery_supported: true,
+ inactive_group_counts: {},
+ };
+ inactiveGroupsRef.current.data = undefined;
+}
+
+describe("DingTalkBotGroups", () => {
+ beforeEach(resetFixtures);
+ it("sorts active groups by recency, then inactive groups by title and conversation ID", () => {
+ groupsRef.current.data.groups = [
+ {
+ conversation_id: "cid-alpha-b",
+ conversation_title: "Alpha",
+ bots: [{ installation_id: "i1", agent_id: "agent-7" }],
+ },
+ {
+ conversation_id: "cid-old",
+ conversation_title: "Zulu",
+ bots: [
+ {
+ installation_id: "i1",
+ agent_id: "agent-7",
+ last_active_at: "2026-08-19T08:00:00Z",
+ },
+ ],
+ },
+ {
+ conversation_id: "cid-untitled",
+ conversation_title: "",
+ bots: [{ installation_id: "i1", agent_id: "agent-7" }],
+ },
+ {
+ conversation_id: "cid-recent",
+ conversation_title: "Beta",
+ bots: [
+ {
+ installation_id: "i1",
+ agent_id: "agent-7",
+ last_active_at: "2026-08-19T09:00:00Z",
+ },
+ ],
+ },
+ {
+ conversation_id: "cid-alpha-a",
+ conversation_title: "Alpha",
+ bots: [{ installation_id: "i1", agent_id: "agent-7" }],
+ },
+ ];
+
+ renderUI(<GroupList />);
+ expect(
+ screen
+ .getAllByTestId("dingtalk-group-item")
+ .map((item) => item.querySelector("code")?.textContent),
+ ).toEqual([
+ "cid-recent",
+ "cid-old",
+ "cid-alpha-a",
+ "cid-alpha-b",
+ "cid-untitled",
+ ]);
+ });
+
+ it("globally sorts inactive groups after merging loaded pages", async () => {
+ groupsRef.current.data = {
+ groups: [],
+ group_discovery_supported: true,
+ inactive_group_counts: { i1: 4 },
+ };
+ inactiveGroupsRef.current.data = {
+ pages: [
+ {
+ groups: [
+ {
+ conversation_id: "cid-zulu",
+ conversation_title: "Zulu",
+ bots: [{ installation_id: "i1", agent_id: "agent-7" }],
+ },
+ {
+ conversation_id: "cid-bravo-b",
+ conversation_title: "Bravo",
+ bots: [{ installation_id: "i1", agent_id: "agent-7" }],
+ },
+ ],
+ next_offset: 2,
+ },
+ {
+ groups: [
+ {
+ conversation_id: "cid-alpha",
+ conversation_title: "Alpha",
+ bots: [{ installation_id: "i1", agent_id: "agent-7" }],
+ },
+ {
+ conversation_id: "cid-bravo-a",
+ conversation_title: "Bravo",
+ bots: [{ installation_id: "i1", agent_id: "agent-7" }],
+ },
+ ],
+ next_offset: null,
+ },
+ ],
+ };
+
+ renderUI(<GroupList />);
+ await userEvent.click(
+ screen.getByRole("button", { name: /long inactive/i }),
+ );
+ expect(
+ screen
+ .getAllByTestId("dingtalk-group-item")
+ .map((item) => item.querySelector("code")?.textContent),
+ ).toEqual(["cid-alpha", "cid-bravo-a", "cid-bravo-b", "cid-zulu"]);
+ });
+});
diff --git a/packages/views/settings/components/dingtalk-bot-groups.tsx b/packages/views/settings/components/dingtalk-bot-groups.tsx
new file mode 100644
index 0000000000..f37706972f
--- /dev/null
+++ b/packages/views/settings/components/dingtalk-bot-groups.tsx
@@ -0,0 +1,339 @@
+"use client";
+
+import { useState } from "react";
+import { useInfiniteQuery, useQueryClient } from "@tanstack/react-query";
+import { toast } from "sonner";
+import { ChevronDown, ChevronRight } from "@multica/ui/icons";
+import { cn } from "@multica/ui/lib/utils";
+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 {
+ Tooltip,
+ TooltipContent,
+ TooltipProvider,
+ TooltipTrigger,
+} from "@multica/ui/components/ui/tooltip";
+import { dingtalkKeys } from "@multica/core/dingtalk";
+import { api } from "@multica/core/api";
+import type { DingTalkGroup, DingTalkGroupBot } from "@multica/core/types";
+import { useT, useTimeAgo } from "../../i18n";
+
+export function getDingTalkBotIdentity(
+ groups: DingTalkGroup[],
+ installationId: string,
+): DingTalkGroupBot | undefined {
+ const bots = groups.flatMap((group) =>
+ group.bots.filter((bot) => bot.installation_id === installationId),
+ );
+ const identity = bots.find((bot) => bot.bot_name) ?? bots[0];
+ const issue = bots.find((bot) => bot.bot_identity_issue)?.bot_identity_issue;
+ return identity
+ ? { ...identity, bot_identity_issue: issue ?? identity.bot_identity_issue }
+ : undefined;
+}
+
+export function DingTalkBotGroups({
+ workspaceId,
+ agentId,
+ installationId,
+ groups,
+ inactiveCount = 0,
+ canForget = false,
+ isLoading,
+ isError,
+ onRetry,
+ showDescription = true,
+ className,
+}: {
+ workspaceId: string;
+ agentId?: string;
+ installationId: string;
+ groups: DingTalkGroup[];
+ inactiveCount?: number;
+ canForget?: boolean;
+ isLoading: boolean;
+ isError: boolean;
+ onRetry: () => void;
+ showDescription?: boolean;
+ className?: string;
+}) {
+ const { t } = useT("settings");
+ const timeAgo = useTimeAgo();
+ const qc = useQueryClient();
+ const [inactiveExpanded, setInactiveExpanded] = useState(false);
+ const [forgetTarget, setForgetTarget] = useState<DingTalkGroup | null>(null);
+ const [forgetting, setForgetting] = useState(false);
+ const inactiveQuery = useInfiniteQuery({
+ queryKey: agentId
+ ? dingtalkKeys.agentInactiveGroups(workspaceId, agentId, installationId)
+ : dingtalkKeys.inactiveGroups(workspaceId, installationId),
+ initialPageParam: 0,
+ queryFn: ({ pageParam }) => {
+ const params = {
+ activity: "inactive" as const,
+ installationId,
+ offset: pageParam,
+ };
+ return agentId
+ ? api.listAgentDingTalkGroups(agentId, params)
+ : api.listDingTalkGroups(workspaceId, params);
+ },
+ getNextPageParam: (page) => page.next_offset,
+ enabled: inactiveExpanded && inactiveCount > 0,
+ });
+
+ const collectObserved = (source: DingTalkGroup[]) =>
+ source
+ .flatMap((group) => {
+ const bot = group.bots.find(
+ (candidate) => candidate.installation_id === installationId,
+ );
+ return bot ? [{ group, bot }] : [];
+ })
+ .sort((left, right) => {
+ const leftActiveAt = Date.parse(left.bot.last_active_at ?? "");
+ const rightActiveAt = Date.parse(right.bot.last_active_at ?? "");
+ const leftIsActive = !Number.isNaN(leftActiveAt);
+ const rightIsActive = !Number.isNaN(rightActiveAt);
+
+ if (leftIsActive && rightIsActive && leftActiveAt !== rightActiveAt) {
+ return rightActiveAt - leftActiveAt;
+ }
+ if (leftIsActive !== rightIsActive) return leftIsActive ? -1 : 1;
+
+ const leftTitle = left.group.conversation_title;
+ const rightTitle = right.group.conversation_title;
+ if (leftTitle !== rightTitle) {
+ if (!leftTitle) return 1;
+ if (!rightTitle) return -1;
+ return leftTitle < rightTitle ? -1 : 1;
+ }
+ if (left.group.conversation_id === right.group.conversation_id)
+ return 0;
+ return left.group.conversation_id < right.group.conversation_id
+ ? -1
+ : 1;
+ });
+ const observed = collectObserved(groups);
+ const inactiveObserved = collectObserved(
+ inactiveQuery.data?.pages.flatMap((page) => page.groups) ?? [],
+ );
+
+ async function handleForget() {
+ if (!forgetTarget || forgetting) return;
+ setForgetting(true);
+ try {
+ await api.forgetDingTalkGroup(
+ workspaceId,
+ installationId,
+ forgetTarget.conversation_id,
+ );
+ await qc.invalidateQueries({
+ queryKey: dingtalkKeys.groups(workspaceId),
+ });
+ toast.success(t(($) => $.dingtalk.group_forget_success));
+ setForgetTarget(null);
+ } catch (error) {
+ toast.error(
+ error instanceof Error
+ ? error.message
+ : t(($) => $.dingtalk.group_forget_failed),
+ );
+ } finally {
+ setForgetting(false);
+ }
+ }
+
+ const renderObserved = (
+ entries: Array<{ group: DingTalkGroup; bot: DingTalkGroupBot }>,
+ ) => (
+ <div>
+ {entries.map(({ group, bot }) => (
+ <div
+ key={group.conversation_id}
+ className="group space-y-1.5 border-t py-2.5"
+ data-testid="dingtalk-group-item"
+ >
+ <div className="flex min-w-0 items-baseline justify-between gap-3">
+ <div className="flex min-w-0 flex-1 items-baseline gap-3">
+ <p className="min-w-0 truncate text-caption font-medium">
+ {group.conversation_title ||
+ t(($) => $.dingtalk.group_untitled)}
+ </p>
+ {canForget && (
+ <button
+ type="button"
+ className="pointer-events-none shrink-0 text-micro text-muted-foreground opacity-0 underline-offset-2 transition-opacity group-hover:pointer-events-auto group-hover:opacity-100 group-focus-within:pointer-events-auto group-focus-within:opacity-100 hover:text-foreground hover:underline focus-visible:pointer-events-auto focus-visible:opacity-100"
+ onClick={() => setForgetTarget(group)}
+ >
+ {t(($) => $.dingtalk.group_forget)}
+ </button>
+ )}
+ </div>
+ <div className="flex min-w-0 max-w-[60%] items-center">
+ <TooltipProvider delay={0}>
+ <Tooltip>
+ <TooltipTrigger
+ render={
+ <code
+ tabIndex={0}
+ translate="no"
+ aria-label={`${t(($) => $.dingtalk.conversation_id_label)} ${group.conversation_id}`}
+ className="block min-w-0 truncate font-mono text-micro text-faint-foreground transition-colors group-hover:text-muted-foreground focus-visible:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
+ >
+ {group.conversation_id}
+ </code>
+ }
+ />
+ <TooltipContent side="top">
+ {t(($) => $.dingtalk.conversation_id_label)}
+ </TooltipContent>
+ </Tooltip>
+ </TooltipProvider>
+ </div>
+ </div>
+ {bot.last_active_at && (
+ <p
+ className="text-micro tabular-nums text-muted-foreground"
+ data-testid="dingtalk-group-activity"
+ >
+ {t(($) => $.dingtalk.group_last_active, {
+ time: timeAgo(bot.last_active_at),
+ })}
+ <span className="mx-1.5" aria-hidden="true">
+ ·
+ </span>
+ {t(($) => $.dingtalk.group_mentions, {
+ count: bot.mention_count ?? 0,
+ })}
+ </p>
+ )}
+ </div>
+ ))}
+ </div>
+ );
+
+ return (
+ <div
+ className={cn("space-y-2 pt-3", className)}
+ data-testid="dingtalk-bot-groups"
+ >
+ {showDescription && (
+ <p className="text-caption leading-relaxed text-muted-foreground">
+ {t(($) => $.dingtalk.groups_description)}
+ </p>
+ )}
+ {isLoading ? (
+ <p className="text-caption text-muted-foreground">
+ {t(($) => $.dingtalk.groups_loading)}
+ </p>
+ ) : isError ? (
+ <div className="flex items-center justify-between gap-3" role="alert">
+ <p className="text-caption text-muted-foreground">
+ {t(($) => $.dingtalk.groups_error)}
+ </p>
+ <button
+ type="button"
+ className="shrink-0 text-caption font-medium underline-offset-2 hover:underline"
+ onClick={onRetry}
+ >
+ {t(($) => $.dingtalk.groups_retry)}
+ </button>
+ </div>
+ ) : observed.length === 0 ? (
+ <p className="text-caption text-muted-foreground">
+ {inactiveCount > 0
+ ? t(($) => $.dingtalk.groups_no_recent)
+ : t(($) => $.dingtalk.groups_empty)}
+ </p>
+ ) : (
+ renderObserved(observed)
+ )}
+ {!isLoading && !isError && inactiveCount > 0 && (
+ <div className="border-t pt-2">
+ <button
+ type="button"
+ className="flex w-full items-center gap-1.5 py-1 text-caption font-medium text-muted-foreground hover:text-foreground"
+ onClick={() => setInactiveExpanded((value) => !value)}
+ aria-expanded={inactiveExpanded}
+ >
+ {inactiveExpanded ? (
+ <ChevronDown className="h-3.5 w-3.5" aria-hidden="true" />
+ ) : (
+ <ChevronRight className="h-3.5 w-3.5" aria-hidden="true" />
+ )}
+ {t(($) => $.dingtalk.groups_inactive, { count: inactiveCount })}
+ </button>
+ {inactiveExpanded && (
+ <div className="pt-1">
+ {inactiveQuery.isLoading ? (
+ <p className="py-2 text-caption text-muted-foreground">
+ {t(($) => $.dingtalk.groups_loading)}
+ </p>
+ ) : inactiveQuery.isError ? (
+ <button
+ type="button"
+ className="py-2 text-caption font-medium underline-offset-2 hover:underline"
+ onClick={() => void inactiveQuery.refetch()}
+ >
+ {t(($) => $.dingtalk.groups_retry)}
+ </button>
+ ) : (
+ <>
+ {renderObserved(inactiveObserved)}
+ {inactiveQuery.hasNextPage && (
+ <Button
+ type="button"
+ variant="ghost"
+ size="sm"
+ disabled={inactiveQuery.isFetchingNextPage}
+ onClick={() => void inactiveQuery.fetchNextPage()}
+ >
+ {inactiveQuery.isFetchingNextPage
+ ? t(($) => $.dingtalk.groups_loading)
+ : t(($) => $.dingtalk.groups_load_more)}
+ </Button>
+ )}
+ </>
+ )}
+ </div>
+ )}
+ </div>
+ )}
+ <AlertDialog
+ open={!!forgetTarget}
+ onOpenChange={(open) => {
+ if (!open && !forgetting) setForgetTarget(null);
+ }}
+ >
+ <AlertDialogContent>
+ <AlertDialogHeader>
+ <AlertDialogTitle>
+ {t(($) => $.dingtalk.group_forget_title)}
+ </AlertDialogTitle>
+ <AlertDialogDescription>
+ {t(($) => $.dingtalk.group_forget_description)}
+ </AlertDialogDescription>
+ </AlertDialogHeader>
+ <AlertDialogFooter>
+ <AlertDialogCancel disabled={forgetting}>
+ {t(($) => $.dingtalk.group_forget_cancel)}
+ </AlertDialogCancel>
+ <AlertDialogAction onClick={handleForget} disabled={forgetting}>
+ {t(($) => $.dingtalk.group_forget_confirm)}
+ </AlertDialogAction>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
+ </div>
+ );
+}
diff --git a/packages/views/settings/components/dingtalk-tab.test.tsx b/packages/views/settings/components/dingtalk-tab.test.tsx
deleted file mode 100644
index 3be78c8475..0000000000
--- a/packages/views/settings/components/dingtalk-tab.test.tsx
+++ /dev/null
@@ -1,752 +0,0 @@
-// @vitest-environment jsdom
-
-import { type ReactNode } from "react";
-import { describe, it, expect, beforeEach, afterEach, vi } from "vitest";
-import { cleanup, render, screen, waitFor } from "@testing-library/react";
-import userEvent from "@testing-library/user-event";
-import { I18nProvider } from "@multica/core/i18n/react";
-import enCommon from "../../locales/en/common.json";
-import enSettings from "../../locales/en/settings.json";
-
-type MemberRole = "owner" | "admin" | "member";
-
-const membersRef = vi.hoisted(() => ({
- current: [{ user_id: "user-1", role: "owner" as MemberRole }],
-}));
-const agentsRef = vi.hoisted(() => ({
- current: [
- { id: "agent-1" },
- { id: "agent-7" },
- { id: "agent-8" },
- ],
-}));
-const installationsRef = vi.hoisted(() => ({
- current: {
- installations: [] as unknown[],
- configured: true,
- install_supported: true,
- },
-}));
-const groupsRef = vi.hoisted(() => ({
- current: {
- data: { groups: [], group_discovery_supported: true } as {
- groups: unknown[];
- group_discovery_supported: boolean;
- inactive_group_counts?: Record<string, number>;
- bot_identities?: Record<string, unknown>;
- },
- isLoading: false,
- isError: false,
- refetch: vi.fn(),
- },
-}));
-const inactiveGroupsRef = vi.hoisted(() => ({
- current: {
- data: undefined as undefined | { pages: Array<{ groups: unknown[]; next_offset: number | null }> },
- isLoading: false,
- isError: false,
- refetch: vi.fn(),
- hasNextPage: false,
- isFetchingNextPage: false,
- fetchNextPage: vi.fn(),
- },
-}));
-const mockRegisterBYO = vi.hoisted(() => vi.fn());
-const mockDeleteInstallation = vi.hoisted(() => vi.fn());
-const mockOpenExternal = vi.hoisted(() => vi.fn());
-const mockInvalidate = vi.hoisted(() => vi.fn());
-
-vi.mock("@tanstack/react-query", () => ({
- useQuery: (opts: { queryKey: unknown[]; enabled?: boolean }) => {
- if (opts.enabled === false) return { data: undefined, isLoading: false };
- const key = JSON.stringify(opts.queryKey);
- if (key.includes("members")) return { data: membersRef.current, isLoading: false };
- if (key.includes("agents")) return { data: agentsRef.current, isLoading: false };
- if (key.includes("groups")) return groupsRef.current;
- if (key.includes("installations")) return { data: installationsRef.current, isLoading: false };
- return { data: undefined, isLoading: false };
- },
- useQueryClient: () => ({ invalidateQueries: mockInvalidate }),
- useInfiniteQuery: () => inactiveGroupsRef.current,
- queryOptions: <T,>(opts: T) => opts,
-}));
-
-vi.mock("@multica/core/hooks", () => ({ useWorkspaceId: () => "workspace-1" }));
-
-vi.mock("@multica/core/workspace/queries", () => ({
- memberListOptions: () => ({ queryKey: ["members"], queryFn: vi.fn() }),
- agentListOptions: () => ({ queryKey: ["agents"], queryFn: vi.fn() }),
-}));
-
-vi.mock("@multica/core/workspace/hooks", () => ({
- useActorName: () => ({
- getAgentName: (agentId: string) => `Agent ${agentId}`,
- getMemberName: () => "Unknown",
- getSquadName: () => "Unknown Squad",
- getActorName: () => "Unknown",
- getActorInitials: () => "??",
- getActorAvatarUrl: () => null,
- }),
-}));
-
-vi.mock("../../common/actor-avatar", () => ({
- ActorAvatar: ({
- actorId,
- profileLink,
- }: {
- actorId: string;
- profileLink?: boolean;
- }) => (
- <span
- data-testid="actor-avatar"
- data-actor-id={actorId}
- data-profile-link={String(profileLink)}
- />
- ),
-}));
-
-vi.mock("@multica/core/dingtalk", () => ({
- dingtalkInstallationsOptions: () => ({
- queryKey: ["dingtalk", "installations"],
- queryFn: vi.fn(),
- }),
- dingtalkGroupsOptions: () => ({
- queryKey: ["dingtalk", "groups"],
- queryFn: vi.fn(),
- }),
- dingtalkKeys: {
- installations: (wsId: string) => ["dingtalk", "installations", wsId],
- groups: (wsId: string) => ["dingtalk", "groups", wsId],
- inactiveGroups: (wsId: string, installationId: string) =>
- ["dingtalk", "groups", wsId, "inactive", installationId],
- agentInactiveGroups: (wsId: string, agentId: string, installationId: string) =>
- ["dingtalk", "groups", wsId, "agent", agentId, "inactive", installationId],
- },
-}));
-
-vi.mock("@multica/core/api", () => ({
- api: {
- registerDingTalkBYO: mockRegisterBYO,
- deleteDingTalkInstallation: mockDeleteInstallation,
- forgetDingTalkGroup: vi.fn(),
- },
-}));
-
-vi.mock("@multica/core/auth", () => {
- const useAuthStore = Object.assign(
- (sel?: (s: { user: { id: string } }) => unknown) =>
- sel ? sel({ user: { id: "user-1" } }) : { user: { id: "user-1" } },
- { getState: () => ({ user: { id: "user-1" } }) },
- );
- return { useAuthStore };
-});
-
-vi.mock("sonner", () => ({
- toast: { success: vi.fn(), error: vi.fn(), message: vi.fn() },
-}));
-
-vi.mock("../../platform", () => ({ openExternal: mockOpenExternal }));
-
-import { DingTalkAgentBindButton, DingTalkTab } from "./dingtalk-tab";
-
-const TEST_RESOURCES = { en: { common: enCommon, settings: enSettings } };
-
-afterEach(cleanup);
-
-function renderUI(children: ReactNode) {
- return render(
- <I18nProvider locale="en" resources={TEST_RESOURCES}>
- {children}
- </I18nProvider>,
- );
-}
-
-function resetFixtures() {
- vi.clearAllMocks();
- membersRef.current = [{ user_id: "user-1", role: "owner" }];
- agentsRef.current = [
- { id: "agent-1" },
- { id: "agent-7" },
- { id: "agent-8" },
- ];
- installationsRef.current = { installations: [], configured: true, install_supported: true };
- groupsRef.current = {
- data: { groups: [], group_discovery_supported: true },
- isLoading: false,
- isError: false,
- refetch: vi.fn(),
- };
- inactiveGroupsRef.current = {
- data: undefined,
- isLoading: false,
- isError: false,
- refetch: vi.fn(),
- hasNextPage: false,
- isFetchingNextPage: false,
- fetchNextPage: vi.fn(),
- };
-}
-
-describe("DingTalkAgentBindButton", () => {
- beforeEach(resetFixtures);
-
- it("opens the BYO dialog and submits the pasted AppKey + AppSecret", async () => {
- mockRegisterBYO.mockResolvedValue({ id: "i1", agent_id: "agent-1", status: "active" });
- renderUI(<DingTalkAgentBindButton agentId="agent-1" agentName="Bot" />);
- await userEvent.click(screen.getByTestId("dingtalk-agent-connect"));
- const idInput = await screen.findByTestId("dingtalk-byo-client-id");
- await userEvent.type(idInput, "ding-appkey");
- await userEvent.type(screen.getByTestId("dingtalk-byo-client-secret"), "ding-appsecret");
- await userEvent.click(screen.getByTestId("dingtalk-byo-submit"));
- await waitFor(() =>
- expect(mockRegisterBYO).toHaveBeenCalledWith("workspace-1", "agent-1", {
- client_id: "ding-appkey",
- client_secret: "ding-appsecret",
- }),
- );
- expect(mockOpenExternal).not.toHaveBeenCalled();
- });
-
- it("masks both credential inputs as password fields", async () => {
- renderUI(<DingTalkAgentBindButton agentId="agent-1" agentName="Bot" />);
- await userEvent.click(screen.getByTestId("dingtalk-agent-connect"));
- const idInput = await screen.findByTestId("dingtalk-byo-client-id");
- const secretInput = screen.getByTestId("dingtalk-byo-client-secret");
- expect(idInput.getAttribute("type")).toBe("password");
- expect(secretInput.getAttribute("type")).toBe("password");
- });
-
- it("shows the connected badge (not the CTA) when the agent already has an active install", () => {
- installationsRef.current = {
- installations: [{ id: "i1", agent_id: "agent-1", status: "active" }],
- configured: true,
- install_supported: true,
- };
- renderUI(<DingTalkAgentBindButton agentId="agent-1" />);
- expect(screen.getByTestId("dingtalk-agent-bot-connected")).toBeTruthy();
- expect(screen.getByTestId("dingtalk-agent-bot-disconnect")).toBeTruthy();
- expect(screen.queryByTestId("dingtalk-agent-connect")).toBeNull();
- });
-
- it.each([
- { role: "owner", ownsAgent: false, canManage: true },
- { role: "owner", ownsAgent: true, canManage: true },
- { role: "admin", ownsAgent: false, canManage: true },
- { role: "admin", ownsAgent: true, canManage: true },
- { role: "member", ownsAgent: false, canManage: false },
- { role: "member", ownsAgent: true, canManage: true },
- ] as const)(
- "applies the Agent Detail permission matrix: role=$role ownsAgent=$ownsAgent",
- ({ role, ownsAgent, canManage }) => {
- membersRef.current = [{ user_id: "user-1", role }];
- renderUI(
- <DingTalkAgentBindButton
- agentId="agent-1"
- agentOwnerId={ownsAgent ? "user-1" : "user-2"}
- />,
- );
- expect(screen.queryByTestId("dingtalk-agent-connect") !== null).toBe(canManage);
- },
- );
-
- it("renders no management entry for a user without workspace membership", () => {
- membersRef.current = [];
- const { container } = renderUI(
- <DingTalkAgentBindButton agentId="agent-1" agentOwnerId="user-1" />,
- );
- expect(container.firstChild).toBeNull();
- });
-
- it("renders nothing when install is unavailable and the agent is unbound", () => {
- installationsRef.current = { installations: [], configured: true, install_supported: false };
- const { container } = renderUI(<DingTalkAgentBindButton agentId="agent-1" />);
- expect(container.firstChild).toBeNull();
- });
-});
-
-describe("DingTalkTab", () => {
- beforeEach(resetFixtures);
-
- it.each([
- { role: "owner", canManage: true },
- { role: "admin", canManage: true },
- { role: "member", canManage: false },
- ] as const)(
- "applies the Settings permission matrix for role=$role",
- ({ role, canManage }) => {
- // Settings intentionally has no Agent-owner input: every plain member,
- // including someone who owns one of these Agents, stays read-only here.
- membersRef.current = [{ user_id: "user-1", role }];
- installationsRef.current = {
- installations: [{
- id: "i-role-matrix",
- agent_id: "agent-7",
- status: "active",
- installed_at: "2026-08-19T00:00:00Z",
- bound_dingtalk_user_ids: ["staff-role-matrix"],
- }],
- configured: true,
- install_supported: true,
- };
- groupsRef.current.data.groups = [{
- conversation_id: "cid-role-matrix",
- conversation_title: "Role matrix group",
- bots: [{
- installation_id: "i-role-matrix",
- agent_id: "agent-7",
- bot_name: "Role matrix bot",
- }],
- }];
-
- renderUI(<DingTalkTab />);
- expect(screen.queryByRole("button", { name: /Disconnect/i }) !== null).toBe(canManage);
- expect(
- screen.queryByRole("button", { name: "Role matrix bot" }) !== null,
- ).toBe(canManage);
- expect(screen.queryByText(/staff-role-matrix/)).toBeNull();
- expect(screen.getByText("Role matrix bot")).toBeTruthy();
- expect(screen.getByText("Role matrix group")).toBeTruthy();
- expect(screen.getByTestId("dingtalk-installation-metadata").textContent).toContain(
- "Installed",
- );
- expect(
- screen.queryByRole("heading", {
- name: "Connections",
- level: 2,
- }),
- ).toBeTruthy();
- },
- );
-
- it("surfaces the not-enabled notice when the deployment has no DingTalk key", () => {
- installationsRef.current = { installations: [], configured: false, install_supported: false };
- renderUI(<DingTalkTab />);
- expect(screen.getByText(/DingTalk integration not enabled/i)).toBeTruthy();
- });
-
- it("shows the empty state when configured but nothing is connected", () => {
- renderUI(<DingTalkTab />);
- expect(screen.getByText(/No bots connected yet/i)).toBeTruthy();
- });
-
- it("shows linked Staff IDs from the bot name without adding them to the row", async () => {
- installationsRef.current = {
- installations: [{
- id: "i1",
- agent_id: "agent-7",
- status: "active",
- bound_dingtalk_user_ids: ["staff-1001", "staff-1002"],
- }],
- configured: true,
- install_supported: true,
- };
- groupsRef.current.data.groups = [{
- conversation_id: "cid-linked",
- conversation_title: "Linked group",
- bots: [{
- installation_id: "i1",
- agent_id: "agent-7",
- bot_name: "Linked Bot",
- }],
- }];
- renderUI(<DingTalkTab />);
- expect(screen.getByText("Agent agent-7")).toBeTruthy();
- const botName = screen.getByRole("button", { name: "Linked Bot" });
- expect(screen.queryByText(/Linked staff ID:/i)).toBeNull();
- await userEvent.hover(botName);
- expect(
- await screen.findByText("Linked staff ID: staff-1001, staff-1002"),
- ).toBeTruthy();
- expect(screen.getByText(/Disconnect/i)).toBeTruthy();
- });
-
- it("does not render a linked identity when this member has no DingTalk binding", () => {
- installationsRef.current = {
- installations: [{ id: "i1", agent_id: "agent-7", status: "active" }],
- configured: true,
- install_supported: true,
- };
- renderUI(<DingTalkTab />);
- expect(screen.queryByText(/Linked staff ID:/i)).toBeNull();
- });
-
- it("hides linked DingTalk identities from a regular workspace member", () => {
- membersRef.current = [{ user_id: "user-1", role: "member" }];
- installationsRef.current = {
- installations: [{
- id: "i1",
- agent_id: "agent-7",
- status: "active",
- bound_dingtalk_user_ids: ["staff-must-stay-private"],
- }],
- configured: true,
- install_supported: true,
- };
- renderUI(<DingTalkTab />);
- expect(screen.getByText("Agent agent-7")).toBeTruthy();
- expect(screen.queryByText(/staff-must-stay-private/)).toBeNull();
- expect(screen.queryByText(/Linked staff ID:/i)).toBeNull();
- expect(screen.getByRole("heading", { name: "Connections", level: 2 })).toBeTruthy();
- });
-
- it("shows every observed Agent → Bot → Group relationship to an admin", async () => {
- membersRef.current = [{ user_id: "user-1", role: "admin" }];
- installationsRef.current = {
- installations: [
- {
- id: "i1",
- agent_id: "agent-7",
- status: "active",
- installed_at: "2026-08-19T00:00:00Z",
- bound_dingtalk_user_ids: ["staff-1001"],
- },
- ],
- configured: true,
- install_supported: true,
- };
- groupsRef.current.data.groups = [
- {
- conversation_id: "cid-platform",
- conversation_title: "Platform team",
- bots: [
- {
- installation_id: "i1",
- agent_id: "agent-7",
- bot_name: "Release Bot",
- bot_identity_issue: "missing_qyapi_chat_manage",
- },
- ],
- },
- ];
-
- renderUI(<DingTalkTab />);
- expect(screen.getByText("Agent agent-7")).toBeTruthy();
- expect(screen.getByRole("heading", { name: "Connections", level: 2 })).toBeTruthy();
- expect(screen.getByText("Release Bot")).toBeTruthy();
- expect(
- screen.getByRole("button", { name: /qyapi_chat_manage/i }),
- ).toBeTruthy();
- const connectedLabel = screen.getByText("Connected bot:");
- const connectedStatus = connectedLabel.parentElement?.parentElement;
- expect(connectedStatus?.classList).toContain(
- "text-caption",
- );
- expect(connectedStatus?.classList).not.toContain(
- "text-micro",
- );
- const metadata = screen.getByTestId("dingtalk-installation-metadata");
- expect(metadata.contains(connectedLabel)).toBe(false);
- expect(metadata.parentElement).toBe(connectedStatus?.parentElement);
- expect(metadata.textContent).toContain("Installed");
- expect(metadata.parentElement?.textContent).toContain(
- "Connected bot:Release Bot·Installed",
- );
- expect(metadata.parentElement?.textContent).not.toContain("Linked staff ID");
- expect(metadata.textContent).not.toContain("Release Bot");
- expect(metadata.textContent).not.toMatch(/\d{1,2}:\d{2}:\d{2}/);
- expect(screen.queryByText(/Connected to Agent/i)).toBeNull();
- const groupTitle = screen.getByText("Platform team");
- const forgetButton = screen.getByRole("button", { name: "Forget" });
- expect(groupTitle.parentElement?.contains(forgetButton)).toBe(true);
- expect(forgetButton.classList).toContain("opacity-0");
- expect(forgetButton.classList).toContain("group-hover:opacity-100");
- expect(forgetButton.classList).toContain("group-focus-within:opacity-100");
- expect(
- screen.getByRole("heading", { name: "Recent groups", level: 4 }),
- ).toBeTruthy();
- expect(screen.getByTestId("dingtalk-bot-groups").parentElement).toBe(
- screen.getByTestId("dingtalk-installation-row"),
- );
- expect(screen.getByTestId("dingtalk-installation-row").classList).toContain("py-6");
- expect(
- screen.getByTestId("dingtalk-installation-row").closest('[data-slot="card"]')?.classList,
- ).toContain("py-0");
- const conversationId = screen.getByLabelText(
- "DingTalk group conversation ID cid-platform",
- );
- expect(conversationId.textContent).toBe("cid-platform");
- expect(conversationId.classList).toContain("text-faint-foreground");
- expect(conversationId.classList).toContain("group-hover:text-muted-foreground");
- await userEvent.hover(conversationId);
- await waitFor(() =>
- expect(document.querySelector('[data-slot="tooltip-content"]')).toBeTruthy(),
- );
- const tooltip = document.querySelector('[data-slot="tooltip-content"]');
- expect(tooltip?.textContent).toBe("DingTalk group conversation ID");
- expect(tooltip?.textContent).not.toContain("cid-platform");
- expect(screen.getAllByText("cid-platform")).toHaveLength(1);
- });
-
- it("sorts active groups by recency, then inactive groups by title and conversation ID", () => {
- installationsRef.current = {
- installations: [{ id: "i1", agent_id: "agent-7", status: "active" }],
- configured: true,
- install_supported: true,
- };
- groupsRef.current.data.groups = [
- {
- conversation_id: "cid-alpha-b",
- conversation_title: "Alpha",
- bots: [{ installation_id: "i1", agent_id: "agent-7" }],
- },
- {
- conversation_id: "cid-old",
- conversation_title: "Zulu",
- bots: [{
- installation_id: "i1",
- agent_id: "agent-7",
- last_active_at: "2026-08-19T08:00:00Z",
- }],
- },
- {
- conversation_id: "cid-untitled",
- conversation_title: "",
- bots: [{ installation_id: "i1", agent_id: "agent-7" }],
- },
- {
- conversation_id: "cid-recent",
- conversation_title: "Beta",
- bots: [{
- installation_id: "i1",
- agent_id: "agent-7",
- last_active_at: "2026-08-19T09:00:00Z",
- }],
- },
- {
- conversation_id: "cid-alpha-a",
- conversation_title: "Alpha",
- bots: [{ installation_id: "i1", agent_id: "agent-7" }],
- },
- ];
-
- renderUI(<DingTalkTab />);
- expect(
- screen.getAllByTestId("dingtalk-group-item").map((item) =>
- item.querySelector("code")?.textContent,
- ),
- ).toEqual([
- "cid-recent",
- "cid-old",
- "cid-alpha-a",
- "cid-alpha-b",
- "cid-untitled",
- ]);
- });
-
- it("globally sorts inactive groups after merging loaded pages", async () => {
- installationsRef.current = {
- installations: [{ id: "i1", agent_id: "agent-7", status: "active" }],
- configured: true,
- install_supported: true,
- };
- groupsRef.current.data = {
- groups: [],
- group_discovery_supported: true,
- inactive_group_counts: { i1: 4 },
- };
- inactiveGroupsRef.current.data = {
- pages: [
- {
- groups: [
- {
- conversation_id: "cid-zulu",
- conversation_title: "Zulu",
- bots: [{ installation_id: "i1", agent_id: "agent-7" }],
- },
- {
- conversation_id: "cid-bravo-b",
- conversation_title: "Bravo",
- bots: [{ installation_id: "i1", agent_id: "agent-7" }],
- },
- ],
- next_offset: 2,
- },
- {
- groups: [
- {
- conversation_id: "cid-alpha",
- conversation_title: "Alpha",
- bots: [{ installation_id: "i1", agent_id: "agent-7" }],
- },
- {
- conversation_id: "cid-bravo-a",
- conversation_title: "Bravo",
- bots: [{ installation_id: "i1", agent_id: "agent-7" }],
- },
- ],
- next_offset: null,
- },
- ],
- };
-
- renderUI(<DingTalkTab />);
- await userEvent.click(screen.getByRole("button", { name: /long inactive/i }));
- expect(
- screen.getAllByTestId("dingtalk-group-item").map((item) =>
- item.querySelector("code")?.textContent,
- ),
- ).toEqual(["cid-alpha", "cid-bravo-a", "cid-bravo-b", "cid-zulu"]);
- });
-
- it("renders discovery UI only when the backend explicitly supports it", () => {
- installationsRef.current = {
- installations: [{ id: "i1", agent_id: "agent-7", status: "active" }],
- configured: true,
- install_supported: true,
- };
- groupsRef.current.data = {
- groups: [],
- group_discovery_supported: false,
- };
-
- renderUI(<DingTalkTab />);
- expect(screen.getByText("Connected bot:")).toBeTruthy();
- expect(screen.queryByText("Identity unavailable")).toBeNull();
- expect(screen.queryByTestId("dingtalk-bot-groups")).toBeNull();
- });
-
- it("keeps loading and retryable error states visible before capability data arrives", async () => {
- installationsRef.current = {
- installations: [{ id: "i1", agent_id: "agent-7", status: "active" }],
- configured: true,
- install_supported: true,
- };
- groupsRef.current.isLoading = true;
- groupsRef.current.data = undefined as never;
-
- const loading = renderUI(<DingTalkTab />);
- expect(screen.getByText("Loading groups…")).toBeTruthy();
- loading.unmount();
-
- groupsRef.current.isLoading = false;
- groupsRef.current.isError = true;
- groupsRef.current.data = undefined as never;
- renderUI(<DingTalkTab />);
-
- await userEvent.click(screen.getByRole("button", { name: "Retry" }));
- expect(groupsRef.current.refetch).toHaveBeenCalledOnce();
- });
-
- it("shows only the server-filtered Agent, bot, groups, and install time to a regular member", () => {
- membersRef.current = [{ user_id: "user-1", role: "member" }];
- installationsRef.current = {
- installations: [
- { id: "i1", agent_id: "agent-7", status: "active", installed_at: "" },
- ],
- configured: true,
- install_supported: true,
- };
- groupsRef.current.data.groups = [
- {
- conversation_id: "cid-private",
- conversation_title: "Visible group",
- bots: [
- {
- installation_id: "i1",
- agent_id: "agent-7",
- bot_name: "Visible Bot",
- bot_identity_issue: "missing_qyapi_chat_manage",
- },
- ],
- },
- ];
-
- renderUI(<DingTalkTab />);
- expect(screen.getByText("Agent agent-7")).toBeTruthy();
- expect(screen.getByText("Visible Bot")).toBeTruthy();
- expect(screen.getByText("Visible group")).toBeTruthy();
- expect(screen.getByTestId("dingtalk-bot-groups")).toBeTruthy();
- expect(screen.getByTestId("dingtalk-installation-metadata").textContent).toContain(
- "Installed —",
- );
- expect(screen.queryByRole("button", { name: /Disconnect/i })).toBeNull();
- expect(screen.queryByRole("button", { name: /qyapi_chat_manage/i })).toBeNull();
- });
-
- it("shows an unavailable bot identity without admin remediation to a regular member", () => {
- membersRef.current = [{ user_id: "user-1", role: "member" }];
- installationsRef.current = {
- installations: [
- { id: "i1", agent_id: "agent-7", status: "active", installed_at: "" },
- ],
- configured: true,
- install_supported: true,
- };
- groupsRef.current.data.groups = [
- {
- conversation_id: "cid-visible",
- conversation_title: "Visible group",
- bots: [
- {
- installation_id: "i1",
- agent_id: "agent-7",
- bot_name: "",
- bot_identity_issue: "missing_qyapi_chat_manage",
- },
- ],
- },
- ];
-
- renderUI(<DingTalkTab />);
- expect(screen.getByText("Identity unavailable")).toBeTruthy();
- expect(screen.queryByRole("button", { name: /qyapi_chat_manage/i })).toBeNull();
- });
-
- it("filters a legacy server row when the member cannot see its Agent", () => {
- membersRef.current = [{ user_id: "user-1", role: "member" }];
- agentsRef.current = [{ id: "agent-7" }];
- installationsRef.current = {
- installations: [
- {
- id: "i-private",
- agent_id: "agent-private",
- status: "active",
- installed_at: "2026-08-19T00:00:00Z",
- },
- ],
- configured: true,
- install_supported: true,
- };
-
- renderUI(<DingTalkTab />);
- expect(screen.queryByText("Agent agent-private")).toBeNull();
- expect(screen.queryByTestId("dingtalk-installation-row")).toBeNull();
- expect(screen.getByText("No bots connected yet")).toBeTruthy();
- });
-
- it("labels an orphaned admin-only installation without linking to a missing Agent", () => {
- installationsRef.current = {
- installations: [
- {
- id: "i-orphan",
- agent_id: "agent-deleted",
- agent_available: false,
- status: "active",
- installed_at: "2026-08-19T00:00:00Z",
- },
- ],
- configured: true,
- install_supported: true,
- };
-
- renderUI(<DingTalkTab />);
- expect(screen.getByText("Deleted Agent")).toBeTruthy();
- expect(screen.getByTestId("actor-avatar").getAttribute("data-profile-link")).toBe(
- "false",
- );
- expect(screen.getByRole("button", { name: /Disconnect/i })).toBeTruthy();
- });
-
- it("shows a placeholder instead of 'Invalid Date' when installed_at is missing or malformed", () => {
- installationsRef.current = {
- installations: [
- { id: "i1", agent_id: "agent-7", status: "active", installed_at: "" },
- { id: "i2", agent_id: "agent-8", status: "active", installed_at: "not-a-date" },
- ],
- configured: true,
- install_supported: true,
- };
- renderUI(<DingTalkTab />);
- expect(screen.queryByText(/Invalid Date/i)).toBeNull();
- });
-});
diff --git a/packages/views/settings/components/dingtalk-tab.tsx b/packages/views/settings/components/dingtalk-tab.tsx
deleted file mode 100644
index 263c869915..0000000000
--- a/packages/views/settings/components/dingtalk-tab.tsx
+++ /dev/null
@@ -1,1159 +0,0 @@
-"use client";
-
-import { useState } from "react";
-import { useInfiniteQuery, useQuery, useQueryClient } from "@tanstack/react-query";
-import { toast } from "sonner";
-import { ChevronDown, ChevronRight, ExternalLink, Info, Trash2 } from "@multica/ui/icons";
-import { cn } from "@multica/ui/lib/utils";
-import { Button } from "@multica/ui/components/ui/button";
-import { Card, CardContent } from "@multica/ui/components/ui/card";
-import {
- Dialog,
- DialogContent,
- DialogHeader,
- DialogTitle,
-} from "@multica/ui/components/ui/dialog";
-import { Input } from "@multica/ui/components/ui/input";
-import { Label } from "@multica/ui/components/ui/label";
-import {
- AlertDialog,
- AlertDialogAction,
- AlertDialogCancel,
- AlertDialogContent,
- AlertDialogDescription,
- AlertDialogFooter,
- AlertDialogHeader,
- AlertDialogTitle,
-} from "@multica/ui/components/ui/alert-dialog";
-import {
- Tooltip,
- TooltipContent,
- TooltipProvider,
- TooltipTrigger,
-} from "@multica/ui/components/ui/tooltip";
-import { useAuthStore } from "@multica/core/auth";
-import { useWorkspaceId } from "@multica/core/hooks";
-import {
- agentListOptions,
- memberListOptions,
-} from "@multica/core/workspace/queries";
-import { DingTalkMark } from "./dingtalk-mark";
-import { useActorName } from "@multica/core/workspace/hooks";
-import {
- dingtalkGroupsOptions,
- dingtalkInstallationsOptions,
- dingtalkKeys,
-} from "@multica/core/dingtalk";
-import { api } from "@multica/core/api";
-import type {
- DingTalkGroup,
- DingTalkGroupBot,
- DingTalkInstallation,
-} from "@multica/core/types";
-import { ActorAvatar } from "../../common/actor-avatar";
-import { docsLocalePrefix } from "../../common/docs-locale";
-import { openExternal } from "../../platform";
-import { useT, useTimeAgo } from "../../i18n";
-import { TooltipHint } from "@multica/ui/components/common/tooltip-hint";
-
-const dingTalkChatManagePermission = "qyapi_chat_manage";
-
-// formatInstalledAt renders the install timestamp defensively: the schema
-// defaults installed_at to "" and the backend can emit a zero-value timestamp
-// (0001-01-01T…) for a never-set time, either of which would otherwise surface
-// as "Invalid Date" or a year-1 date. Fall back to a neutral placeholder.
-function formatInstalledAt(value: string, locale: string): string {
- const t = Date.parse(value);
- if (!value || Number.isNaN(t) || t <= 0) return "—";
- return new Intl.DateTimeFormat(locale, {
- dateStyle: "medium",
- timeStyle: "short",
- }).format(new Date(t));
-}
-
-export function getDingTalkBotIdentity(
- groups: DingTalkGroup[],
- installationId: string,
-): DingTalkGroupBot | undefined {
- const bots = groups.flatMap((group) =>
- group.bots.filter((bot) => bot.installation_id === installationId),
- );
- const identity = bots.find((bot) => bot.bot_name) ?? bots[0];
- const issue = bots.find((bot) => bot.bot_identity_issue)?.bot_identity_issue;
- return identity
- ? { ...identity, bot_identity_issue: issue ?? identity.bot_identity_issue }
- : undefined;
-}
-
-export function DingTalkConnectionLabel({
- botName,
- botIdentityIssue,
- linkedIdentityIDs = [],
- showBotIdentity = true,
- showPermissionHelp = true,
- className,
-}: {
- botName?: string;
- botIdentityIssue?: string;
- linkedIdentityIDs?: string[];
- showBotIdentity?: boolean;
- showPermissionHelp?: boolean;
- className?: string;
-}) {
- const { t } = useT("settings");
- const botIdentityText =
- botName || t(($) => $.dingtalk.bot_identity_unavailable);
- const linkedIdentityLabel =
- linkedIdentityIDs.length > 0
- ? t(($) => $.dingtalk.identity_label, {
- identity: linkedIdentityIDs.join(", "),
- })
- : "";
- const missingChatManagePermission =
- botIdentityIssue === "missing_qyapi_chat_manage";
- const permissionTooltipPrefix = t(
- ($) => $.dingtalk.bot_permission_tooltip_prefix,
- );
- const permissionTooltipSuffix = t(
- ($) => $.dingtalk.bot_permission_tooltip_suffix,
- );
- const permissionTooltip = `${permissionTooltipPrefix} ${dingTalkChatManagePermission} ${permissionTooltipSuffix}`;
- const [permissionTooltipOpen, setPermissionTooltipOpen] = useState(false);
-
- return (
- <span
- className={cn(
- "inline-flex min-w-0 items-center gap-2 text-caption text-muted-foreground",
- className,
- )}
- >
- <span
- className="inline-block h-1.5 w-1.5 shrink-0 rounded-full bg-emerald-500"
- aria-hidden="true"
- />
- <span className="inline-flex min-w-0 items-center">
- <span className="shrink-0">
- {t(($) => $.dingtalk.agent_bot_connected_label)}
- </span>
- {showBotIdentity && (
- <>
- {linkedIdentityLabel ? (
- <TooltipProvider delay={0}>
- <Tooltip>
- <TooltipTrigger
- render={
- <button
- type="button"
- className="ml-1 min-w-0 cursor-help truncate rounded-sm text-left text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
- >
- {botIdentityText}
- </button>
- }
- />
- <TooltipContent
- side="top"
- className="max-w-80 whitespace-normal break-all"
- translate="no"
- >
- {linkedIdentityLabel}
- </TooltipContent>
- </Tooltip>
- </TooltipProvider>
- ) : (
- <span className="ml-1 truncate text-foreground">
- {botIdentityText}
- </span>
- )}
- {missingChatManagePermission && showPermissionHelp && (
- <TooltipProvider delay={0}>
- <Tooltip
- open={permissionTooltipOpen}
- onOpenChange={setPermissionTooltipOpen}
- >
- <TooltipTrigger
- closeOnClick={false}
- onClick={() => setPermissionTooltipOpen(true)}
- render={
- <button
- type="button"
- className="-my-1 ml-0.5 inline-flex size-6 shrink-0 items-center justify-center rounded-sm text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
- aria-label={permissionTooltip}
- >
- <Info className="size-3.5" aria-hidden="true" />
- </button>
- }
- />
- <TooltipContent
- side="top"
- align="start"
- className="max-w-80 items-start whitespace-normal px-3 py-2"
- >
- <span className="leading-relaxed">
- {permissionTooltipPrefix}{" "}
- <code
- className="rounded-xs bg-muted px-1.5 py-0.5 font-mono text-micro text-foreground ring-1 ring-border"
- translate="no"
- >
- {dingTalkChatManagePermission}
- </code>{" "}
- {permissionTooltipSuffix}
- </span>
- </TooltipContent>
- </Tooltip>
- </TooltipProvider>
- )}
- </>
- )}
- </span>
- </span>
- );
-}
-
-export function DingTalkBotGroups({
- workspaceId,
- agentId,
- installationId,
- groups,
- inactiveCount = 0,
- canForget = false,
- isLoading,
- isError,
- onRetry,
- showDescription = true,
- className,
-}: {
- workspaceId: string;
- agentId?: string;
- installationId: string;
- groups: DingTalkGroup[];
- inactiveCount?: number;
- canForget?: boolean;
- isLoading: boolean;
- isError: boolean;
- onRetry: () => void;
- showDescription?: boolean;
- className?: string;
-}) {
- const { t } = useT("settings");
- const timeAgo = useTimeAgo();
- const qc = useQueryClient();
- const [inactiveExpanded, setInactiveExpanded] = useState(false);
- const [forgetTarget, setForgetTarget] = useState<DingTalkGroup | null>(null);
- const [forgetting, setForgetting] = useState(false);
- const inactiveQuery = useInfiniteQuery({
- queryKey: agentId
- ? dingtalkKeys.agentInactiveGroups(workspaceId, agentId, installationId)
- : dingtalkKeys.inactiveGroups(workspaceId, installationId),
- initialPageParam: 0,
- queryFn: ({ pageParam }) => {
- const params = {
- activity: "inactive" as const,
- installationId,
- offset: pageParam,
- };
- return agentId
- ? api.listAgentDingTalkGroups(agentId, params)
- : api.listDingTalkGroups(workspaceId, params);
- },
- getNextPageParam: (page) => page.next_offset,
- enabled: inactiveExpanded && inactiveCount > 0,
- });
-
- const collectObserved = (source: DingTalkGroup[]) => source
- .flatMap((group) => {
- const bot = group.bots.find(
- (candidate) => candidate.installation_id === installationId,
- );
- return bot ? [{ group, bot }] : [];
- })
- .sort((left, right) => {
- const leftActiveAt = Date.parse(left.bot.last_active_at ?? "");
- const rightActiveAt = Date.parse(right.bot.last_active_at ?? "");
- const leftIsActive = !Number.isNaN(leftActiveAt);
- const rightIsActive = !Number.isNaN(rightActiveAt);
-
- if (leftIsActive && rightIsActive && leftActiveAt !== rightActiveAt) {
- return rightActiveAt - leftActiveAt;
- }
- if (leftIsActive !== rightIsActive) return leftIsActive ? -1 : 1;
-
- const leftTitle = left.group.conversation_title;
- const rightTitle = right.group.conversation_title;
- if (leftTitle !== rightTitle) {
- if (!leftTitle) return 1;
- if (!rightTitle) return -1;
- return leftTitle < rightTitle ? -1 : 1;
- }
- if (left.group.conversation_id === right.group.conversation_id) return 0;
- return left.group.conversation_id < right.group.conversation_id ? -1 : 1;
- });
- const observed = collectObserved(groups);
- const inactiveObserved = collectObserved(
- inactiveQuery.data?.pages.flatMap((page) => page.groups) ?? [],
- );
-
- async function handleForget() {
- if (!forgetTarget || forgetting) return;
- setForgetting(true);
- try {
- await api.forgetDingTalkGroup(
- workspaceId,
- installationId,
- forgetTarget.conversation_id,
- );
- await qc.invalidateQueries({ queryKey: dingtalkKeys.groups(workspaceId) });
- toast.success(t(($) => $.dingtalk.group_forget_success));
- setForgetTarget(null);
- } catch (error) {
- toast.error(
- error instanceof Error
- ? error.message
- : t(($) => $.dingtalk.group_forget_failed),
- );
- } finally {
- setForgetting(false);
- }
- }
-
- const renderObserved = (
- entries: Array<{ group: DingTalkGroup; bot: DingTalkGroupBot }>,
- ) => (
- <div>
- {entries.map(({ group, bot }) => (
- <div
- key={group.conversation_id}
- className="group space-y-1.5 border-t py-2.5"
- data-testid="dingtalk-group-item"
- >
- <div className="flex min-w-0 items-baseline justify-between gap-3">
- <div className="flex min-w-0 flex-1 items-baseline gap-3">
- <p className="min-w-0 truncate text-caption font-medium">
- {group.conversation_title || t(($) => $.dingtalk.group_untitled)}
- </p>
- {canForget && (
- <button
- type="button"
- className="pointer-events-none shrink-0 text-micro text-muted-foreground opacity-0 underline-offset-2 transition-opacity group-hover:pointer-events-auto group-hover:opacity-100 group-focus-within:pointer-events-auto group-focus-within:opacity-100 hover:text-foreground hover:underline focus-visible:pointer-events-auto focus-visible:opacity-100"
- onClick={() => setForgetTarget(group)}
- >
- {t(($) => $.dingtalk.group_forget)}
- </button>
- )}
- </div>
- <div className="flex min-w-0 max-w-[60%] items-center">
- <TooltipProvider delay={0}>
- <Tooltip>
- <TooltipTrigger
- render={
- <code
- tabIndex={0}
- translate="no"
- aria-label={`${t(($) => $.dingtalk.conversation_id_label)} ${group.conversation_id}`}
- className="block min-w-0 truncate font-mono text-micro text-faint-foreground transition-colors group-hover:text-muted-foreground focus-visible:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
- >
- {group.conversation_id}
- </code>
- }
- />
- <TooltipContent side="top">
- {t(($) => $.dingtalk.conversation_id_label)}
- </TooltipContent>
- </Tooltip>
- </TooltipProvider>
- </div>
- </div>
- {bot.last_active_at && (
- <p
- className="text-micro tabular-nums text-muted-foreground"
- data-testid="dingtalk-group-activity"
- >
- {t(($) => $.dingtalk.group_last_active, {
- time: timeAgo(bot.last_active_at),
- })}
- <span className="mx-1.5" aria-hidden="true">·</span>
- {t(($) => $.dingtalk.group_mentions, {
- count: bot.mention_count ?? 0,
- })}
- </p>
- )}
- </div>
- ))}
- </div>
- );
-
- return (
- <div
- className={cn("space-y-2 pt-3", className)}
- data-testid="dingtalk-bot-groups"
- >
- <div className="flex items-center gap-2">
- <h4 className="text-body font-medium text-pretty">
- {t(($) => $.dingtalk.groups_title)}
- </h4>
- {!isLoading && !isError && (
- <span className="rounded-full bg-muted px-2 py-0.5 text-micro tabular-nums text-muted-foreground">
- {t(($) => $.dingtalk.groups_count, { count: observed.length })}
- </span>
- )}
- </div>
- {showDescription && (
- <p className="text-caption leading-relaxed text-muted-foreground">
- {t(($) => $.dingtalk.groups_description)}
- </p>
- )}
- {isLoading ? (
- <p className="text-caption text-muted-foreground">
- {t(($) => $.dingtalk.groups_loading)}
- </p>
- ) : isError ? (
- <div className="flex items-center justify-between gap-3" role="alert">
- <p className="text-caption text-muted-foreground">
- {t(($) => $.dingtalk.groups_error)}
- </p>
- <button
- type="button"
- className="shrink-0 text-caption font-medium underline-offset-2 hover:underline"
- onClick={onRetry}
- >
- {t(($) => $.dingtalk.groups_retry)}
- </button>
- </div>
- ) : observed.length === 0 ? (
- <p className="text-caption text-muted-foreground">
- {inactiveCount > 0
- ? t(($) => $.dingtalk.groups_no_recent)
- : t(($) => $.dingtalk.groups_empty)}
- </p>
- ) : (
- renderObserved(observed)
- )}
- {!isLoading && !isError && inactiveCount > 0 && (
- <div className="border-t pt-2">
- <button
- type="button"
- className="flex w-full items-center gap-1.5 py-1 text-caption font-medium text-muted-foreground hover:text-foreground"
- onClick={() => setInactiveExpanded((value) => !value)}
- aria-expanded={inactiveExpanded}
- >
- {inactiveExpanded
- ? <ChevronDown className="h-3.5 w-3.5" aria-hidden="true" />
- : <ChevronRight className="h-3.5 w-3.5" aria-hidden="true" />}
- {t(($) => $.dingtalk.groups_inactive, { count: inactiveCount })}
- </button>
- {inactiveExpanded && (
- <div className="pt-1">
- {inactiveQuery.isLoading ? (
- <p className="py-2 text-caption text-muted-foreground">
- {t(($) => $.dingtalk.groups_loading)}
- </p>
- ) : inactiveQuery.isError ? (
- <button
- type="button"
- className="py-2 text-caption font-medium underline-offset-2 hover:underline"
- onClick={() => void inactiveQuery.refetch()}
- >
- {t(($) => $.dingtalk.groups_retry)}
- </button>
- ) : (
- <>
- {renderObserved(inactiveObserved)}
- {inactiveQuery.hasNextPage && (
- <Button
- type="button"
- variant="ghost"
- size="sm"
- disabled={inactiveQuery.isFetchingNextPage}
- onClick={() => void inactiveQuery.fetchNextPage()}
- >
- {inactiveQuery.isFetchingNextPage
- ? t(($) => $.dingtalk.groups_loading)
- : t(($) => $.dingtalk.groups_load_more)}
- </Button>
- )}
- </>
- )}
- </div>
- )}
- </div>
- )}
- <AlertDialog
- open={!!forgetTarget}
- onOpenChange={(open) => {
- if (!open && !forgetting) setForgetTarget(null);
- }}
- >
- <AlertDialogContent>
- <AlertDialogHeader>
- <AlertDialogTitle>{t(($) => $.dingtalk.group_forget_title)}</AlertDialogTitle>
- <AlertDialogDescription>
- {t(($) => $.dingtalk.group_forget_description)}
- </AlertDialogDescription>
- </AlertDialogHeader>
- <AlertDialogFooter>
- <AlertDialogCancel disabled={forgetting}>
- {t(($) => $.dingtalk.group_forget_cancel)}
- </AlertDialogCancel>
- <AlertDialogAction onClick={handleForget} disabled={forgetting}>
- {t(($) => $.dingtalk.group_forget_confirm)}
- </AlertDialogAction>
- </AlertDialogFooter>
- </AlertDialogContent>
- </AlertDialog>
- </div>
- );
-}
-
-// DingTalkTab is the workspace settings panel for DingTalk robot installations.
-// Installation rows and group metadata follow Agent view permissions on the
-// server. Disconnect, linked Staff IDs, and permission remediation remain
-// workspace owner/admin-only in Settings.
-//
-// Adding a new installation flows through the Agent detail page: the install
-// path is per-agent (each Multica agent gets exactly one robot — the
-// (workspace_id, agent_id, channel_type) UNIQUE in channel_installation), so
-// asking the user to pick an agent here would re-create that page's picker.
-export function DingTalkTab() {
- const { t } = useT("settings");
- const wsId = useWorkspaceId();
- const qc = useQueryClient();
- const user = useAuthStore((s) => s.user);
-
- const { data: members = [] } = useQuery(memberListOptions(wsId));
- const currentMember = members.find((m) => m.user_id === user?.id) ?? null;
- const canManage =
- currentMember?.role === "owner" || currentMember?.role === "admin";
-
- const { data, isLoading } = useQuery({
- ...dingtalkInstallationsOptions(wsId),
- });
- const installations = data?.installations ?? [];
- const { data: visibleAgents = [], isLoading: agentsLoading } = useQuery({
- ...agentListOptions(wsId),
- enabled: !canManage && !!wsId,
- });
- const visibleAgentIDs = new Set(visibleAgents.map((agent) => agent.id));
- // New servers already filter this response. Keep the client-side join as a
- // compatibility guard for older servers that returned every workspace
- // installation to members, which otherwise creates Unknown Agent dead links.
- const displayedInstallations = canManage
- ? installations
- : installations.filter(
- (installation) =>
- installation.agent_available !== false &&
- visibleAgentIDs.has(installation.agent_id),
- );
- const configured = data?.configured === true;
- const {
- data: groupsData,
- isLoading: groupsLoading,
- isError: groupsError,
- refetch: retryGroups,
- } = useQuery({
- ...dingtalkGroupsOptions(wsId),
- enabled:
- configured &&
- displayedInstallations.some(
- (installation) => installation.status === "active",
- ),
- });
- const groupDiscoverySupported =
- groupsData?.group_discovery_supported === true;
- const showGroupDiscovery =
- groupDiscoverySupported || groupsLoading || groupsError;
-
- const [disconnectTarget, setDisconnectTarget] = useState<string | null>(null);
- const [disconnecting, setDisconnecting] = useState(false);
-
- async function handleDisconnect() {
- if (!disconnectTarget || disconnecting) return;
- setDisconnecting(true);
- try {
- await api.deleteDingTalkInstallation(wsId, disconnectTarget);
- await qc.invalidateQueries({ queryKey: dingtalkKeys.installations(wsId) });
- toast.success(t(($) => $.dingtalk.toast_disconnected));
- setDisconnectTarget(null);
- } catch (e) {
- toast.error(
- e instanceof Error ? e.message : t(($) => $.dingtalk.toast_disconnect_failed),
- );
- } finally {
- setDisconnecting(false);
- }
- }
-
- return (
- <div className="space-y-8">
- {!configured ? (
- <Card>
- <CardContent className="space-y-2">
- <p className="text-body font-medium">{t(($) => $.dingtalk.not_enabled_title)}</p>
- <p className="text-caption text-muted-foreground">
- {t(($) => $.dingtalk.not_enabled_description_prefix)}{" "}
- <code className="rounded-xs bg-muted px-1 py-0.5 text-micro">
- MULTICA_DINGTALK_SECRET_KEY
- </code>{" "}
- {t(($) => $.dingtalk.not_enabled_description_suffix)}{" "}
- {t(($) => $.dingtalk.not_enabled_self_host_hint)}
- </p>
- </CardContent>
- </Card>
- ) : (
- <section className="space-y-4">
- <div className="space-y-1.5">
- <h2 className="text-body font-semibold">
- {t(($) => $.dingtalk.connections_title)}
- </h2>
- </div>
- {isLoading || (!canManage && agentsLoading) ? (
- <Card>
- <CardContent>
- <p className="text-body text-muted-foreground">{t(($) => $.dingtalk.loading)}</p>
- </CardContent>
- </Card>
- ) : displayedInstallations.length === 0 ? (
- <Card>
- <CardContent className="space-y-2">
- <p className="text-body font-medium">{t(($) => $.dingtalk.empty_title)}</p>
- <p className="text-caption text-muted-foreground">
- {t(($) => $.dingtalk.empty_description_prefix)}{" "}
- <strong>{t(($) => $.dingtalk.empty_description_cta)}</strong>{" "}
- {t(($) => $.dingtalk.empty_description_suffix)}
- </p>
- </CardContent>
- </Card>
- ) : (
- <Card className="py-0">
- <CardContent className="divide-y divide-border/70">
- {displayedInstallations.map((inst) => (
- <InstallationRow
- key={inst.id}
- workspaceId={wsId}
- installation={inst}
- canManage={canManage}
- onDisconnect={() => setDisconnectTarget(inst.id)}
- groups={groupsData?.groups ?? []}
- botIdentity={groupsData?.bot_identities?.[inst.id]}
- inactiveCount={groupsData?.inactive_group_counts?.[inst.id] ?? 0}
- groupsLoading={groupsLoading}
- groupsError={groupsError}
- groupDiscoverySupported={groupDiscoverySupported}
- showGroupDiscovery={showGroupDiscovery}
- onRetryGroups={() => void retryGroups()}
- />
- ))}
- </CardContent>
- </Card>
- )}
- </section>
- )}
-
- <AlertDialog
- open={!!disconnectTarget}
- onOpenChange={(v) => {
- if (!v && !disconnecting) setDisconnectTarget(null);
- }}
- >
- <AlertDialogContent>
- <AlertDialogHeader>
- <AlertDialogTitle>
- {t(($) => $.dingtalk.disconnect_confirm_title)}
- </AlertDialogTitle>
- <AlertDialogDescription>
- {t(($) => $.dingtalk.disconnect_confirm_description)}
- </AlertDialogDescription>
- </AlertDialogHeader>
- <AlertDialogFooter>
- <AlertDialogCancel disabled={disconnecting}>
- {t(($) => $.dingtalk.disconnect_confirm_cancel)}
- </AlertDialogCancel>
- <AlertDialogAction onClick={handleDisconnect} disabled={disconnecting}>
- {disconnecting
- ? t(($) => $.dingtalk.disconnecting)
- : t(($) => $.dingtalk.disconnect)}
- </AlertDialogAction>
- </AlertDialogFooter>
- </AlertDialogContent>
- </AlertDialog>
- </div>
- );
-}
-
-function InstallationRow({
- workspaceId,
- installation,
- canManage,
- onDisconnect,
- groups,
- botIdentity: suppliedBotIdentity,
- inactiveCount,
- groupsLoading,
- groupsError,
- groupDiscoverySupported,
- showGroupDiscovery,
- onRetryGroups,
-}: {
- workspaceId: string;
- installation: DingTalkInstallation;
- canManage: boolean;
- onDisconnect: () => void;
- groups: DingTalkGroup[];
- botIdentity?: DingTalkGroupBot;
- inactiveCount: number;
- groupsLoading: boolean;
- groupsError: boolean;
- groupDiscoverySupported: boolean;
- showGroupDiscovery: boolean;
- onRetryGroups: () => void;
-}) {
- const { t, i18n } = useT("settings");
- const { getAgentName } = useActorName();
- const isActive = installation.status === "active";
- const agentAvailable = installation.agent_available !== false;
- const agentName = agentAvailable
- ? getAgentName(installation.agent_id)
- : t(($) => $.dingtalk.deleted_agent);
- const linkedIdentityIDs = canManage
- ? (installation.bound_dingtalk_user_ids ?? [])
- : [];
- const botIdentity = suppliedBotIdentity ?? getDingTalkBotIdentity(groups, installation.id);
- return (
- <div
- className="py-6"
- data-testid="dingtalk-installation-row"
- >
- <div className="flex items-start justify-between gap-6">
- <div className="flex min-w-0 items-start gap-3">
- <ActorAvatar
- actorType="agent"
- actorId={installation.agent_id}
- size="lg"
- enableHoverCard={agentAvailable}
- profileLink={agentAvailable}
- />
- <div className="min-w-0 space-y-1.5">
- <h3 className="truncate text-title-sm font-medium text-pretty">
- {agentName}
- {!isActive && (
- <span className="ml-2 rounded-xs bg-muted px-1.5 py-0.5 text-micro text-muted-foreground">
- {t(($) => $.dingtalk.revoked_badge)}
- </span>
- )}
- </h3>
- <div className="flex min-w-0 flex-wrap items-center gap-x-2 gap-y-1">
- {isActive && (
- <>
- <DingTalkConnectionLabel
- botName={botIdentity?.bot_name ?? ""}
- botIdentityIssue={botIdentity?.bot_identity_issue ?? ""}
- linkedIdentityIDs={linkedIdentityIDs}
- showBotIdentity={
- groupDiscoverySupported && !groupsLoading
- }
- showPermissionHelp={canManage}
- />
- <span
- className="text-micro text-muted-foreground"
- aria-hidden="true"
- >
- ·
- </span>
- </>
- )}
- <span
- className="text-micro text-muted-foreground"
- data-testid="dingtalk-installation-metadata"
- >
- {t(($) => $.dingtalk.installed_at_label, {
- when: formatInstalledAt(installation.installed_at, i18n.language),
- })}
- </span>
- </div>
- </div>
- </div>
- {canManage && isActive && (
- <Button variant="outline" size="sm" onClick={onDisconnect}>
- <Trash2 className="h-3 w-3" aria-hidden="true" />
- {t(($) => $.dingtalk.disconnect)}
- </Button>
- )}
- </div>
- {isActive && showGroupDiscovery && (
- <DingTalkBotGroups
- workspaceId={workspaceId}
- installationId={installation.id}
- groups={groups}
- inactiveCount={inactiveCount}
- canForget={canManage}
- isLoading={groupsLoading}
- isError={groupsError}
- onRetry={onRetryGroups}
- showDescription={false}
- className="space-y-3 pt-5"
- />
- )}
- </div>
- );
-}
-
-// dingtalkDocsUrl points at the DingTalk integration guide on the docs site,
-// localized to the viewer's language. The docs site uses /<lang>/ path
-// prefixes (English has none), matching the convention used elsewhere in the
-// app for doc links.
-function dingtalkDocsUrl(lang: string | undefined): string {
- return `https://multica.ai/docs${docsLocalePrefix(lang)}/dingtalk-bot-integration`;
-}
-
-// DingTalkAgentBindButton is the per-agent CTA exposed from the agent detail
-// page. DingTalk uses the bring-your-own-app model: the button opens a dialog
-// where an authorized manager pastes the AppKey (client id) + AppSecret (client
-// secret) of the DingTalk robot they created (the backend validates both).
-// Visibility:
-// 1. Only the agent's owner or a workspace owner/admin sees management UI.
-// 2. If this agent already has an active installation, show the connected
-// badge (already-installed robots stay manageable).
-// 3. Otherwise the Connect CTA shows whenever install is available.
-export function DingTalkAgentBindButton({
- agentId,
- agentName,
- agentOwnerId,
- botName,
- botIdentityIssue,
- className,
- onShowConnectedDetails,
-}: {
- agentId: string;
- agentName?: string;
- /** Mirrors the backend canManageAgent rule for the per-agent entry point. */
- agentOwnerId?: string | null;
- botName?: string;
- botIdentityIssue?: string;
- className?: string;
- /**
- * When set, the connected state renders as a compact read-only status row
- * that invokes this callback on click instead of the full badge with inline
- * actions — the agent inspector passes a "jump to the Integrations tab"
- * handler so management actions live in one place.
- */
- onShowConnectedDetails?: () => void;
-}) {
- const { t, i18n } = useT("settings");
- const wsId = useWorkspaceId();
- const qc = useQueryClient();
- const user = useAuthStore((s) => s.user);
-
- const [dialogOpen, setDialogOpen] = useState(false);
- const [clientId, setClientId] = useState("");
- const [clientSecret, setClientSecret] = useState("");
- const [submitting, setSubmitting] = useState(false);
-
- const { data: listing } = useQuery({
- ...dingtalkInstallationsOptions(wsId),
- });
- const installSupported = listing?.install_supported === true;
-
- const { data: members = [] } = useQuery({
- ...memberListOptions(wsId),
- enabled: !!wsId,
- });
- const currentMember = members.find((m) => m.user_id === user?.id) ?? null;
- const isWorkspaceAdmin =
- currentMember?.role === "owner" || currentMember?.role === "admin";
- const isAgentOwner =
- currentMember != null &&
- !!user?.id &&
- agentOwnerId != null &&
- agentOwnerId === user.id;
- const canManage = isWorkspaceAdmin || isAgentOwner;
-
- if (!canManage) return null;
-
- const existing = listing?.installations?.find(
- (inst) => inst.agent_id === agentId && inst.status === "active",
- );
- if (existing) {
- return onShowConnectedDetails ? (
- <DingTalkAgentBotStatusRow
- onClick={onShowConnectedDetails}
- className={className}
- />
- ) : (
- <DingTalkAgentBotConnectedBadge
- installation={existing}
- botName={botName}
- botIdentityIssue={botIdentityIssue}
- className={className}
- />
- );
- }
-
- if (!installSupported) return null;
-
- function closeDialog() {
- if (submitting) return;
- setDialogOpen(false);
- setClientId("");
- setClientSecret("");
- }
-
- async function handleSubmit() {
- const client_id = clientId.trim();
- const client_secret = clientSecret.trim();
- if (submitting || !agentId || !client_id || !client_secret) return;
- setSubmitting(true);
- try {
- await api.registerDingTalkBYO(wsId, agentId, { client_id, client_secret });
- // The dingtalk_installation realtime event also refreshes this list, but
- // invalidate explicitly so the connected badge appears immediately.
- await qc.invalidateQueries({ queryKey: dingtalkKeys.installations(wsId) });
- toast.success(t(($) => $.dingtalk.byo_success_toast));
- setDialogOpen(false);
- setClientId("");
- setClientSecret("");
- } catch (e) {
- toast.error(
- e instanceof Error ? e.message : t(($) => $.dingtalk.byo_failed_toast),
- );
- } finally {
- setSubmitting(false);
- }
- }
-
- const canSubmit =
- clientId.trim() !== "" && clientSecret.trim() !== "" && !submitting;
-
- return (
- <div
- className={cn("flex flex-wrap items-center gap-2", className)}
- data-testid="dingtalk-agent-bind-buttons"
- >
- <TooltipHint
- label={
- agentName
- ? t(($) => $.dingtalk.bind_button_title, { agent: agentName })
- : undefined
- }
- >
- <Button
- variant="outline"
- size="sm"
- onClick={() => setDialogOpen(true)}
- disabled={!agentId}
- data-testid="dingtalk-agent-connect"
- >
- <DingTalkMark className="h-4 w-4" />
- {t(($) => $.dingtalk.bind_button)}
- </Button>
- </TooltipHint>
-
- <Dialog
- open={dialogOpen}
- onOpenChange={(v) => (v ? setDialogOpen(true) : closeDialog())}
- >
- <DialogContent
- className="gap-0 overflow-hidden p-0 sm:max-w-lg"
- data-testid="dingtalk-byo-dialog"
- >
- <DialogHeader className="gap-1 border-b px-5 py-3">
- <DialogTitle className="text-title-sm font-semibold">
- {t(($) => $.dingtalk.byo_dialog_title)}
- </DialogTitle>
-
- <button
- type="button"
- onClick={() => openExternal(dingtalkDocsUrl(i18n.language))}
- className="inline-flex w-fit items-center gap-1.5 text-caption text-muted-foreground underline-offset-2 transition-colors hover:text-foreground hover:underline"
- data-testid="dingtalk-byo-docs-link"
- >
- <ExternalLink className="h-3.5 w-3.5" aria-hidden="true" />
- {t(($) => $.dingtalk.byo_docs_link)}
- </button>
- </DialogHeader>
-
- <div className="space-y-4 p-5">
- <div className="space-y-1.5">
- <Label
- htmlFor="dingtalk-byo-client-id"
- className="text-caption text-muted-foreground"
- >
- {t(($) => $.dingtalk.byo_appkey_label)}
- </Label>
- <Input
- id="dingtalk-byo-client-id"
- data-testid="dingtalk-byo-client-id"
- type="password"
- value={clientId}
- onChange={(e) => setClientId(e.target.value)}
- autoComplete="off"
- spellCheck={false}
- disabled={submitting}
- />
- </div>
-
- <div className="space-y-1.5">
- <Label
- htmlFor="dingtalk-byo-client-secret"
- className="text-caption text-muted-foreground"
- >
- {t(($) => $.dingtalk.byo_appsecret_label)}
- </Label>
- <Input
- id="dingtalk-byo-client-secret"
- data-testid="dingtalk-byo-client-secret"
- type="password"
- value={clientSecret}
- onChange={(e) => setClientSecret(e.target.value)}
- autoComplete="off"
- spellCheck={false}
- disabled={submitting}
- />
- </div>
- </div>
-
- {/* Inline footer instead of <DialogFooter>: its -mx-4/-mb-4 offsets
- assume the default p-4 DialogContent; with p-0 they push the bar
- outside the dialog. */}
- <div className="flex items-center justify-end gap-2 border-t bg-background px-5 py-3">
- <Button variant="ghost" onClick={closeDialog} disabled={submitting}>
- {t(($) => $.dingtalk.byo_cancel)}
- </Button>
- <Button
- onClick={handleSubmit}
- disabled={!canSubmit}
- data-testid="dingtalk-byo-submit"
- >
- {submitting
- ? t(($) => $.dingtalk.byo_submitting)
- : t(($) => $.dingtalk.byo_submit)}
- </Button>
- </div>
- </DialogContent>
- </Dialog>
- </div>
- );
-}
-
-// DingTalkAgentBotStatusRow is the compact, read-only connected affordance the
-// agent inspector renders instead of the full badge; it deep-links into the
-// Integrations tab where Manage / Disconnect live.
-function DingTalkAgentBotStatusRow({
- onClick,
- className,
-}: {
- onClick: () => void;
- className?: string;
-}) {
- return (
- <button
- type="button"
- onClick={onClick}
- className={cn(
- "flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-caption text-muted-foreground transition-colors hover:bg-muted focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/50",
- className,
- )}
- data-testid="dingtalk-agent-bot-status"
- >
- <DingTalkConnectionLabel showBotIdentity={false} />
- <ChevronRight
- className="ml-auto h-3.5 w-3.5 shrink-0"
- aria-hidden="true"
- />
- </button>
- );
-}
-
-// DingTalkAgentBotConnectedBadge is the full "already connected" affordance the
-// Integrations tab renders in place of the Connect button: a status row plus a
-// soft-destructive Disconnect. Only owners/admins ever reach this component.
-function DingTalkAgentBotConnectedBadge({
- installation,
- botName,
- botIdentityIssue,
- className,
-}: {
- installation: DingTalkInstallation;
- botName?: string;
- botIdentityIssue?: string;
- className?: string;
-}) {
- const { t } = useT("settings");
- const wsId = useWorkspaceId();
- const qc = useQueryClient();
-
- const [confirmOpen, setConfirmOpen] = useState(false);
- const [disconnecting, setDisconnecting] = useState(false);
-
- async function handleDisconnect() {
- if (disconnecting) return;
- setDisconnecting(true);
- try {
- await api.deleteDingTalkInstallation(wsId, installation.id);
- await qc.invalidateQueries({ queryKey: dingtalkKeys.installations(wsId) });
- toast.success(t(($) => $.dingtalk.toast_disconnected));
- setConfirmOpen(false);
- } catch (e) {
- toast.error(
- e instanceof Error ? e.message : t(($) => $.dingtalk.toast_disconnect_failed),
- );
- } finally {
- setDisconnecting(false);
- }
- }
-
- return (
- <div
- className={cn("space-y-2", className)}
- data-testid="dingtalk-agent-bot-connected"
- >
- <div className="flex items-center justify-between gap-3">
- <DingTalkConnectionLabel
- botName={botName}
- botIdentityIssue={botIdentityIssue}
- showBotIdentity={botName !== undefined || botIdentityIssue !== undefined}
- />
- <TooltipHint label={t(($) => $.dingtalk.agent_bot_disconnect_tooltip)}>
- <Button
- variant="destructive"
- size="sm"
- onClick={() => setConfirmOpen(true)}
- disabled={disconnecting}
- aria-label={t(($) => $.dingtalk.disconnect)}
- data-testid="dingtalk-agent-bot-disconnect"
- >
- <Trash2 className="h-3 w-3" aria-hidden="true" />
- {disconnecting
- ? t(($) => $.dingtalk.disconnecting)
- : t(($) => $.dingtalk.disconnect)}
- </Button>
- </TooltipHint>
- </div>
-
- <AlertDialog
- open={confirmOpen}
- onOpenChange={(v) => {
- if (!v && !disconnecting) setConfirmOpen(false);
- }}
- >
- <AlertDialogContent>
- <AlertDialogHeader>
- <AlertDialogTitle>
- {t(($) => $.dingtalk.disconnect_confirm_title)}
- </AlertDialogTitle>
- <AlertDialogDescription>
- {t(($) => $.dingtalk.disconnect_confirm_description)}
- </AlertDialogDescription>
- </AlertDialogHeader>
- <AlertDialogFooter>
- <AlertDialogCancel disabled={disconnecting}>
- {t(($) => $.dingtalk.disconnect_confirm_cancel)}
- </AlertDialogCancel>
- <AlertDialogAction onClick={handleDisconnect} disabled={disconnecting}>
- {disconnecting
- ? t(($) => $.dingtalk.disconnecting)
- : t(($) => $.dingtalk.disconnect)}
- </AlertDialogAction>
- </AlertDialogFooter>
- </AlertDialogContent>
- </AlertDialog>
- </div>
- );
-}
diff --git a/packages/views/settings/components/lark-channel-authorization.test.tsx b/packages/views/settings/components/lark-channel-authorization.test.tsx
new file mode 100644
index 0000000000..7a3289d68e
--- /dev/null
+++ b/packages/views/settings/components/lark-channel-authorization.test.tsx
@@ -0,0 +1,168 @@
+import { StrictMode, type ReactNode } from "react";
+import { describe, it, expect, beforeEach, afterEach, vi } from "vitest";
+import { act, render, screen, waitFor } from "@testing-library/react";
+import { I18nProvider } from "@multica/core/i18n/react";
+import { ApiError } from "@multica/core/api";
+import enSettings from "../../locales/en/settings.json";
+import { LarkChannelAuthorization } from "./lark-channel-authorization";
+const mockBeginInstall = vi.hoisted(() => vi.fn());
+const mockGetStatus = vi.hoisted(() => vi.fn());
+const mockInvalidate = vi.hoisted(() => vi.fn());
+vi.mock("@tanstack/react-query", () => ({
+ useQueryClient: () => ({ invalidateQueries: mockInvalidate }),
+}));
+vi.mock("@multica/core/lark", () => ({
+ larkKeys: { installations: (id: string) => ["lark", id, "installations"] },
+}));
+vi.mock("@multica/core/api", async (original) => ({
+ ...(await original<typeof import("@multica/core/api")>()),
+ api: {
+ beginLarkInstall: mockBeginInstall,
+ getLarkInstallStatus: mockGetStatus,
+ },
+}));
+vi.mock("sonner", () => ({
+ toast: { success: vi.fn(), error: vi.fn(), message: vi.fn() },
+}));
+vi.mock("react-qr-code", () => ({
+ QRCode: ({ value }: { value: string }) => (
+ <span data-testid="qr-code" data-value={value} />
+ ),
+}));
+function I18nWrapper({ children }: { children: ReactNode }) {
+ return (
+ <I18nProvider locale="en" resources={{ en: { settings: enSettings } }}>
+ {children}
+ </I18nProvider>
+ );
+}
+function StrictModeWrapper({ children }: { children: ReactNode }) {
+ return (
+ <StrictMode>
+ <I18nWrapper>{children}</I18nWrapper>
+ </StrictMode>
+ );
+}
+function resetFixtures() {
+ vi.clearAllMocks();
+}
+
+describe("LarkInstallDialog (polling terminal errors)", () => {
+ beforeEach(() => {
+ resetFixtures();
+ vi.useFakeTimers({ shouldAdvanceTime: true });
+ mockBeginInstall.mockResolvedValue({
+ session_id: "sess-1",
+ qr_code_url: "https://accounts.feishu.cn/oauth/v1/device?u=abc",
+ expires_in_seconds: 300,
+ poll_interval_seconds: 2,
+ });
+ });
+
+ afterEach(() => {
+ vi.useRealTimers();
+ });
+
+ async function openDialog() {
+ render(
+ <LarkChannelAuthorization
+ wsId="workspace-1"
+ agentId="agent-1"
+ region="feishu"
+ onClose={vi.fn()}
+ />,
+ {
+ wrapper: I18nWrapper,
+ },
+ );
+ // Let the begin-session promise resolve and the QR render.
+ await waitFor(() => {
+ expect(screen.getByTestId("qr-code")).toBeTruthy();
+ });
+ }
+
+ it("falls into a terminal session_lost error state when status polling 404s instead of looping forever", async () => {
+ mockGetStatus.mockRejectedValue(
+ new ApiError("install session not found", 404, "Not Found"),
+ );
+
+ await openDialog();
+ // Drive the polling timer (intervalMs = max(2000, 2*1000)) and let
+ // the rejected promise propagate into the catch.
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(2100);
+ });
+
+ await waitFor(() => {
+ expect(
+ screen.getByText(
+ /Install session expired or was lost\. Scan again to start over\./i,
+ ),
+ ).toBeTruthy();
+ });
+ expect(screen.getByRole("button", { name: /Scan again/i })).toBeTruthy();
+ // The dialog renders multiple Close affordances (footer button + the
+ // built-in dialog dismiss); we only need to confirm at least one is
+ // mounted alongside the retry button.
+ expect(
+ screen.getAllByRole("button", { name: /Close/i }).length,
+ ).toBeGreaterThan(0);
+ });
+
+ it("treats 403 as a terminal forbidden error state (no infinite retry on revoked permission)", async () => {
+ mockGetStatus.mockRejectedValue(
+ new ApiError("forbidden", 403, "Forbidden"),
+ );
+
+ await openDialog();
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(2100);
+ });
+
+ await waitFor(() => {
+ expect(
+ screen.getByText(
+ /You no longer have permission to install Lark Bots in this workspace/i,
+ ),
+ ).toBeTruthy();
+ });
+ // Drive another full poll interval — the polling loop must NOT
+ // schedule a follow-up fetch after a terminal 4xx.
+ const callsAfterTerminal = mockGetStatus.mock.calls.length;
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(5000);
+ });
+ expect(mockGetStatus.mock.calls.length).toBe(callsAfterTerminal);
+ });
+
+ it("renders the QR after a React StrictMode double-mount (regression for empty dialog body)", async () => {
+ render(
+ <LarkChannelAuthorization
+ wsId="workspace-1"
+ agentId="agent-1"
+ region="feishu"
+ onClose={vi.fn()}
+ />,
+ {
+ wrapper: StrictModeWrapper,
+ },
+ );
+
+ // The QR must appear even though the dialog mounted, unmounted, and
+ // mounted again under StrictMode. The previous bug left the body
+ // empty here.
+ await waitFor(
+ () => {
+ expect(screen.getByTestId("qr-code")).toBeTruthy();
+ },
+ { timeout: 2000 },
+ );
+
+ // And the QR's value should match what the (latest) begin call
+ // returned — not be empty / undefined.
+ const qr = screen.getByTestId("qr-code");
+ expect(qr.getAttribute("data-value")).toBe(
+ "https://accounts.feishu.cn/oauth/v1/device?u=abc",
+ );
+ });
+});
diff --git a/packages/views/settings/components/lark-channel-authorization.tsx b/packages/views/settings/components/lark-channel-authorization.tsx
new file mode 100644
index 0000000000..5dabc6569d
--- /dev/null
+++ b/packages/views/settings/components/lark-channel-authorization.tsx
@@ -0,0 +1,272 @@
+"use client";
+
+import { useEffect, useRef, useState } from "react";
+import { useQueryClient } from "@tanstack/react-query";
+import { toast } from "sonner";
+import { QRCode } from "react-qr-code";
+import { RefreshCw } from "@multica/ui/icons";
+import { Button } from "@multica/ui/components/ui/button";
+import { DialogFooter } from "@multica/ui/components/ui/dialog";
+import { api, ApiError } from "@multica/core/api";
+import { larkKeys } from "@multica/core/lark";
+import type { LarkInstallStatusResponse } from "@multica/core/types";
+import { useT } from "../../i18n";
+
+export function LarkChannelAuthorization({
+ wsId,
+ agentId,
+ region,
+ onClose,
+}: {
+ wsId: string;
+ agentId: string;
+ region: "feishu" | "lark";
+ onClose: () => void;
+}) {
+ const { t } = useT("settings");
+ const qc = useQueryClient();
+
+ // We track session lifecycle as local state because TanStack Query is
+ // optimized for cached server reads, and this dialog is a one-shot
+ // flow whose entire state collapses on close. Using `useQuery` for
+ // the polling would also fight TanStack's default refetch heuristics
+ // (window focus, online/offline, retries) that have the wrong shape
+ // for a single bounded session.
+ const [session, setSession] = useState<null | {
+ sessionId: string;
+ qrCodeURL: string;
+ expiresInSeconds: number;
+ pollIntervalSeconds: number;
+ }>(null);
+ const [status, setStatus] =
+ useState<LarkInstallStatusResponse["status"]>("pending");
+ const [errorReason, setErrorReason] = useState<string | null>(null);
+ const [errorMessage, setErrorMessage] = useState<string | null>(null);
+ const [beginning, setBeginning] = useState(false);
+ const closedRef = useRef(false);
+
+ // beginSession is callable from both the initial mount and the
+ // "scan again" action. Wrapping in a function (instead of a useEffect
+ // dependency cascade) makes the retry path explicit.
+ async function beginSession() {
+ setBeginning(true);
+ setStatus("pending");
+ setErrorReason(null);
+ setErrorMessage(null);
+ setSession(null);
+ try {
+ const res = await api.beginLarkInstall(wsId, agentId, region);
+ if (closedRef.current) return;
+ setSession({
+ sessionId: res.session_id,
+ qrCodeURL: res.qr_code_url,
+ expiresInSeconds: res.expires_in_seconds,
+ pollIntervalSeconds: res.poll_interval_seconds,
+ });
+ } catch (e) {
+ if (closedRef.current) return;
+ setStatus("error");
+ setErrorReason("internal_error");
+ setErrorMessage(e instanceof Error ? e.message : String(e));
+ } finally {
+ setBeginning(false);
+ }
+ }
+
+ // Kick off on mount.
+ //
+ // Reset closedRef AT THE START of every mount, not just at construction.
+ // React 18+ / 19 StrictMode dev runs effects twice (mount → cleanup →
+ // mount) on the same component instance, which preserves useRef across
+ // the simulated remount. Without resetting, the cleanup from mount #1
+ // flips closedRef.current=true, and on mount #2 every beginSession
+ // promise sees closedRef=true at the await boundary and early-exits
+ // before calling setSession — leaving the dialog body empty (no
+ // "starting" placeholder, no QR, no error), which is exactly the
+ // "QR never appears" bug. Reset on entry so the second mount
+ // re-arms the in-flight cancellation guard.
+ useEffect(() => {
+ closedRef.current = false;
+ void beginSession();
+ return () => {
+ closedRef.current = true;
+ };
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, []);
+
+ // Polling loop. Bounded by the device-flow expiry — once that
+ // elapses Lark's server returns expired_token and our backend marks
+ // the session errored, so we don't need a separate client-side
+ // expiry timer.
+ useEffect(() => {
+ if (!session || status !== "pending") return;
+ const intervalMs = Math.max(2000, session.pollIntervalSeconds * 1000);
+ let cancelled = false;
+ let timer: ReturnType<typeof setTimeout> | null = null;
+
+ const poll = async () => {
+ if (cancelled) return;
+ try {
+ const res = await api.getLarkInstallStatus(wsId, session.sessionId);
+ if (cancelled) return;
+ setStatus(res.status);
+ if (res.status === "success") {
+ await qc.invalidateQueries({
+ queryKey: larkKeys.installations(wsId),
+ });
+ toast.success(t(($) => $.channels.connect_success));
+ return;
+ }
+ if (res.status === "error") {
+ setErrorReason(res.error_reason ?? "internal_error");
+ setErrorMessage(res.error_message ?? null);
+ return;
+ }
+ timer = setTimeout(poll, intervalMs);
+ } catch (e) {
+ if (cancelled) return;
+ // Terminal HTTP states must NOT be retried — the session is
+ // gone or the caller has lost permission, and polling forever
+ // would trap the user on a stale QR with no error feedback.
+ // 404: server restarted, multi-instance routed elsewhere, or
+ // the in-process GC swept the session. Treat as session
+ // lost — user has to scan a fresh QR.
+ // 403: permission revoked mid-session (role downgrade, etc.).
+ // The CTA gate prevents this on entry, but a role change
+ // while the dialog is open would land here.
+ // 401: the global ApiClient interceptor handles re-auth, so
+ // reaching the catch with 401 means re-auth itself
+ // failed — treat as terminal so the user doesn't loop.
+ if (e instanceof ApiError) {
+ if (e.status === 404) {
+ setStatus("error");
+ setErrorReason("session_lost");
+ setErrorMessage(e.message);
+ return;
+ }
+ if (e.status === 403 || e.status === 401) {
+ setStatus("error");
+ setErrorReason("forbidden");
+ setErrorMessage(e.message);
+ return;
+ }
+ }
+ // Transient errors (network blip, 5xx) — schedule another
+ // poll rather than killing the session. The next backend
+ // status read will either confirm pending or surface the
+ // terminal error the polling goroutine recorded.
+ timer = setTimeout(poll, intervalMs);
+ // Surface the message as a non-blocking toast for diagnostics.
+ toast.message(
+ t(($) => $.lark.install_poll_retry),
+ {
+ description: e instanceof Error ? e.message : String(e),
+ },
+ );
+ }
+ };
+
+ timer = setTimeout(poll, intervalMs);
+ return () => {
+ cancelled = true;
+ if (timer) clearTimeout(timer);
+ };
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [session?.sessionId, status]);
+
+ useEffect(() => {
+ if (status !== "success") return;
+ const timer = setTimeout(onClose, 800);
+ return () => clearTimeout(timer);
+ }, [status, onClose]);
+
+ return (
+ <>
+ <div className="flex flex-col items-center gap-4 py-2">
+ {beginning && !session && (
+ <p className="text-body text-muted-foreground">
+ {t(($) => $.lark.install_starting)}
+ </p>
+ )}
+
+ {session && status === "pending" && (
+ <>
+ <div className="rounded-md border bg-white p-3">
+ {/* react-qr-code renders an inline SVG — no external
+ network image dependency, prints at any DPI. */}
+ <QRCode value={session.qrCodeURL} size={192} />
+ </div>
+ <a
+ href={session.qrCodeURL}
+ target="_blank"
+ rel="noopener noreferrer"
+ className="text-caption underline text-muted-foreground"
+ >
+ {region === "lark"
+ ? t(($) => $.lark.install_open_link_fallback_lark)
+ : t(($) => $.lark.install_open_link_fallback_feishu)}
+ </a>
+ </>
+ )}
+
+ {status === "success" && (
+ <p className="text-body font-medium">
+ {t(($) => $.channels.waiting_message)}
+ </p>
+ )}
+
+ {status === "error" && (
+ <div className="space-y-2 text-center">
+ <p className="text-body font-medium text-destructive">
+ {(() => {
+ switch (errorReason) {
+ case "expired":
+ return t(($) => $.lark.install_error_expired);
+ case "access_denied":
+ return t(($) => $.lark.install_error_access_denied);
+ case "lark_protocol_error":
+ return t(($) => $.lark.install_error_protocol);
+ case "bot_info_failed":
+ return t(($) => $.lark.install_error_bot_info);
+ case "installation_conflict":
+ return t(($) => $.lark.install_error_conflict);
+ case "installer_bind_failed":
+ return t(($) => $.lark.install_error_installer_bind);
+ case "session_lost":
+ return t(($) => $.lark.install_error_session_lost);
+ case "forbidden":
+ return t(($) => $.lark.install_error_forbidden);
+ default:
+ return t(($) => $.lark.install_error_generic);
+ }
+ })()}
+ </p>
+ {errorMessage && (
+ <p className="text-micro text-muted-foreground break-all">
+ {errorMessage}
+ </p>
+ )}
+ </div>
+ )}
+ </div>
+
+ <DialogFooter>
+ {status === "error" ? (
+ <>
+ <Button variant="outline" size="sm" onClick={onClose}>
+ {t(($) => $.lark.install_close)}
+ </Button>
+ <Button size="sm" onClick={beginSession} disabled={beginning}>
+ <RefreshCw className="h-3 w-3" />
+ {t(($) => $.lark.install_retry)}
+ </Button>
+ </>
+ ) : (
+ <Button variant="outline" size="sm" onClick={onClose}>
+ {t(($) => $.lark.install_close)}
+ </Button>
+ )}
+ </DialogFooter>
+ </>
+ );
+}
diff --git a/packages/views/settings/components/lark-tab.test.tsx b/packages/views/settings/components/lark-tab.test.tsx
deleted file mode 100644
index cef9193f94..0000000000
--- a/packages/views/settings/components/lark-tab.test.tsx
+++ /dev/null
@@ -1,809 +0,0 @@
-import { StrictMode, type ReactNode } from "react";
-import { describe, it, expect, beforeEach, afterEach, vi } from "vitest";
-import { act, render, screen, waitFor } from "@testing-library/react";
-import userEvent from "@testing-library/user-event";
-import { I18nProvider } from "@multica/core/i18n/react";
-import enCommon from "../../locales/en/common.json";
-import enSettings from "../../locales/en/settings.json";
-
-// ApiError is re-exported from @multica/core/api; we mock the api module
-// itself but still need a real ApiError class so `e instanceof ApiError`
-// in the polling catch behaves the way it does at runtime.
-const ApiError = vi.hoisted(() => {
- class ApiError extends Error {
- readonly status: number;
- readonly statusText: string;
- readonly body?: unknown;
- constructor(message: string, status: number, statusText = "", body?: unknown) {
- super(message);
- this.name = "ApiError";
- this.status = status;
- this.statusText = statusText;
- this.body = body;
- }
- }
- return ApiError;
-});
-
-const mockBeginInstall = vi.hoisted(() => vi.fn());
-const mockGetStatus = vi.hoisted(() => vi.fn());
-const mockDeleteInstallation = vi.hoisted(() => vi.fn());
-const mockInvalidate = vi.hoisted(() => vi.fn());
-
-type MemberRole = "owner" | "admin" | "member" | "guest";
-
-const membersRef = vi.hoisted(() => ({
- current: [{ user_id: "user-1", role: "owner" as MemberRole }],
-}));
-const installationsRef = vi.hoisted(() => ({
- current: {
- installations: [] as unknown[],
- configured: true,
- install_supported: true,
- },
-}));
-
-vi.mock("@tanstack/react-query", () => ({
- useQuery: (opts: { queryKey: unknown[]; enabled?: boolean }) => {
- if (opts.enabled === false) return { data: undefined, isLoading: false };
- const key = JSON.stringify(opts.queryKey);
- if (key.includes("members")) return { data: membersRef.current, isLoading: false };
- if (key.includes("installations")) {
- return { data: installationsRef.current, isLoading: false };
- }
- return { data: undefined, isLoading: false };
- },
- useQueryClient: () => ({
- invalidateQueries: mockInvalidate,
- }),
- queryOptions: <T,>(opts: T) => opts,
-}));
-
-vi.mock("@multica/core/hooks", () => ({
- useWorkspaceId: () => "workspace-1",
-}));
-
-vi.mock("@multica/core/workspace/queries", () => ({
- memberListOptions: () => ({ queryKey: ["members"], queryFn: vi.fn() }),
-}));
-
-// useActorName is the workspace-wide identity helper. The Installation
-// row uses it to render the Multica agent's name in place of the raw
-// Lark app_id. Stubbing it here decouples LarkTab tests from the agent
-// list query plumbing.
-const agentNameByIdRef = vi.hoisted(() => ({
- current: new Map<string, string>(),
-}));
-vi.mock("@multica/core/workspace/hooks", () => ({
- useActorName: () => ({
- getAgentName: (agentId: string) =>
- agentNameByIdRef.current.get(agentId) ?? "Unknown Agent",
- getMemberName: () => "Unknown",
- getSquadName: () => "Unknown Squad",
- getActorName: () => "Unknown",
- getActorInitials: () => "??",
- getActorAvatarUrl: () => null,
- }),
-}));
-
-// ActorAvatar pulls in a deep tree (hover cards, presence query, paths).
-// In LarkTab tests we only care that the row identifies the correct
-// agent — render a tiny stub that surfaces actorId in the DOM so the
-// agent-identity assertion can read it directly.
-vi.mock("../../common/actor-avatar", () => ({
- ActorAvatar: ({ actorType, actorId }: { actorType: string; actorId: string }) => (
- <span data-testid="actor-avatar" data-actor-type={actorType} data-actor-id={actorId} />
- ),
-}));
-
-vi.mock("@multica/core/lark", () => ({
- larkInstallationsOptions: () => ({
- queryKey: ["lark", "installations"],
- queryFn: vi.fn(),
- }),
- larkKeys: { installations: (wsId: string) => ["lark", "installations", wsId] },
-}));
-
-vi.mock("@multica/core/api", () => ({
- api: {
- beginLarkInstall: mockBeginInstall,
- getLarkInstallStatus: mockGetStatus,
- deleteLarkInstallation: mockDeleteInstallation,
- },
- ApiError,
-}));
-
-vi.mock("@multica/core/auth", () => {
- const useAuthStore = Object.assign(
- (sel?: (s: { user: { id: string } }) => unknown) =>
- sel ? sel({ user: { id: "user-1" } }) : { user: { id: "user-1" } },
- { getState: () => ({ user: { id: "user-1" } }) },
- );
- return { useAuthStore };
-});
-
-vi.mock("sonner", () => ({
- toast: {
- success: vi.fn(),
- error: vi.fn(),
- message: vi.fn(),
- },
-}));
-
-// react-qr-code renders SVG that jsdom doesn't fully support — a stub
-// keeps the dialog DOM compact and lets us assert on the surrounding
-// chrome (status text, buttons) without QR mechanics.
-// Expose the stub as BOTH the named `QRCode` export (what lark-tab now
-// imports — see the named-import interop fix) and `default`, so the mock
-// stays correct regardless of how the component pulls it in. The stub is
-// defined inside the factory because vi.mock is hoisted above any
-// top-level variable.
-vi.mock("react-qr-code", () => {
- const QrStub = ({ value }: { value: string }) => (
- <span data-testid="qr-code" data-value={value} />
- );
- return { QRCode: QrStub, default: QrStub };
-});
-
-import { LarkAgentBindButton, LarkTab } from "./lark-tab";
-import { toast } from "sonner";
-
-const TEST_RESOURCES = {
- en: { common: enCommon, settings: enSettings },
-};
-
-function I18nWrapper({ children }: { children: ReactNode }) {
- return (
- <I18nProvider locale="en" resources={TEST_RESOURCES}>
- {children}
- </I18nProvider>
- );
-}
-
-// StrictMode wrapper used to reproduce the dev-mode mount → unmount →
-// remount cycle. React 19 dev runs this on every component, which
-// surfaces effect cleanup bugs that don't show in production builds.
-function StrictModeWrapper({ children }: { children: ReactNode }) {
- return (
- <StrictMode>
- <I18nProvider locale="en" resources={TEST_RESOURCES}>
- {children}
- </I18nProvider>
- </StrictMode>
- );
-}
-
-function resetFixtures() {
- vi.clearAllMocks();
- membersRef.current = [{ user_id: "user-1", role: "owner" }];
- installationsRef.current = {
- installations: [],
- configured: true,
- install_supported: true,
- };
- agentNameByIdRef.current = new Map();
-}
-
-describe("LarkAgentBindButton (CTA gate)", () => {
- beforeEach(resetFixtures);
-
- it("shows the Feishu bind CTA but hides the Lark CTA for an owner (MUL-3083)", () => {
- // Mainland Feishu binding stays available; the Lark (international)
- // entry is temporarily hidden via LARK_INTL_CONNECT_ENABLED while its
- // install→inbound pipeline is stabilized (MUL-3083).
- render(<LarkAgentBindButton agentId="agent-1" agentName="Bot" />, {
- wrapper: I18nWrapper,
- });
- expect(screen.getByRole("button", { name: /Bind to Feishu/i })).toBeTruthy();
- expect(screen.queryByRole("button", { name: /Bind to Lark/i })).toBeNull();
- });
-
- it("shows the Feishu bind CTA but hides the Lark CTA for an admin (MUL-3083)", () => {
- membersRef.current = [{ user_id: "user-1", role: "admin" }];
- render(<LarkAgentBindButton agentId="agent-1" agentName="Bot" />, {
- wrapper: I18nWrapper,
- });
- expect(screen.getByRole("button", { name: /Bind to Feishu/i })).toBeTruthy();
- expect(screen.queryByRole("button", { name: /Bind to Lark/i })).toBeNull();
- });
-
- it("hides both bind CTAs for a plain member when no agentOwnerId is supplied (stays admin-only)", () => {
- membersRef.current = [{ user_id: "user-1", role: "member" }];
- const { container } = render(
- <LarkAgentBindButton agentId="agent-1" agentName="Bot" />,
- { wrapper: I18nWrapper },
- );
- expect(container.querySelector("button")).toBeNull();
- });
-
- it("shows the Feishu bind CTA for a non-admin agent owner (agentOwnerId matches the user, MUL-4213)", () => {
- // The backend authorizes the agent's owner via canManageAgent even when
- // they are only a plain workspace member, so the CTA must render for
- // them once the caller threads the agent's owner_id.
- membersRef.current = [{ user_id: "user-1", role: "member" }];
- render(
- <LarkAgentBindButton
- agentId="agent-1"
- agentName="Bot"
- agentOwnerId="user-1"
- />,
- { wrapper: I18nWrapper },
- );
- expect(screen.getByRole("button", { name: /Bind to Feishu/i })).toBeTruthy();
- });
-
- it("still hides the CTAs for a non-admin member who is NOT the agent owner", () => {
- // agentOwnerId belongs to someone else, so a plain member gets nothing.
- membersRef.current = [{ user_id: "user-1", role: "member" }];
- const { container } = render(
- <LarkAgentBindButton
- agentId="agent-1"
- agentName="Bot"
- agentOwnerId="user-2"
- />,
- { wrapper: I18nWrapper },
- );
- expect(container.querySelector("button")).toBeNull();
- });
-
- it("hides both bind CTAs when the device-flow install path is not wired on the server", () => {
- installationsRef.current.install_supported = false;
- const { container } = render(
- <LarkAgentBindButton agentId="agent-1" agentName="Bot" />,
- { wrapper: I18nWrapper },
- );
- expect(container.querySelector("button")).toBeNull();
- });
-
- it("clicking Bind to Feishu begins an install with region='feishu'", async () => {
- // Pin the routing wire-up: each split CTA must pass its own region
- // string to the API client (which threads it onto the
- // /lark/install/begin?region=… query param), so the device-flow
- // begins on the matching accounts host. A regression here would
- // silently send Lark users to a Feishu QR — the exact bug this
- // refactor addresses.
- const user = userEvent.setup();
- mockBeginInstall.mockResolvedValue({
- session_id: "sess-feishu",
- qr_code_url: "https://accounts.feishu.cn/oauth/v1/device?u=feishu",
- expires_in_seconds: 300,
- poll_interval_seconds: 2,
- });
- mockGetStatus.mockResolvedValue({ status: "pending" });
- render(<LarkAgentBindButton agentId="agent-1" agentName="Bot" />, {
- wrapper: I18nWrapper,
- });
- await user.click(screen.getByRole("button", { name: /Bind to Feishu/i }));
- await waitFor(() => {
- expect(mockBeginInstall).toHaveBeenCalledTimes(1);
- });
- expect(mockBeginInstall).toHaveBeenCalledWith(
- "workspace-1",
- "agent-1",
- "feishu",
- );
- });
-
- // NOTE (MUL-3083): the "clicking Bind to Lark begins an install with
- // region='lark'" test was removed alongside the temporarily-hidden Lark
- // (international) CTA — there is no Lark button to click while
- // LARK_INTL_CONNECT_ENABLED is false. The Feishu region routing is still
- // pinned by the "clicking Bind to Feishu …" test above; restore the Lark
- // case when the entry is re-enabled.
-
- it("swaps the bind CTAs for a 'Connected + Manage in Lark' badge when this agent already has an active installation", () => {
- // Anti-zombie guard: re-scanning the same agent upserts the row
- // and orphans the previously-created Lark PersonalAgent. The badge
- // closes the install entry point and links the user to the Bot's
- // dev console page where scopes / display name / additional
- // permissions are actually managed.
- installationsRef.current.installations = [
- {
- id: "inst-1",
- workspace_id: "ws-1",
- agent_id: "agent-1",
- app_id: "cli_existing_app",
- bot_open_id: "ou_existing_bot",
- installer_user_id: "user-1",
- status: "active",
- installed_at: "2026-06-03T00:00:00Z",
- created_at: "2026-06-03T00:00:00Z",
- updated_at: "2026-06-03T00:00:00Z",
- },
- ];
- render(
- <LarkAgentBindButton agentId="agent-1" agentName="Bot" />,
- { wrapper: I18nWrapper },
- );
- // Both Bind CTAs must be gone — re-scanning would orphan the
- // PersonalAgent (see badge comment in lark-tab.tsx).
- expect(screen.queryByRole("button", { name: /Bind to Feishu/i })).toBeNull();
- expect(screen.queryByRole("button", { name: /Bind to Lark/i })).toBeNull();
- // The fixture omits `region`, which the listings DTO defaults to
- // Feishu (mainland). After the #3830 badge restructure the cloud is
- // shown as a "Feishu" chip (not baked into the connected label) and a
- // Disconnect action appears; the region-aware Manage link still points
- // at the mainland host.
- expect(screen.getByText("Feishu")).toBeTruthy();
- expect(screen.getByText("Bound — awaiting message verification")).toBeTruthy();
- expect(screen.getByTestId("lark-agent-bot-disconnect")).toBeTruthy();
- const link = screen.getByRole("link", { name: /Manage in Feishu/i }) as HTMLAnchorElement;
- expect(link.href).toBe("https://open.feishu.cn/app/cli_existing_app");
- expect(link.target).toBe("_blank");
- expect(link.rel).toContain("noopener");
- });
-
- it("renders region-aware badge text and Manage link for a Lark-international (region=lark) installation", () => {
- // Dual-region: a bot installed against the Lark international cloud
- // must show "Connected to Lark" + "Manage in Lark" copy, with the
- // Manage link pointing at open.larksuite.com (not the Feishu
- // default). Without region-aware copy a user who clicked
- // "Bind to Feishu" and saw "Connected to Lark" would (rightly) be
- // confused — the labels must match the cloud the bot lives on.
- installationsRef.current.installations = [
- {
- id: "inst-lark",
- workspace_id: "ws-1",
- agent_id: "agent-1",
- app_id: "cli_lark_app",
- bot_open_id: "ou_lark_bot",
- installer_user_id: "user-1",
- status: "active",
- region: "lark",
- installed_at: "2026-06-03T00:00:00Z",
- created_at: "2026-06-03T00:00:00Z",
- updated_at: "2026-06-03T00:00:00Z",
- },
- ];
- render(<LarkAgentBindButton agentId="agent-1" agentName="Bot" />, {
- wrapper: I18nWrapper,
- });
- expect(screen.getByText("Bound — awaiting message verification")).toBeTruthy();
- const link = screen.getByRole("link", { name: /Manage in Lark/i }) as HTMLAnchorElement;
- expect(link.href).toBe("https://open.larksuite.com/app/cli_lark_app");
- });
-
- it("shows the Feishu CTA (Lark hidden) for an agent without its own installation, per-agent scoping (MUL-3083)", () => {
- installationsRef.current.installations = [
- {
- id: "inst-other",
- workspace_id: "ws-1",
- agent_id: "agent-other",
- app_id: "cli_other",
- bot_open_id: "ou_other",
- installer_user_id: "user-1",
- status: "active",
- installed_at: "2026-06-03T00:00:00Z",
- created_at: "2026-06-03T00:00:00Z",
- updated_at: "2026-06-03T00:00:00Z",
- },
- ];
- render(<LarkAgentBindButton agentId="agent-1" agentName="Bot" />, {
- wrapper: I18nWrapper,
- });
- expect(screen.getByRole("button", { name: /Bind to Feishu/i })).toBeTruthy();
- expect(screen.queryByRole("button", { name: /Bind to Lark/i })).toBeNull();
- });
-
- it("keeps the Connected + Manage badge for an already-installed agent even when new installs are unavailable (install_supported=false)", () => {
- // install_supported governs only NEW scan-installs — an already-installed
- // bot stays manageable when the device-flow transport is unwired
- // (server/internal/handler/lark.go: "already-installed bots still appear
- // and remain manageable"). Regression: the install_supported gate used to
- // run before the existing-installation check and hid the bound state.
- installationsRef.current.install_supported = false;
- installationsRef.current.installations = [
- {
- id: "inst-1",
- workspace_id: "ws-1",
- agent_id: "agent-1",
- app_id: "cli_existing_app",
- bot_open_id: "ou_existing_bot",
- installer_user_id: "user-1",
- status: "active",
- installed_at: "2026-06-03T00:00:00Z",
- created_at: "2026-06-03T00:00:00Z",
- updated_at: "2026-06-03T00:00:00Z",
- },
- ];
- render(
- <LarkAgentBindButton agentId="agent-1" agentName="Bot" />,
- { wrapper: I18nWrapper },
- );
- // Both Bind CTAs must be gone even when install_supported=false,
- // since the existing-installation check runs first.
- expect(screen.queryByRole("button", { name: /Bind to Feishu/i })).toBeNull();
- expect(screen.queryByRole("button", { name: /Bind to Lark/i })).toBeNull();
- // Fixture omits region → defaults to Feishu: the cloud shows as a
- // "Feishu" chip (post-#3830 badge restructure), the Disconnect action
- // is present, and the Manage link stays Feishu-aware.
- expect(screen.getByText("Feishu")).toBeTruthy();
- expect(screen.getByTestId("lark-agent-bot-disconnect")).toBeTruthy();
- expect(
- screen.getByRole("link", { name: /Manage in Feishu/i }),
- ).toBeTruthy();
- });
-
- it("shows the Feishu CTA (Lark hidden) when this agent's only installation is revoked (MUL-3083)", () => {
- installationsRef.current.installations = [
- {
- id: "inst-revoked",
- workspace_id: "ws-1",
- agent_id: "agent-1",
- app_id: "cli_revoked",
- bot_open_id: "ou_revoked",
- installer_user_id: "user-1",
- status: "revoked",
- installed_at: "2026-06-03T00:00:00Z",
- created_at: "2026-06-03T00:00:00Z",
- updated_at: "2026-06-03T00:00:00Z",
- },
- ];
- render(<LarkAgentBindButton agentId="agent-1" agentName="Bot" />, {
- wrapper: I18nWrapper,
- });
- expect(screen.getByRole("button", { name: /Bind to Feishu/i })).toBeTruthy();
- expect(screen.queryByRole("button", { name: /Bind to Lark/i })).toBeNull();
- });
-});
-
-// The Connected badge surfaces an Unbind affordance for owners/admins
-// (parent gate keeps non-admins out of this component entirely). The
-// disconnect path is the recovery handle for the install_supported=false
-// re-scan zombie-bot trap and the dual-bot conflict — these tests pin
-// the contract: confirm gating, deleteLarkInstallation wiring, cache
-// invalidation, and toast feedback on success / failure.
-describe("LarkAgentBotConnectedBadge (Unbind / Disconnect)", () => {
- beforeEach(() => {
- resetFixtures();
- installationsRef.current.installations = [
- {
- id: "inst-1",
- workspace_id: "ws-1",
- agent_id: "agent-1",
- app_id: "cli_existing_app",
- bot_open_id: "ou_existing_bot",
- installer_user_id: "user-1",
- status: "active",
- installed_at: "2026-06-03T00:00:00Z",
- created_at: "2026-06-03T00:00:00Z",
- updated_at: "2026-06-03T00:00:00Z",
- },
- ];
- });
-
- it("renders a Disconnect affordance alongside the Manage link when the agent is bound", () => {
- render(<LarkAgentBindButton agentId="agent-1" agentName="Bot" />, {
- wrapper: I18nWrapper,
- });
- // The badge surfaces three siblings: the green-dot status pill,
- // the Manage link, and the Unbind action. We assert by test-id so
- // we don't trip over /Disconnect/i copy that also appears in the
- // (closed) AlertDialog.
- expect(screen.getByTestId("lark-agent-bot-disconnect")).toBeTruthy();
- // Fixture omits region → Feishu copy.
- expect(screen.getByRole("link", { name: /Manage in Feishu/i })).toBeTruthy();
- });
-
- it("points a silent bot at the event-delivery check (#8496)", () => {
- render(<LarkAgentBindButton agentId="agent-1" agentName="Bot" />, {
- wrapper: I18nWrapper,
- });
- // A bound app whose events go to a request URL renders this exact
- // badge and receives nothing, so the connected state has to name the
- // one setting that explains the silence.
- expect(screen.getByText(/long connection/i)).toBeTruthy();
- const docs = screen.getByRole("link", { name: /Troubleshooting/i });
- expect(docs.getAttribute("href")).toBe(
- "https://multica.ai/docs/lark-bot-integration",
- );
- });
-
- it("opens the confirm dialog and does NOT call the API until the user confirms", async () => {
- const user = userEvent.setup();
- render(<LarkAgentBindButton agentId="agent-1" agentName="Bot" />, {
- wrapper: I18nWrapper,
- });
- await user.click(screen.getByTestId("lark-agent-bot-disconnect"));
- // Confirm dialog must mount with the correct copy.
- await waitFor(() => {
- expect(
- screen.getByText(/Disconnect this Lark bot\?/i),
- ).toBeTruthy();
- });
- // Critically: clicking the trigger alone must NOT have deleted the
- // installation — confirmation is mandatory.
- expect(mockDeleteInstallation).not.toHaveBeenCalled();
- });
-
- it("calls deleteLarkInstallation with (workspaceId, installationId), invalidates the cache, and toasts on confirm", async () => {
- mockDeleteInstallation.mockResolvedValue(undefined);
- const user = userEvent.setup();
- render(<LarkAgentBindButton agentId="agent-1" agentName="Bot" />, {
- wrapper: I18nWrapper,
- });
- await user.click(screen.getByTestId("lark-agent-bot-disconnect"));
- // Wait for the dialog to mount, then click the destructive action
- // (the AlertDialogAction's accessible name is the same "Disconnect"
- // label as the trigger button — but we're now inside the dialog
- // role, so role+name is unambiguous).
- const confirmButton = await screen.findByRole("button", {
- name: /^Disconnect$/i,
- });
- await user.click(confirmButton);
-
- await waitFor(() => {
- expect(mockDeleteInstallation).toHaveBeenCalledTimes(1);
- });
- expect(mockDeleteInstallation).toHaveBeenCalledWith("workspace-1", "inst-1");
- // Listings cache must be invalidated so the parent re-renders the
- // Bind CTA in place of the now-stale Connected badge.
- expect(mockInvalidate).toHaveBeenCalledWith({
- queryKey: ["lark", "installations", "workspace-1"],
- });
- expect(toast.success).toHaveBeenCalledTimes(1);
- });
-
- it("toasts an error and keeps the badge mounted when the API call rejects", async () => {
- mockDeleteInstallation.mockRejectedValue(
- new Error("upstream 500"),
- );
- const user = userEvent.setup();
- render(<LarkAgentBindButton agentId="agent-1" agentName="Bot" />, {
- wrapper: I18nWrapper,
- });
- await user.click(screen.getByTestId("lark-agent-bot-disconnect"));
- const confirmButton = await screen.findByRole("button", {
- name: /^Disconnect$/i,
- });
- await user.click(confirmButton);
-
- await waitFor(() => {
- expect(toast.error).toHaveBeenCalledTimes(1);
- });
- // Cache must NOT be invalidated on failure — invalidating would
- // round-trip a refetch, momentarily flicker the row away even
- // though the install is still active server-side.
- expect(mockInvalidate).not.toHaveBeenCalled();
- // Badge stays mounted so the user can retry.
- expect(screen.getByTestId("lark-agent-bot-connected")).toBeTruthy();
- });
-
- it("disables the Cancel button while the request is in-flight (prevents racing the close)", async () => {
- let resolveDelete: () => void = () => {};
- mockDeleteInstallation.mockImplementation(
- () =>
- new Promise<void>((resolve) => {
- resolveDelete = resolve;
- }),
- );
- const user = userEvent.setup();
- render(<LarkAgentBindButton agentId="agent-1" agentName="Bot" />, {
- wrapper: I18nWrapper,
- });
- await user.click(screen.getByTestId("lark-agent-bot-disconnect"));
- const confirmButton = await screen.findByRole("button", {
- name: /^Disconnect$/i,
- });
- await user.click(confirmButton);
-
- // Cancel is disabled while disconnecting — closing mid-flight
- // would orphan the in-flight invalidate + toast.
- const cancel = screen.getByRole("button", { name: /Cancel/i });
- await waitFor(() => {
- expect((cancel as HTMLButtonElement).disabled).toBe(true);
- });
-
- // Resolve and let the request finish so jsdom doesn't carry a
- // dangling promise into the next test.
- resolveDelete();
- await waitFor(() => {
- expect(toast.success).toHaveBeenCalled();
- });
- });
-});
-
-describe("LarkInstallDialog (polling terminal errors)", () => {
- beforeEach(() => {
- resetFixtures();
- vi.useFakeTimers({ shouldAdvanceTime: true });
- mockBeginInstall.mockResolvedValue({
- session_id: "sess-1",
- qr_code_url: "https://accounts.feishu.cn/oauth/v1/device?u=abc",
- expires_in_seconds: 300,
- poll_interval_seconds: 2,
- });
- });
-
- afterEach(() => {
- vi.useRealTimers();
- });
-
- async function openDialog() {
- const user = userEvent.setup({ advanceTimers: vi.advanceTimersByTime });
- render(<LarkAgentBindButton agentId="agent-1" agentName="Bot" />, {
- wrapper: I18nWrapper,
- });
- // The Lark CTA is hidden (MUL-3083); open the dialog via the Feishu CTA
- // — the polling-error behavior under test is region-agnostic.
- await user.click(screen.getByRole("button", { name: /Bind to Feishu/i }));
- // Let the begin-session promise resolve and the QR render.
- await waitFor(() => {
- expect(screen.getByTestId("qr-code")).toBeTruthy();
- });
- }
-
- it("falls into a terminal session_lost error state when status polling 404s instead of looping forever", async () => {
- mockGetStatus.mockRejectedValue(
- new ApiError("install session not found", 404, "Not Found"),
- );
-
- await openDialog();
- // Drive the polling timer (intervalMs = max(2000, 2*1000)) and let
- // the rejected promise propagate into the catch.
- await act(async () => {
- await vi.advanceTimersByTimeAsync(2100);
- });
-
- await waitFor(() => {
- expect(
- screen.getByText(
- /Install session expired or was lost\. Scan again to start over\./i,
- ),
- ).toBeTruthy();
- });
- expect(screen.getByRole("button", { name: /Scan again/i })).toBeTruthy();
- // The dialog renders multiple Close affordances (footer button + the
- // built-in dialog dismiss); we only need to confirm at least one is
- // mounted alongside the retry button.
- expect(screen.getAllByRole("button", { name: /Close/i }).length).toBeGreaterThan(0);
- });
-
- it("treats 403 as a terminal forbidden error state (no infinite retry on revoked permission)", async () => {
- mockGetStatus.mockRejectedValue(
- new ApiError("forbidden", 403, "Forbidden"),
- );
-
- await openDialog();
- await act(async () => {
- await vi.advanceTimersByTimeAsync(2100);
- });
-
- await waitFor(() => {
- expect(
- screen.getByText(
- /You no longer have permission to install Lark Bots in this workspace/i,
- ),
- ).toBeTruthy();
- });
- // Drive another full poll interval — the polling loop must NOT
- // schedule a follow-up fetch after a terminal 4xx.
- const callsAfterTerminal = mockGetStatus.mock.calls.length;
- await act(async () => {
- await vi.advanceTimersByTimeAsync(5000);
- });
- expect(mockGetStatus.mock.calls.length).toBe(callsAfterTerminal);
- });
-
- // Regression test for the empty-dialog bug Bohan hit on PR #3277:
- // the QR area was completely blank after opening the dialog. React 19
- // StrictMode dev mounts every component twice. The mount/cleanup/mount
- // cycle preserves the component's useRef across the simulated remount,
- // so the cleanup's `closedRef.current = true` survived into the
- // second mount. Both beginSession() promises then saw closedRef=true
- // at the post-await guard and skipped setSession(), leaving the dialog
- // body with no QR, no error, no loading text — just empty. Resetting
- // closedRef.current at the START of the effect re-arms the guard on
- // every mount.
- it("renders the QR after a React StrictMode double-mount (regression for empty dialog body)", async () => {
- const user = userEvent.setup({ advanceTimers: vi.advanceTimersByTime });
- render(<LarkAgentBindButton agentId="agent-1" agentName="Bot" />, {
- wrapper: StrictModeWrapper,
- });
- // The Lark CTA is hidden (MUL-3083); the StrictMode regression is about
- // the dialog mount cycle, so open it via the Feishu CTA.
- await user.click(screen.getByRole("button", { name: /Bind to Feishu/i }));
-
- // The QR must appear even though the dialog mounted, unmounted, and
- // mounted again under StrictMode. The previous bug left the body
- // empty here.
- await waitFor(
- () => {
- expect(screen.getByTestId("qr-code")).toBeTruthy();
- },
- { timeout: 2000 },
- );
-
- // And the QR's value should match what the (latest) begin call
- // returned — not be empty / undefined.
- const qr = screen.getByTestId("qr-code");
- expect(qr.getAttribute("data-value")).toBe(
- "https://accounts.feishu.cn/oauth/v1/device?u=abc",
- );
- });
-});
-
-// The Connected bots list used to surface Lark's raw cli_… app_id and
-// ou_… bot_open_id, which are meaningless to product users. The row now
-// renders the Multica agent's avatar + name (joined via inst.agent_id),
-// since the binding is 1:1 with an Agent. These tests pin that identity
-// rendering so the row never regresses to leaking the cli_ prefix.
-describe("LarkTab connected bots list (agent identity rendering)", () => {
- beforeEach(resetFixtures);
-
- it("renders the Multica agent's name and avatar instead of the raw Lark app_id / bot_open_id", () => {
- agentNameByIdRef.current = new Map([["agent-1", "Bohan's Helper"]]);
- installationsRef.current.installations = [
- {
- id: "inst-1",
- workspace_id: "ws-1",
- agent_id: "agent-1",
- app_id: "cli_aa941499d4f95cd9",
- bot_open_id: "ou_abc123",
- installer_user_id: "user-1",
- status: "active",
- installed_at: "2026-06-03T00:00:00Z",
- created_at: "2026-06-03T00:00:00Z",
- updated_at: "2026-06-03T00:00:00Z",
- },
- ];
-
- render(<LarkTab />, { wrapper: I18nWrapper });
-
- // The agent's display name is the primary identifier.
- expect(screen.getByText("Bohan's Helper")).toBeTruthy();
-
- // The ActorAvatar stub records the actor it was asked to render —
- // confirms we joined on agent_id (and didn't accidentally pass the
- // bot_open_id or installation id).
- const avatar = screen.getByTestId("actor-avatar");
- expect(avatar.getAttribute("data-actor-type")).toBe("agent");
- expect(avatar.getAttribute("data-actor-id")).toBe("agent-1");
-
- // The raw Lark IDs are explicitly absent — the row must not leak
- // the cli_ / ou_ prefixes anymore.
- expect(screen.queryByText(/cli_aa941499d4f95cd9/)).toBeNull();
- expect(screen.queryByText(/ou_abc123/)).toBeNull();
- });
-
- it("falls back to a stable placeholder when the agent has been deleted (so the row is still actionable for cleanup)", () => {
- // Empty map → useActorName.getAgentName returns "Unknown Agent".
- // The row must still render so admins can hit Disconnect.
- installationsRef.current.installations = [
- {
- id: "inst-orphan",
- workspace_id: "ws-1",
- agent_id: "agent-deleted",
- app_id: "cli_orphan",
- bot_open_id: "ou_orphan",
- installer_user_id: "user-1",
- status: "active",
- installed_at: "2026-06-03T00:00:00Z",
- created_at: "2026-06-03T00:00:00Z",
- updated_at: "2026-06-03T00:00:00Z",
- },
- ];
-
- render(<LarkTab />, { wrapper: I18nWrapper });
-
- expect(screen.getByText(/Unknown Agent/)).toBeTruthy();
- // Disconnect stays reachable so the orphan row can be cleaned up.
- expect(screen.getByRole("button", { name: /Disconnect/i })).toBeTruthy();
- });
-});
-
-
-describe("Lark inbound verification display", () => {
- it("updates the bound status when refreshed evidence arrives", () => {
- const installation = { id: "proof", workspace_id: "workspace-1", agent_id: "agent-1", app_id: "app", bot_open_id: "bot", installer_user_id: "user-1", status: "active", installed_at: "2026-10-29T00:00:00Z", created_at: "2026-10-29T00:00:00Z", updated_at: "2026-10-29T00:00:00Z", first_message_received_at: null as string | null };
- installationsRef.current.installations = [installation];
- const { rerender } = render(<LarkAgentBindButton agentId="agent-1" agentName="Bot" />, { wrapper: I18nWrapper });
- expect(screen.getByText("Bound — awaiting message verification")).toBeTruthy();
- expect(screen.getByText(/Existing bindings may have no recorded verification yet/)).toBeTruthy();
- installation.first_message_received_at = "2026-10-29T01:00:00Z";
- rerender(<LarkAgentBindButton agentId="agent-1" agentName="Bot" />);
- expect(screen.getByText("Message reception verified")).toBeTruthy();
- expect(screen.getByText(/does not confirm ongoing connectivity/)).toBeTruthy();
- expect(screen.queryByText("Bound — awaiting message verification")).toBeNull();
- });
-});
diff --git a/packages/views/settings/components/lark-tab.tsx b/packages/views/settings/components/lark-tab.tsx
deleted file mode 100644
index e0d24bfbab..0000000000
--- a/packages/views/settings/components/lark-tab.tsx
+++ /dev/null
@@ -1,991 +0,0 @@
-"use client";
-
-import { useEffect, useRef, useState } from "react";
-import { useQuery, useQueryClient } from "@tanstack/react-query";
-import { toast } from "sonner";
-import { ChevronRight, ExternalLink, RefreshCw, Trash2 } from "@multica/ui/icons";
-// Named import, NOT default: react-qr-code is CJS, and electron-vite's
-// dep-optimizer default-import interop handed back the module namespace
-// object instead of the component, throwing "Element type is invalid …
-// got: object" the moment <QRCode> mounted (the QR step of the install
-// dialog) — desktop white-screened while web (Next.js, different interop)
-// was fine. The named export maps straight to `exports.QRCode` and
-// resolves correctly under both bundlers.
-import { QRCode } from "react-qr-code";
-import { cn } from "@multica/ui/lib/utils";
-import { Button } from "@multica/ui/components/ui/button";
-import { Card, CardContent } from "@multica/ui/components/ui/card";
-import {
- AlertDialog,
- AlertDialogAction,
- AlertDialogCancel,
- AlertDialogContent,
- AlertDialogDescription,
- AlertDialogFooter,
- AlertDialogHeader,
- AlertDialogTitle,
-} from "@multica/ui/components/ui/alert-dialog";
-import {
- Dialog,
- DialogContent,
- DialogHeader,
- DialogTitle,
- DialogDescription,
- DialogFooter,
-} from "@multica/ui/components/ui/dialog";
-import { useAuthStore } from "@multica/core/auth";
-import { useWorkspaceId } from "@multica/core/hooks";
-import { memberListOptions } from "@multica/core/workspace/queries";
-import { useActorName } from "@multica/core/workspace/hooks";
-import { larkInstallationsOptions, larkKeys } from "@multica/core/lark";
-import { api, ApiError } from "@multica/core/api";
-import type { LarkInstallation, LarkInstallStatusResponse } from "@multica/core/types";
-import { ActorAvatar } from "../../common/actor-avatar";
-import { docsLocalePrefix } from "../../common/docs-locale";
-import { useLocale, useT } from "../../i18n";
-import { TooltipHint } from "@multica/ui/components/common/tooltip-hint";
-
-// MUL-3083: the Lark (international, open.larksuite.com) "connect a Bot"
-// entry is temporarily hidden while its install → inbound pipeline is
-// stabilized — some Lark installs complete on Lark's side but never land a
-// `lark_installation` row, so the Bot silently can't receive messages.
-// Mainland Feishu is unaffected and keeps its bind entry. Existing
-// installations (either cloud) stay fully manageable. Flip this back to
-// `true` to restore the "Bind to Lark" CTA; nothing else needs to change.
-const LARK_INTL_CONNECT_ENABLED: boolean = false;
-
-// LarkTab is the workspace settings panel for Lark Bot installations.
-// Listing is member-visible; the disconnect action is admin-only (the
-// backend enforces it; the UI hides the button for non-admins to match).
-//
-// Adding a new installation flows through the Agent detail page: the
-// install path is per-agent (each Multica Agent gets exactly one Bot —
-// see the (workspace_id, agent_id) UNIQUE in lark_installation), so
-// asking the user to pick an agent here would re-create that page's
-// picker. The "Bind your first agent" copy in the empty state hints
-// users at the right entry point.
-export function LarkTab() {
- const { t } = useT("settings");
- const wsId = useWorkspaceId();
- const qc = useQueryClient();
- const user = useAuthStore((s) => s.user);
-
- const { data: members = [] } = useQuery(memberListOptions(wsId));
- const currentMember = members.find((m) => m.user_id === user?.id) ?? null;
- const canManage =
- currentMember?.role === "owner" || currentMember?.role === "admin";
-
- const { data, isLoading } = useQuery({
- ...larkInstallationsOptions(wsId),
- enabled: !!wsId,
- });
- const installations = data?.installations ?? [];
- const configured = data?.configured === true;
- // install_supported tracks whether the device-flow install path is
- // wired end-to-end on the server. When false, scan-to-bind would
- // fail at the post-poll bot-info step, so we hide install entry
- // points and surface a "coming soon" notice in their place rather
- // than send users into a broken flow. Already-installed bots still
- // appear in the listing below and remain manageable.
- const installSupported = data?.install_supported === true;
-
- const [disconnectTarget, setDisconnectTarget] = useState<string | null>(null);
- const [disconnecting, setDisconnecting] = useState(false);
-
- async function handleDisconnect() {
- if (!disconnectTarget || disconnecting) return;
- setDisconnecting(true);
- try {
- await api.deleteLarkInstallation(wsId, disconnectTarget);
- await qc.invalidateQueries({ queryKey: larkKeys.installations(wsId) });
- toast.success(t(($) => $.lark.toast_disconnected));
- setDisconnectTarget(null);
- } catch (e) {
- toast.error(e instanceof Error ? e.message : t(($) => $.lark.toast_disconnect_failed));
- } finally {
- setDisconnecting(false);
- }
- }
-
- return (
- <div className="space-y-8">
- {!configured ? (
- <Card>
- <CardContent className="space-y-2">
- <p className="text-body font-medium">{t(($) => $.lark.not_enabled_title)}</p>
- <p className="text-caption text-muted-foreground">
- {t(($) => $.lark.not_enabled_description_prefix)}{" "}
- <code className="rounded-xs bg-muted px-1 py-0.5 text-micro">
- MULTICA_LARK_SECRET_KEY
- </code>{" "}
- {t(($) => $.lark.not_enabled_description_suffix)}{" "}
- {t(($) => $.lark.not_enabled_self_host_hint)}
- </p>
- </CardContent>
- </Card>
- ) : !installSupported && installations.length === 0 ? (
- // Device-flow install path is not wired (HTTP client is the stub
- // or RegistrationService didn't initialize). We deliberately do
- // NOT direct users to the agent-detail "Bind" button because the
- // backend would reject it anyway. Existing installations still render
- // via the branch below; this only hides the empty-state CTA
- // when there is nothing to manage.
- <Card>
- <CardContent className="space-y-2">
- <p className="text-body font-medium">{t(($) => $.lark.preview_title)}</p>
- <p className="text-caption text-muted-foreground">
- {t(($) => $.lark.preview_description)}
- </p>
- </CardContent>
- </Card>
- ) : (
- <section className="space-y-3">
- <h2 className="text-body font-semibold">{t(($) => $.lark.connected_bots)}</h2>
- {isLoading ? (
- <Card>
- <CardContent>
- <p className="text-body text-muted-foreground">{t(($) => $.lark.loading)}</p>
- </CardContent>
- </Card>
- ) : installations.length === 0 ? (
- <Card>
- <CardContent className="space-y-2">
- <p className="text-body font-medium">{t(($) => $.lark.empty_title)}</p>
- <p className="text-caption text-muted-foreground">
- {t(($) => $.lark.empty_description_prefix)}{" "}
- <strong>{t(($) => $.lark.empty_description_cta)}</strong>{" "}
- {t(($) => $.lark.empty_description_suffix)}
- </p>
- </CardContent>
- </Card>
- ) : (
- <Card>
- <CardContent className="divide-y">
- {installations.map((inst) => (
- <InstallationRow
- key={inst.id}
- installation={inst}
- canManage={canManage}
- onDisconnect={() => setDisconnectTarget(inst.id)}
- />
- ))}
- </CardContent>
- </Card>
- )}
- </section>
- )}
-
- <AlertDialog
- open={!!disconnectTarget}
- onOpenChange={(v) => {
- if (!v && !disconnecting) setDisconnectTarget(null);
- }}
- >
- <AlertDialogContent>
- <AlertDialogHeader>
- <AlertDialogTitle>
- {t(($) => $.lark.disconnect_confirm_title)}
- </AlertDialogTitle>
- <AlertDialogDescription>
- {t(($) => $.lark.disconnect_confirm_description)}
- </AlertDialogDescription>
- </AlertDialogHeader>
- <AlertDialogFooter>
- <AlertDialogCancel disabled={disconnecting}>
- {t(($) => $.lark.disconnect_confirm_cancel)}
- </AlertDialogCancel>
- <AlertDialogAction onClick={handleDisconnect} disabled={disconnecting}>
- {disconnecting
- ? t(($) => $.lark.disconnecting)
- : t(($) => $.lark.disconnect)}
- </AlertDialogAction>
- </AlertDialogFooter>
- </AlertDialogContent>
- </AlertDialog>
- </div>
- );
-}
-
-function LarkReceiptGuidance({
- installation,
- showStatus = true,
-}: {
- installation: LarkInstallation;
- showStatus?: boolean;
-}) {
- const { t } = useT("settings");
- const verified = !!installation.first_message_received_at;
- return (
- <div className="space-y-1 text-caption text-muted-foreground">
- {showStatus && (
- <p>{verified ? t(($) => $.lark.inbound_verified) : t(($) => $.lark.inbound_pending)}</p>
- )}
- <p>{verified ? t(($) => $.lark.inbound_verified_hint) : t(($) => $.lark.inbound_pending_hint)}</p>
- </div>
- );
-}
-
-function InstallationRow({
- installation,
- canManage,
- onDisconnect,
-}: {
- installation: LarkInstallation;
- canManage: boolean;
- onDisconnect: () => void;
-}) {
- const { t } = useT("settings");
- const locale = useLocale();
- // The bot is bound 1:1 to a Multica Agent (per the (workspace_id,
- // agent_id) UNIQUE in lark_installation). Render the Multica agent's
- // identity here rather than the raw Lark app_id / bot_open_id — those
- // mean nothing to product users. getAgentName falls back to
- // "Unknown Agent" when the agent has been deleted; the Disconnect
- // affordance below is the recovery path for that orphan row.
- const { getAgentName } = useActorName();
- const isActive = installation.status === "active";
- const agentName = getAgentName(installation.agent_id);
- return (
- <div className="flex items-start justify-between gap-4 py-3 first:pt-0 last:pb-0">
- <div className="flex items-start gap-3">
- <ActorAvatar
- actorType="agent"
- actorId={installation.agent_id}
- size="lg"
- enableHoverCard
- profileLink
- />
- <div className="space-y-1">
- <p className="text-body font-medium">
- {agentName}
- <span className="ml-2 rounded-xs bg-muted px-1.5 py-0.5 text-micro text-muted-foreground">
- {installation.region === "lark"
- ? t(($) => $.lark.region_lark)
- : t(($) => $.lark.region_feishu)}
- </span>
- {!isActive && (
- <span className="ml-2 rounded-xs bg-muted px-1.5 py-0.5 text-micro text-muted-foreground">
- {t(($) => $.lark.revoked_badge)}
- </span>
- )}
- </p>
- {isActive && <LarkReceiptGuidance installation={installation} />}
- <p className="text-micro text-muted-foreground">
- {t(($) => $.lark.installed_at_label, {
- when: new Date(installation.installed_at).toLocaleString(locale),
- })}
- </p>
- </div>
- </div>
- {canManage && isActive && (
- <Button variant="outline" size="sm" onClick={onDisconnect}>
- <Trash2 className="h-3 w-3" />
- {t(($) => $.lark.disconnect)}
- </Button>
- )}
- </div>
- );
-}
-
-// LarkAgentBindButton is the per-agent CTA we expose from the agent
-// detail page. The Settings panel above is the management view; this
-// button is the entry point.
-//
-// Visibility rules, in order:
-// 1. Only the agent's owner or a workspace owner/admin see anything —
-// the backend authorizes `POST /lark/install/begin`, the status
-// poll, AND disconnect with canManageAgent (agent owner OR ws
-// owner/admin; see server/internal/handler/lark.go, MUL-4213), so
-// the gate here mirrors that. `agentOwnerId` is what lets a
-// non-admin owner through; when it is omitted the button stays
-// workspace owner/admin-only.
-// 2. If this agent ALREADY has an active installation, they see
-// the "Connected + Manage in Lark" badge — regardless of
-// install_supported. install_supported governs only whether NEW
-// scan-installs can complete; already-installed bots stay manageable
-// when the device-flow transport is unwired (see
-// server/internal/handler/lark.go — "already-installed bots still
-// appear and remain manageable"). Gating the badge on it would hide a
-// bound agent's connected state the moment the transport went away.
-// 3. Otherwise the Bind CTA shows only when install_supported is true —
-// a fresh scan against a stub transport would fail at the post-poll
-// bot-info step, so we don't surface a flow that's guaranteed to fail.
-export function LarkAgentBindButton({
- agentId,
- agentName,
- agentOwnerId,
- className,
- onShowConnectedDetails,
-}: {
- agentId: string;
- agentName?: string;
- /**
- * The bound agent's owner (`agent.owner_id`). When it matches the
- * current user, the button treats them as able to manage the bot even
- * if they are not a workspace owner/admin — mirroring the backend's
- * canManageAgent authorization (MUL-4213). Omit it to keep the button
- * workspace owner/admin-only.
- */
- agentOwnerId?: string | null;
- className?: string;
- /**
- * When set, the connected state renders as a compact read-only status
- * row that invokes this callback on click instead of the full badge with
- * inline Manage / Disconnect actions. The agent inspector passes a
- * "jump to the Integrations tab" handler so the left column stays a
- * glanceable summary and the management actions live in one place (the
- * tab). The tab itself omits this prop and gets the full badge.
- */
- onShowConnectedDetails?: () => void;
-}) {
- const { t } = useT("settings");
- const wsId = useWorkspaceId();
- const user = useAuthStore((s) => s.user);
- // dialogRegion carries two pieces of state in one variable: which
- // cloud the dialog should target (drives the device-flow `begin`
- // host and the dialog copy), AND whether the dialog is open at all
- // (null = closed). A separate boolean would have to be kept in sync
- // with the region — collapsing them prevents an "open but with no
- // region picked" intermediate state from existing.
- const [dialogRegion, setDialogRegion] = useState<"feishu" | "lark" | null>(
- null,
- );
-
- const { data: listing } = useQuery({
- ...larkInstallationsOptions(wsId),
- enabled: !!wsId,
- });
- const installSupported = listing?.install_supported === true;
-
- const { data: members = [] } = useQuery({
- ...memberListOptions(wsId),
- enabled: !!wsId,
- });
- const currentMember = members.find((m) => m.user_id === user?.id) ?? null;
- const isWorkspaceAdmin =
- currentMember?.role === "owner" || currentMember?.role === "admin";
- const isAgentOwner =
- !!user?.id && agentOwnerId != null && agentOwnerId === user.id;
- // Mirror the backend canManageAgent gate: the agent's owner OR a
- // workspace owner/admin may bind/manage the bot (MUL-4213).
- const canManage = isWorkspaceAdmin || isAgentOwner;
-
- if (!canManage) return null;
-
- // Existing-installation check runs BEFORE the install_supported gate:
- // already-installed bots stay manageable even when new scan-installs are
- // unavailable (server/internal/handler/lark.go). Surfacing the badge here
- // also closes the re-scan zombie-bot trap — re-scanning the same agent
- // upserts the row and orphans the previously-created PersonalAgent, so we
- // close the install entry point and link to the Bot's Lark app page where
- // scopes / display name / additional permissions are actually managed.
- const existing = listing?.installations.find(
- (inst) => inst.agent_id === agentId && inst.status === "active",
- );
- if (existing) {
- return onShowConnectedDetails ? (
- <LarkAgentBotStatusRow
- installation={existing}
- onClick={onShowConnectedDetails}
- className={className}
- />
- ) : (
- <LarkAgentBotConnectedBadge installation={existing} className={className} />
- );
- }
-
- // No existing bot and the device-flow transport isn't wired end-to-end:
- // a fresh scan would fail at the post-poll bot-info step, so hide the CTA.
- if (!installSupported) return null;
-
- // Two CTAs, one per cloud — Feishu (mainland) on the left, Lark
- // (international) on the right. We deliberately render two explicit
- // entry points instead of one auto-detect QR because Lark only emits
- // tenant_brand="lark" mid-poll AFTER the user has authorized; until
- // then a Lark user has to scan a QR served from accounts.feishu.cn,
- // which has surfaced as confusing for international users (MUL-3083
- // follow-up). Each button passes its region to the install dialog,
- // which threads it to the backend so the device-flow `begin` POSTs
- // directly against the matching accounts host. The mid-poll
- // tenant-brand auto-switch in RegistrationService is preserved as a
- // safety net for users who pick the wrong entry.
- return (
- <>
- <div
- className={cn("flex flex-wrap items-center gap-2", className)}
- data-testid="lark-agent-bind-buttons"
- >
- <TooltipHint
- label={
- agentName
- ? t(($) => $.lark.bind_button_feishu_title, { agent: agentName })
- : undefined
- }
- >
- <Button
- variant="outline"
- size="sm"
- onClick={() => setDialogRegion("feishu")}
- disabled={!agentId}
- data-testid="lark-agent-bind-feishu"
- >
- <ExternalLink className="h-3 w-3" />
- {t(($) => $.lark.bind_button_feishu)}
- </Button>
- </TooltipHint>
- {/* MUL-3083: Lark (international) bind entry is temporarily hidden —
- see LARK_INTL_CONNECT_ENABLED. Mainland Feishu (above) is
- unaffected. */}
- {LARK_INTL_CONNECT_ENABLED && (
- <TooltipHint
- label={
- agentName
- ? t(($) => $.lark.bind_button_lark_title, { agent: agentName })
- : undefined
- }
- >
- <Button
- variant="outline"
- size="sm"
- onClick={() => setDialogRegion("lark")}
- disabled={!agentId}
- data-testid="lark-agent-bind-lark"
- >
- <ExternalLink className="h-3 w-3" />
- {t(($) => $.lark.bind_button_lark)}
- </Button>
- </TooltipHint>
- )}
- </div>
- {dialogRegion && (
- <LarkInstallDialog
- wsId={wsId}
- agentId={agentId}
- agentName={agentName}
- region={dialogRegion}
- onClose={() => setDialogRegion(null)}
- />
- )}
- </>
- );
-}
-
-// LarkAgentBotStatusRow is the compact, read-only connected affordance the
-// agent inspector (left column) renders instead of the full badge. It shows
-// only the receipt status and Feishu/Lark region chip
-// — and is a single full-width button that deep-links into the Integrations
-// tab, where Manage / Disconnect live. Keeping the destructive action out of
-// the always-visible sidebar means it exists in exactly one place.
-function LarkAgentBotStatusRow({
- installation,
- onClick,
- className,
-}: {
- installation: LarkInstallation;
- onClick: () => void;
- className?: string;
-}) {
- const { t } = useT("settings");
- return (
- <button
- type="button"
- onClick={onClick}
- className={cn(
- "flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-caption text-muted-foreground transition-colors hover:bg-muted focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/50",
- className,
- )}
- data-testid="lark-agent-bot-status"
- >
- <span className={cn(
- "inline-block h-1.5 w-1.5 shrink-0 rounded-full",
- installation.first_message_received_at ? "bg-success" : "bg-muted-foreground",
- )} />
- <span className="rounded-xs bg-muted px-1.5 py-0.5 text-micro text-muted-foreground">
- {installation.region === "lark"
- ? t(($) => $.lark.region_lark)
- : t(($) => $.lark.region_feishu)}
- </span>
- <span className="truncate">{installation.first_message_received_at
- ? t(($) => $.lark.inbound_verified)
- : t(($) => $.lark.inbound_pending)}</span>
- <ChevronRight className="ml-auto h-3.5 w-3.5 shrink-0" />
- </button>
- );
-}
-
-// LarkAgentBotConnectedBadge is the full "already connected" affordance the
-// Integrations tab renders in place of the Bind button when this agent has
-// an active Lark installation. (The inspector's left column uses the compact
-// LarkAgentBotStatusRow instead, which deep-links here.) It lays out as two
-// rows: row 1 pairs a green-dot status (with the Feishu/Lark region chip) on
-// the left with a soft-destructive Disconnect button on the right; row 2
-// carries the secondary "Manage in Lark" link to the Bot's dev console page
-// (new tab). Disconnect removes the installation after a confirm dialog.
-//
-// Visibility rules carry over from the parent `LarkAgentBindButton`:
-// only the agent's owner or a workspace owner/admin ever reach this
-// component, so the unbind affordance is unconditionally shown — the
-// backend authorizes DELETE with the same canManageAgent check (MUL-4213)
-// and would 403 anyone else, which makes a redundant gate here dead code.
-//
-// The dev-console host depends on which Lark cloud the bot lives on:
-// Feishu (mainland) bots are managed at open.feishu.cn, Lark
-// (international) bots at open.larksuite.com. The region is auto-detected
-// at install time and surfaced per installation on the listings
-// response; an older server that omits `region` defaults to Feishu
-// (API-compat — see CLAUDE.md).
-function larkDevConsoleHost(region?: string): string {
- return region === "lark"
- ? "https://open.larksuite.com"
- : "https://open.feishu.cn";
-}
-
-// larkDocsUrl points at the Lark/Feishu integration guide, localized the
-// same way as the Telegram and Slack docs links.
-function larkDocsUrl(lang: string | undefined): string {
- return `https://multica.ai/docs${docsLocalePrefix(lang)}/lark-bot-integration`;
-}
-
-function LarkAgentBotConnectedBadge({
- installation,
- className,
-}: {
- installation: LarkInstallation;
- className?: string;
-}) {
- const { t, i18n } = useT("settings");
- const wsId = useWorkspaceId();
- const qc = useQueryClient();
- const manageHref = `${larkDevConsoleHost(installation.region)}/app/${encodeURIComponent(installation.app_id)}`;
-
- const [confirmOpen, setConfirmOpen] = useState(false);
- const [disconnecting, setDisconnecting] = useState(false);
-
- async function handleDisconnect() {
- if (disconnecting) return;
- setDisconnecting(true);
- try {
- await api.deleteLarkInstallation(wsId, installation.id);
- // Invalidate before closing the dialog: the badge unmounts when
- // the listings query updates (the parent swaps to the Bind CTA),
- // so leaving the open state behind is fine — but doing the
- // network call before the close prevents a flash of "stale
- // connected" state.
- await qc.invalidateQueries({ queryKey: larkKeys.installations(wsId) });
- toast.success(t(($) => $.lark.toast_disconnected));
- setConfirmOpen(false);
- } catch (e) {
- toast.error(
- e instanceof Error ? e.message : t(($) => $.lark.toast_disconnect_failed),
- );
- } finally {
- setDisconnecting(false);
- }
- }
-
- return (
- <div
- className={cn("space-y-2", className)}
- data-testid="lark-agent-bot-connected"
- >
- {/* Row 1: connection status (left) and the destructive unbind
- action (right). The Disconnect uses the soft-tinted
- `destructive` button variant — it reads dangerous without the
- loud solid-red, and stays visible because it is the user-facing
- recovery path for the install_supported=false / re-scan
- zombie-bot trap (server/internal/handler/lark.go). Confirmation
- is mandatory: the backend disconnect tears down the WebSocket
- and stops message delivery. */}
- <div className="flex items-center justify-between gap-3">
- <span className="inline-flex min-w-0 items-center gap-2 text-caption text-muted-foreground">
- <span className={cn(
- "inline-block h-1.5 w-1.5 shrink-0 rounded-full",
- installation.first_message_received_at ? "bg-success" : "bg-muted-foreground",
- )} />
- <span className="rounded-xs bg-muted px-1.5 py-0.5 text-micro text-muted-foreground">
- {installation.region === "lark"
- ? t(($) => $.lark.region_lark)
- : t(($) => $.lark.region_feishu)}
- </span>
- <span className="truncate">{installation.first_message_received_at
- ? t(($) => $.lark.inbound_verified)
- : t(($) => $.lark.inbound_pending)}</span>
- </span>
- <TooltipHint label={t(($) => $.lark.agent_bot_disconnect_tooltip)}>
- <Button
- variant="destructive"
- size="sm"
- onClick={() => setConfirmOpen(true)}
- disabled={disconnecting}
- aria-label={t(($) => $.lark.disconnect)}
- data-testid="lark-agent-bot-disconnect"
- >
- <Trash2 className="h-3 w-3" />
- {disconnecting
- ? t(($) => $.lark.disconnecting)
- : t(($) => $.lark.disconnect)}
- </Button>
- </TooltipHint>
- </div>
-
- <LarkReceiptGuidance installation={installation} showStatus={false} />
-
- {/* Row 2: secondary "Manage in Lark" link to the Bot's dev-console
- app page. Demoted below the status row so it no longer competes
- with the primary connect/disconnect intents. Region-aware tooltip
- keeps the Feishu vs Lark distinction this branch introduced. */}
- <a
- href={manageHref}
- target="_blank"
- rel="noopener noreferrer"
- className="inline-flex items-center gap-1 text-caption text-muted-foreground underline-offset-2 transition-colors hover:text-foreground hover:underline"
- title={
- installation.region === "lark"
- ? t(($) => $.lark.agent_bot_manage_tooltip_lark)
- : t(($) => $.lark.agent_bot_manage_tooltip_feishu)
- }
- >
- <ExternalLink className="h-3 w-3" />
- {installation.region === "lark"
- ? t(($) => $.lark.agent_bot_manage_link_lark)
- : t(($) => $.lark.agent_bot_manage_link_feishu)}
- </a>
-
- {/* Keep troubleshooting reachable after the install dialog closes. */}
- <p className="text-caption text-muted-foreground">
- <a
- href={larkDocsUrl(i18n.language)}
- target="_blank"
- rel="noopener noreferrer"
- className="underline underline-offset-2 transition-colors hover:text-foreground"
- >
- {t(($) => $.lark.agent_bot_silent_hint_link)}
- </a>
- </p>
-
- <AlertDialog
- open={confirmOpen}
- onOpenChange={(v) => {
- if (!v && !disconnecting) setConfirmOpen(false);
- }}
- >
- <AlertDialogContent>
- <AlertDialogHeader>
- <AlertDialogTitle>
- {t(($) => $.lark.disconnect_confirm_title)}
- </AlertDialogTitle>
- <AlertDialogDescription>
- {t(($) => $.lark.disconnect_confirm_description)}
- </AlertDialogDescription>
- </AlertDialogHeader>
- <AlertDialogFooter>
- <AlertDialogCancel disabled={disconnecting}>
- {t(($) => $.lark.disconnect_confirm_cancel)}
- </AlertDialogCancel>
- <AlertDialogAction
- onClick={handleDisconnect}
- disabled={disconnecting}
- >
- {disconnecting
- ? t(($) => $.lark.disconnecting)
- : t(($) => $.lark.disconnect)}
- </AlertDialogAction>
- </AlertDialogFooter>
- </AlertDialogContent>
- </AlertDialog>
- </div>
- );
-}
-
-// LarkInstallDialog walks the user through the device-flow install:
-// 1) POST /lark/install/begin?region=<feishu|lark> → render QR
-// 2) poll /lark/install/{sessionId}/status until success | error | expiry
-// 3) on success: toast, close, invalidate installations cache
-//
-// The dialog deliberately re-fetches a fresh session on each "retry"
-// rather than reusing a stale device_code — Lark's device_code is
-// single-use and a re-render of the same QR after an error would just
-// fail again at the next poll.
-//
-// region is a required prop so the begin POST hits the right cloud
-// (accounts.feishu.cn vs accounts.larksuite.com) and the dialog copy
-// (title, scan hint, link fallback) reflects the cloud the user
-// picked. Defaulting it would silently route Lark users to a Feishu QR
-// — exactly the confusion this split-CTA refactor is meant to remove.
-function LarkInstallDialog({
- wsId,
- agentId,
- agentName,
- region,
- onClose,
-}: {
- wsId: string;
- agentId: string;
- agentName?: string;
- region: "feishu" | "lark";
- onClose: () => void;
-}) {
- const { t } = useT("settings");
- const qc = useQueryClient();
-
- // We track session lifecycle as local state because TanStack Query is
- // optimized for cached server reads, and this dialog is a one-shot
- // flow whose entire state collapses on close. Using `useQuery` for
- // the polling would also fight TanStack's default refetch heuristics
- // (window focus, online/offline, retries) that have the wrong shape
- // for a single bounded session.
- const [session, setSession] = useState<null | {
- sessionId: string;
- qrCodeURL: string;
- expiresInSeconds: number;
- pollIntervalSeconds: number;
- }>(null);
- const [status, setStatus] = useState<LarkInstallStatusResponse["status"]>("pending");
- const [errorReason, setErrorReason] = useState<string | null>(null);
- const [errorMessage, setErrorMessage] = useState<string | null>(null);
- const [beginning, setBeginning] = useState(false);
- const closedRef = useRef(false);
-
- // beginSession is callable from both the initial mount and the
- // "scan again" action. Wrapping in a function (instead of a useEffect
- // dependency cascade) makes the retry path explicit.
- async function beginSession() {
- setBeginning(true);
- setStatus("pending");
- setErrorReason(null);
- setErrorMessage(null);
- setSession(null);
- try {
- const res = await api.beginLarkInstall(wsId, agentId, region);
- if (closedRef.current) return;
- setSession({
- sessionId: res.session_id,
- qrCodeURL: res.qr_code_url,
- expiresInSeconds: res.expires_in_seconds,
- pollIntervalSeconds: res.poll_interval_seconds,
- });
- } catch (e) {
- if (closedRef.current) return;
- setStatus("error");
- setErrorReason("internal_error");
- setErrorMessage(e instanceof Error ? e.message : String(e));
- } finally {
- setBeginning(false);
- }
- }
-
- // Kick off on mount.
- //
- // Reset closedRef AT THE START of every mount, not just at construction.
- // React 18+ / 19 StrictMode dev runs effects twice (mount → cleanup →
- // mount) on the same component instance, which preserves useRef across
- // the simulated remount. Without resetting, the cleanup from mount #1
- // flips closedRef.current=true, and on mount #2 every beginSession
- // promise sees closedRef=true at the await boundary and early-exits
- // before calling setSession — leaving the dialog body empty (no
- // "starting" placeholder, no QR, no error), which is exactly the
- // "QR never appears" bug. Reset on entry so the second mount
- // re-arms the in-flight cancellation guard.
- useEffect(() => {
- closedRef.current = false;
- void beginSession();
- return () => {
- closedRef.current = true;
- };
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, []);
-
- // Polling loop. Bounded by the device-flow expiry — once that
- // elapses Lark's server returns expired_token and our backend marks
- // the session errored, so we don't need a separate client-side
- // expiry timer.
- useEffect(() => {
- if (!session || status !== "pending") return;
- const intervalMs = Math.max(2000, session.pollIntervalSeconds * 1000);
- let cancelled = false;
- let timer: ReturnType<typeof setTimeout> | null = null;
-
- const poll = async () => {
- if (cancelled) return;
- try {
- const res = await api.getLarkInstallStatus(wsId, session.sessionId);
- if (cancelled) return;
- setStatus(res.status);
- if (res.status === "success") {
- await qc.invalidateQueries({ queryKey: larkKeys.installations(wsId) });
- toast.success(
- region === "lark"
- ? t(($) => $.lark.install_success_toast_lark)
- : t(($) => $.lark.install_success_toast_feishu),
- );
- // Close after a tiny beat so the user sees the success state
- // briefly before the dialog disappears.
- setTimeout(() => {
- if (!cancelled) onClose();
- }, 800);
- return;
- }
- if (res.status === "error") {
- setErrorReason(res.error_reason ?? "internal_error");
- setErrorMessage(res.error_message ?? null);
- return;
- }
- timer = setTimeout(poll, intervalMs);
- } catch (e) {
- if (cancelled) return;
- // Terminal HTTP states must NOT be retried — the session is
- // gone or the caller has lost permission, and polling forever
- // would trap the user on a stale QR with no error feedback.
- // 404: server restarted, multi-instance routed elsewhere, or
- // the in-process GC swept the session. Treat as session
- // lost — user has to scan a fresh QR.
- // 403: permission revoked mid-session (role downgrade, etc.).
- // The CTA gate prevents this on entry, but a role change
- // while the dialog is open would land here.
- // 401: the global ApiClient interceptor handles re-auth, so
- // reaching the catch with 401 means re-auth itself
- // failed — treat as terminal so the user doesn't loop.
- if (e instanceof ApiError) {
- if (e.status === 404) {
- setStatus("error");
- setErrorReason("session_lost");
- setErrorMessage(e.message);
- return;
- }
- if (e.status === 403 || e.status === 401) {
- setStatus("error");
- setErrorReason("forbidden");
- setErrorMessage(e.message);
- return;
- }
- }
- // Transient errors (network blip, 5xx) — schedule another
- // poll rather than killing the session. The next backend
- // status read will either confirm pending or surface the
- // terminal error the polling goroutine recorded.
- timer = setTimeout(poll, intervalMs);
- // Surface the message as a non-blocking toast for diagnostics.
- toast.message(t(($) => $.lark.install_poll_retry), {
- description: e instanceof Error ? e.message : String(e),
- });
- }
- };
-
- timer = setTimeout(poll, intervalMs);
- return () => {
- cancelled = true;
- if (timer) clearTimeout(timer);
- };
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [session?.sessionId, status]);
-
- return (
- <Dialog
- open
- onOpenChange={(o) => {
- if (!o) onClose();
- }}
- >
- <DialogContent className="max-w-sm">
- <DialogHeader>
- <DialogTitle>
- {region === "lark"
- ? t(($) => $.lark.install_dialog_title_lark)
- : t(($) => $.lark.install_dialog_title_feishu)}
- </DialogTitle>
- <DialogDescription>
- {region === "lark"
- ? agentName
- ? t(($) => $.lark.install_dialog_description_for_agent_lark, { agent: agentName })
- : t(($) => $.lark.install_dialog_description_lark)
- : agentName
- ? t(($) => $.lark.install_dialog_description_for_agent_feishu, { agent: agentName })
- : t(($) => $.lark.install_dialog_description_feishu)}
- </DialogDescription>
- </DialogHeader>
-
- <div className="flex flex-col items-center gap-4 py-2">
- {beginning && !session && (
- <p className="text-body text-muted-foreground">{t(($) => $.lark.install_starting)}</p>
- )}
-
- {session && status === "pending" && (
- <>
- <div className="rounded-md border bg-white p-3">
- {/* react-qr-code renders an inline SVG — no external
- network image dependency, prints at any DPI. */}
- <QRCode value={session.qrCodeURL} size={192} />
- </div>
- <a
- href={session.qrCodeURL}
- target="_blank"
- rel="noopener noreferrer"
- className="text-caption underline text-muted-foreground"
- >
- {region === "lark"
- ? t(($) => $.lark.install_open_link_fallback_lark)
- : t(($) => $.lark.install_open_link_fallback_feishu)}
- </a>
- </>
- )}
-
- {status === "success" && (
- <p className="text-body font-medium">{t(($) => $.lark.install_success)}</p>
- )}
-
- {status === "error" && (
- <div className="space-y-2 text-center">
- <p className="text-body font-medium text-destructive">
- {(() => {
- switch (errorReason) {
- case "expired":
- return t(($) => $.lark.install_error_expired);
- case "access_denied":
- return t(($) => $.lark.install_error_access_denied);
- case "lark_protocol_error":
- return t(($) => $.lark.install_error_protocol);
- case "bot_info_failed":
- return t(($) => $.lark.install_error_bot_info);
- case "installation_conflict":
- return t(($) => $.lark.install_error_conflict);
- case "installer_bind_failed":
- return t(($) => $.lark.install_error_installer_bind);
- case "session_lost":
- return t(($) => $.lark.install_error_session_lost);
- case "forbidden":
- return t(($) => $.lark.install_error_forbidden);
- default:
- return t(($) => $.lark.install_error_generic);
- }
- })()}
- </p>
- {errorMessage && (
- <p className="text-micro text-muted-foreground break-all">
- {errorMessage}
- </p>
- )}
- </div>
- )}
- </div>
-
- <DialogFooter>
- {status === "error" ? (
- <>
- <Button variant="outline" size="sm" onClick={onClose}>
- {t(($) => $.lark.install_close)}
- </Button>
- <Button size="sm" onClick={beginSession} disabled={beginning}>
- <RefreshCw className="h-3 w-3" />
- {t(($) => $.lark.install_retry)}
- </Button>
- </>
- ) : (
- <Button variant="outline" size="sm" onClick={onClose}>
- {t(($) => $.lark.install_close)}
- </Button>
- )}
- </DialogFooter>
- </DialogContent>
- </Dialog>
- );
-}
diff --git a/packages/views/settings/components/messaging-channels.test.tsx b/packages/views/settings/components/messaging-channels.test.tsx
new file mode 100644
index 0000000000..5130e9abe3
--- /dev/null
+++ b/packages/views/settings/components/messaging-channels.test.tsx
@@ -0,0 +1,599 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { fireEvent, screen, waitFor, within } from "@testing-library/react";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import type { Agent } from "@multica/core/types";
+import { renderWithI18n } from "../../test/i18n";
+import { api, ApiError } from "@multica/core/api";
+import {
+ AgentChannelsSection,
+ AgentChannelLinks,
+} from "../../agents/components/agent-channels-section";
+import { ChannelsTab } from "./channels-tab";
+import { ChannelConnectDialog } from "./channel-connect-dialog";
+
+const state = vi.hoisted(() => ({
+ role: "admin",
+ member: true,
+ search: "tab=channels",
+ replace: vi.fn(),
+ open: vi.fn(),
+}));
+vi.mock("@multica/core/hooks", () => ({ useWorkspaceId: () => "ws-1" }));
+vi.mock("@multica/core/permissions", () => ({
+ useCurrentMember: () => ({
+ role: state.role,
+ userId: "user-1",
+ member: state.member ? { role: state.role } : null,
+ }),
+}));
+vi.mock("@multica/core/paths", () => ({
+ useCurrentWorkspace: () => ({ id: "ws-1", name: "Acme" }),
+ useWorkspacePaths: () => ({
+ agentDetail: (id: string) => `/acme/agents/${id}`,
+ }),
+}));
+vi.mock("../../navigation/context", async (original) => ({
+ ...(await original<typeof import("../../navigation/context")>()),
+ useNavigation: () => ({
+ pathname: "/acme/settings",
+ searchParams: new URLSearchParams(state.search),
+ replace: state.replace,
+ push: vi.fn(),
+ }),
+}));
+vi.mock("../../platform", () => ({ openExternal: state.open }));
+vi.mock("../../common/actor-avatar", () => ({
+ ActorAvatar: ({ actorId }: { actorId: string }) => (
+ <span data-testid={`avatar-${actorId}`} />
+ ),
+}));
+vi.mock("@multica/core/api", async (original) => ({
+ ...(await original<typeof import("@multica/core/api")>()),
+ api: Object.fromEntries(
+ [
+ "listLarkInstallations",
+ "listSlackInstallations",
+ "listDingTalkInstallations",
+ "listWecomInstallations",
+ "listTelegramInstallations",
+ "registerSlackBYO",
+ "registerDingTalkBYO",
+ "registerWecomBYO",
+ "registerTelegramBot",
+ "deleteLarkInstallation",
+ "deleteSlackInstallation",
+ "deleteDingTalkInstallation",
+ "deleteWecomInstallation",
+ "deleteTelegramInstallation",
+ "listAgentDingTalkGroups",
+ "listAgents",
+ "beginLarkInstall",
+ "getLarkInstallStatus",
+ "beginWecomInstall",
+ "getWecomInstallStatus",
+ ].map((name) => [name, vi.fn()]),
+ ),
+}));
+
+const agent = {
+ id: "agent-1",
+ name: "Mika",
+ owner_id: "user-1",
+ archived_at: null,
+} as Agent;
+const otherAgent = {
+ ...agent,
+ id: "agent-2",
+ name: "Support",
+ owner_id: "user-2",
+};
+const active = {
+ id: "i1",
+ workspace_id: "ws-1",
+ agent_id: agent.id,
+ status: "active",
+};
+const listing = (installations: unknown[] = []) => ({
+ configured: true,
+ install_supported: true,
+ installations,
+});
+
+function show(ui: React.ReactElement) {
+ const qc = new QueryClient({
+ defaultOptions: { queries: { retry: false, gcTime: 0 } },
+ });
+ return {
+ ...renderWithI18n(
+ <QueryClientProvider client={qc}>{ui}</QueryClientProvider>,
+ ),
+ qc,
+ };
+}
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ state.role = "admin";
+ state.member = true;
+ state.search = "tab=channels";
+ for (const name of [
+ "listLarkInstallations",
+ "listSlackInstallations",
+ "listDingTalkInstallations",
+ "listWecomInstallations",
+ "listTelegramInstallations",
+ ] as const) {
+ vi.mocked(api[name]).mockResolvedValue(listing() as never);
+ }
+ vi.mocked(api.listAgents).mockResolvedValue([agent, otherAgent]);
+ vi.mocked(api.listAgentDingTalkGroups).mockResolvedValue({
+ groups: [],
+ group_discovery_supported: false,
+ });
+ vi.mocked(api.beginLarkInstall).mockResolvedValue({
+ session_id: "s1",
+ qr_code_url: "https://accounts.feishu.cn/example",
+ expires_in_seconds: 300,
+ poll_interval_seconds: 2,
+ });
+});
+
+describe("agent messaging channels", () => {
+ it.each([
+ ["feishu", "open.feishu.cn", "Manage in Feishu"],
+ ["lark", "open.larksuite.com", "Manage in Lark"],
+ [undefined, "open.feishu.cn", "Manage in Feishu"],
+ ])(
+ "keeps management and troubleshooting available for an existing %s bot",
+ async (region, host, label) => {
+ vi.mocked(api.listLarkInstallations).mockResolvedValue({
+ ...listing([{ ...active, app_id: "cli_a&b", region }]),
+ install_supported: false,
+ } as never);
+ show(<AgentChannelsSection agent={agent} />);
+ fireEvent.click(
+ await screen.findByRole("button", { name: "Manage Lark" }),
+ );
+ fireEvent.click(await screen.findByRole("menuitem", { name: label }));
+ expect(state.open).toHaveBeenCalledWith(`https://${host}/app/cli_a%26b`);
+ fireEvent.click(screen.getByRole("button", { name: "Manage Lark" }));
+ fireEvent.click(
+ await screen.findByRole("menuitem", { name: "Troubleshooting" }),
+ );
+ expect(state.open).toHaveBeenCalledWith(
+ "https://multica.ai/docs/lark-bot-integration",
+ );
+ },
+ );
+
+ it("shows actionable DingTalk permission help instead of a healthy status", async () => {
+ vi.mocked(api.listDingTalkInstallations).mockResolvedValue(
+ listing([active]) as never,
+ );
+ vi.mocked(api.listAgentDingTalkGroups).mockResolvedValue({
+ groups: [],
+ group_discovery_supported: true,
+ bot_identities: {
+ i1: {
+ installation_id: "i1",
+ agent_id: agent.id,
+ bot_name: "",
+ bot_identity_issue: "missing_qyapi_chat_manage",
+ },
+ },
+ });
+ show(<AgentChannelsSection agent={agent} />);
+ expect(await screen.findByText("qyapi_chat_manage")).toBeInTheDocument();
+ expect(screen.getByText("Identity unavailable")).toBeInTheDocument();
+ expect(screen.getByText(/then @mention the bot again/)).toBeInTheDocument();
+ expect(screen.queryByText("Connected", { exact: true })).toBeNull();
+ });
+
+ it("keeps recovery controls hidden for members who cannot manage the bot", async () => {
+ state.role = "member";
+ vi.mocked(api.listLarkInstallations).mockResolvedValue(
+ listing([
+ { ...active, agent_id: otherAgent.id, app_id: "cli_readonly" },
+ ]) as never,
+ );
+ vi.mocked(api.listDingTalkInstallations).mockResolvedValue(
+ listing([{ ...active, id: "d1", agent_id: otherAgent.id }]) as never,
+ );
+ vi.mocked(api.listAgentDingTalkGroups).mockResolvedValue({
+ groups: [],
+ group_discovery_supported: true,
+ bot_identities: {
+ d1: {
+ installation_id: "d1",
+ agent_id: otherAgent.id,
+ bot_name: "",
+ bot_identity_issue: "missing_qyapi_chat_manage",
+ },
+ },
+ });
+ show(<AgentChannelsSection agent={otherAgent} />);
+ expect(await screen.findByText("Identity unavailable")).toBeInTheDocument();
+ expect(screen.queryByRole("button", { name: "Manage Lark" })).toBeNull();
+ expect(screen.queryByText("qyapi_chat_manage")).toBeNull();
+ });
+ it("does not offer management to someone without workspace membership", async () => {
+ state.member = false;
+ const { container } = show(<AgentChannelsSection agent={agent} />);
+ expect(
+ screen.queryByRole("button", { name: "Add messaging channel" }),
+ ).toBeNull();
+ expect(container).toBeEmptyDOMElement();
+ expect(api.listLarkInstallations).not.toHaveBeenCalled();
+ });
+ it("hides the empty section from a member who cannot manage the agent", async () => {
+ state.role = "member";
+ const { container } = show(<AgentChannelsSection agent={otherAgent} />);
+ await waitFor(() =>
+ expect(api.listTelegramInstallations).toHaveBeenCalled(),
+ );
+ expect(container).toBeEmptyDOMElement();
+ });
+
+ it("gives an agent owner Lark and DingTalk, with admin-only platforms labelled", async () => {
+ state.role = "member";
+ show(<AgentChannelsSection agent={agent} />);
+ await waitFor(() =>
+ expect(
+ screen.getAllByRole("button", { name: "Add messaging channel" }).length,
+ ).toBeGreaterThan(0),
+ );
+ fireEvent.click(
+ screen.getAllByRole("button", { name: "Add messaging channel" })[0]!,
+ );
+ const dialog = await screen.findByRole("dialog");
+ expect(
+ within(dialog).getByRole("button", { name: /^Feishu$/ }),
+ ).toBeEnabled();
+ expect(
+ within(dialog).getByRole("button", { name: /^DingTalk$/ }),
+ ).toBeEnabled();
+ expect(
+ within(dialog).getByRole("button", { name: /Slack Ask an admin/ }),
+ ).toBeDisabled();
+ expect(
+ within(dialog).getByRole("button", { name: /Telegram Ask an admin/ }),
+ ).toBeDisabled();
+ expect(
+ within(dialog).getByRole("button", { name: /WeCom Ask an admin/ }),
+ ).toBeDisabled();
+ });
+
+ it("hides unconfigured platforms from members", async () => {
+ state.role = "member";
+ vi.mocked(api.listSlackInstallations).mockResolvedValue({
+ configured: false,
+ installations: [],
+ });
+ show(
+ <ChannelConnectDialog
+ agents={[agent]}
+ initialAgent={agent}
+ open
+ onOpenChange={vi.fn()}
+ />,
+ );
+ await screen.findByRole("button", { name: /^DingTalk$/ });
+ expect(screen.queryByRole("button", { name: /Slack/ })).toBeNull();
+ });
+
+ it("shows connected channels and a chat link to a read-only member", async () => {
+ state.role = "member";
+ vi.mocked(api.listTelegramInstallations).mockResolvedValue(
+ listing([{ ...active, bot_username: "mika_bot" }]) as never,
+ );
+ show(
+ <>
+ <AgentChannelLinks agent={otherAgent} />
+ <AgentChannelsSection agent={otherAgent} />
+ <AgentChannelsSection agent={agent} />
+ <AgentChannelLinks agent={agent} />
+ </>,
+ );
+ fireEvent.click(
+ await screen.findByRole("button", { name: "Find me on Telegram" }),
+ );
+ expect(state.open).toHaveBeenCalledWith("https://t.me/mika_bot");
+ expect(
+ screen.queryByRole("button", { name: "Manage Telegram" }),
+ ).toBeNull();
+ });
+
+ it("updates Lark from waiting to connected when inbound evidence arrives", async () => {
+ vi.mocked(api.listLarkInstallations).mockResolvedValue(
+ listing([{ ...active, app_id: "cli_mika" }]) as never,
+ );
+ const { qc } = show(<AgentChannelsSection agent={agent} />);
+ expect(
+ await screen.findByText("Waiting for first message"),
+ ).toBeInTheDocument();
+ qc.setQueryData(
+ ["lark", "ws-1", "installations"],
+ listing([
+ {
+ ...active,
+ app_id: "cli_mika",
+ first_message_received_at: "2026-11-10T00:00:00Z",
+ },
+ ]),
+ );
+ await waitFor(() =>
+ expect(screen.queryByText("Waiting for first message")).toBeNull(),
+ );
+ expect(screen.getByText("Connected")).toBeInTheDocument();
+ });
+
+ it("does not display revoked connections or another agent's connection", async () => {
+ vi.mocked(api.listTelegramInstallations).mockResolvedValue(
+ listing([
+ { ...active, status: "revoked" },
+ { ...active, id: "i2", agent_id: "agent-2" },
+ ]) as never,
+ );
+ show(<AgentChannelsSection agent={agent} />);
+ await screen.findAllByRole("button", { name: "Add messaging channel" });
+ expect(screen.queryByText("Telegram")).toBeNull();
+ });
+
+ it.each(["lark", "slack", "dingtalk", "wecom", "telegram"] as const)(
+ "confirms %s disconnect and preserves the connection on failure",
+ async (channel) => {
+ const methods = {
+ lark: ["listLarkInstallations", "deleteLarkInstallation"],
+ slack: ["listSlackInstallations", "deleteSlackInstallation"],
+ dingtalk: ["listDingTalkInstallations", "deleteDingTalkInstallation"],
+ wecom: ["listWecomInstallations", "deleteWecomInstallation"],
+ telegram: ["listTelegramInstallations", "deleteTelegramInstallation"],
+ } as const;
+ const [list, remove] = methods[channel];
+ vi.mocked(api[list]).mockResolvedValue(listing([active]) as never);
+ vi.mocked(api[remove])
+ .mockRejectedValueOnce(new Error("Disconnect failed"))
+ .mockResolvedValueOnce(undefined);
+ show(<AgentChannelsSection agent={agent} />);
+ fireEvent.click(await screen.findByRole("button", { name: /^Manage / }));
+ fireEvent.click(
+ await screen.findByRole("menuitem", { name: "Disconnect" }),
+ );
+ const dialog = await screen.findByRole("alertdialog");
+ expect(api[remove]).not.toHaveBeenCalled();
+ fireEvent.click(
+ within(dialog).getByRole("button", { name: "Disconnect" }),
+ );
+ await waitFor(() =>
+ expect(api[remove]).toHaveBeenCalledWith("ws-1", "i1"),
+ );
+ await waitFor(() =>
+ expect(
+ within(dialog).getByRole("button", { name: "Disconnect" }),
+ ).toBeEnabled(),
+ );
+ expect(dialog).toBeInTheDocument();
+ fireEvent.click(
+ within(dialog).getByRole("button", { name: "Disconnect" }),
+ );
+ await waitFor(() => expect(screen.queryByRole("alertdialog")).toBeNull());
+ },
+ );
+});
+
+describe("shared connection dialog", () => {
+ it("offers only Feishu for new connections while international Lark is disabled", async () => {
+ show(
+ <ChannelConnectDialog
+ agents={[agent]}
+ initialAgent={agent}
+ initialChannel="lark"
+ open
+ onOpenChange={vi.fn()}
+ />,
+ );
+ await waitFor(() =>
+ expect(screen.getByRole("button", { name: "Continue" })).toBeEnabled(),
+ );
+ expect(screen.getByRole("button", { name: "Feishu" })).toBeEnabled();
+ expect(screen.queryByRole("button", { name: "Lark" })).toBeNull();
+ expect(
+ screen.queryByRole("option", { name: "Lark (International)" }),
+ ).toBeNull();
+ fireEvent.click(screen.getByRole("button", { name: "Continue" }));
+ await waitFor(() =>
+ expect(api.beginLarkInstall).toHaveBeenCalledWith(
+ "ws-1",
+ "agent-1",
+ "feishu",
+ ),
+ );
+ });
+
+ it("offers the WeCom QR flow only when the server supports it", async () => {
+ vi.mocked(api.listWecomInstallations).mockResolvedValue({
+ configured: true,
+ install_supported: true,
+ scan_install_supported: true,
+ installations: [],
+ });
+ vi.mocked(api.beginWecomInstall).mockResolvedValue({
+ session_id: "wecom-session",
+ status: "creating",
+ poll_interval_seconds: 1,
+ });
+ show(
+ <ChannelConnectDialog
+ agents={[agent]}
+ initialAgent={agent}
+ initialChannel="wecom"
+ open
+ onOpenChange={vi.fn()}
+ />,
+ );
+ await waitFor(() =>
+ expect(screen.getByRole("button", { name: "Continue" })).toBeEnabled(),
+ );
+ expect(screen.getByLabelText("Connection method")).toHaveValue("scan");
+ fireEvent.click(screen.getByRole("button", { name: "Continue" }));
+ await screen.findByTestId("wecom-scan-starting");
+ expect(api.beginWecomInstall).toHaveBeenCalledWith(
+ "ws-1",
+ "agent-1",
+ expect.any(String),
+ );
+ expect(api.registerWecomBYO).not.toHaveBeenCalled();
+ });
+
+ it.each([
+ [
+ "slack",
+ "registerSlackBYO",
+ ["Bot token (xoxb-)", "App-level token (xapp-)"],
+ { bot_token: "first", app_token: "second" },
+ ],
+ [
+ "dingtalk",
+ "registerDingTalkBYO",
+ ["AppKey (client id)", "AppSecret (client secret)"],
+ { client_id: "first", client_secret: "second" },
+ ],
+ [
+ "wecom",
+ "registerWecomBYO",
+ ["Bot ID", "Long-connection secret"],
+ { bot_id: "first", secret: "second", bot_name: undefined },
+ ],
+ ["telegram", "registerTelegramBot", ["Bot token"], { bot_token: "first" }],
+ ] as const)(
+ "submits %s through the existing API and closes after success",
+ async (channel, method, labels, payload) => {
+ const close = vi.fn();
+ vi.mocked(api[method]).mockResolvedValue(active as never);
+ show(
+ <ChannelConnectDialog
+ agents={[agent]}
+ initialAgent={agent}
+ initialChannel={channel}
+ open
+ onOpenChange={close}
+ />,
+ );
+ const next = screen.getByRole("button", { name: "Continue" });
+ await waitFor(() => expect(next).toBeEnabled());
+ fireEvent.click(next);
+ labels.forEach((label, index) =>
+ fireEvent.change(screen.getByLabelText(label), {
+ target: { value: index === 0 ? " first " : " second " },
+ }),
+ );
+ expect(screen.getByLabelText(labels.at(-1)!)).toHaveAttribute(
+ "type",
+ "password",
+ );
+ fireEvent.click(screen.getByRole("button", { name: "Connect" }));
+ await waitFor(() =>
+ expect(api[method]).toHaveBeenCalledWith("ws-1", "agent-1", payload),
+ );
+ await waitFor(() => expect(close).toHaveBeenCalledWith(false));
+ },
+ );
+
+ it("keeps inputs and localized WeCom errors after rejected credentials", async () => {
+ vi.mocked(api.registerWecomBYO).mockRejectedValue(
+ new ApiError("English server detail", 400, "Bad Request", {
+ code: "wecom_credentials_rejected",
+ }),
+ );
+ show(
+ <ChannelConnectDialog
+ agents={[agent]}
+ initialAgent={agent}
+ initialChannel="wecom"
+ open
+ onOpenChange={vi.fn()}
+ />,
+ );
+ await waitFor(() =>
+ expect(screen.getByRole("button", { name: "Continue" })).toBeEnabled(),
+ );
+ fireEvent.click(screen.getByRole("button", { name: "Continue" }));
+ fireEvent.change(screen.getByLabelText("Bot ID"), {
+ target: { value: "bot" },
+ });
+ fireEvent.change(screen.getByLabelText("Long-connection secret"), {
+ target: { value: "secret" },
+ });
+ fireEvent.click(screen.getByRole("button", { name: "Connect" }));
+ expect(await screen.findByRole("alert")).not.toHaveTextContent(
+ "English server detail",
+ );
+ expect(screen.getByLabelText("Long-connection secret")).toHaveValue(
+ "secret",
+ );
+ });
+
+ it("requires an agent selection when opened from the overview", async () => {
+ show(
+ <ChannelConnectDialog
+ agents={[agent, otherAgent]}
+ initialChannel="telegram"
+ open
+ onOpenChange={vi.fn()}
+ />,
+ );
+ expect(screen.getByRole("button", { name: "Continue" })).toBeDisabled();
+ fireEvent.change(screen.getByLabelText("Agent"), {
+ target: { value: "agent-2" },
+ });
+ await waitFor(() =>
+ expect(screen.getByRole("button", { name: "Continue" })).toBeEnabled(),
+ );
+ });
+});
+
+describe("workspace overview", () => {
+ it("lets admins disconnect an installation whose agent was deleted", async () => {
+ vi.mocked(api.listTelegramInstallations).mockResolvedValue(
+ listing([{ ...active, agent_id: "deleted-agent" }]) as never,
+ );
+ vi.mocked(api.deleteTelegramInstallation).mockResolvedValue(undefined);
+ show(<ChannelsTab />);
+ expect(await screen.findByText("Agent unavailable")).toBeInTheDocument();
+ fireEvent.click(screen.getByRole("button", { name: "Disconnect" }));
+ const dialog = await screen.findByRole("alertdialog");
+ expect(api.deleteTelegramInstallation).not.toHaveBeenCalled();
+ fireEvent.click(within(dialog).getByRole("button", { name: "Disconnect" }));
+ await waitFor(() =>
+ expect(api.deleteTelegramInstallation).toHaveBeenCalledWith("ws-1", "i1"),
+ );
+ });
+
+ it("links each connected agent to their channels, and redirects old detail links", async () => {
+ state.search = "tab=channels&integration=slack";
+ vi.mocked(api.listSlackInstallations).mockResolvedValue(
+ listing([active]) as never,
+ );
+ show(<ChannelsTab />);
+ expect(await screen.findByRole("link", { name: "Mika" })).toHaveAttribute(
+ "href",
+ "/acme/agents/agent-1?view=channels",
+ );
+ expect(state.replace).toHaveBeenCalledWith("/acme/settings?tab=channels");
+ expect(screen.getByText("Who can connect")).toBeInTheDocument();
+ expect(screen.getAllByRole("button", { name: "Connect" })).toHaveLength(5);
+ });
+
+ it("reports failed reads as unavailable and keeps a retry control", async () => {
+ vi.mocked(api.listTelegramInstallations).mockRejectedValue(
+ new Error("offline"),
+ );
+ show(<ChannelsTab />);
+ expect(await screen.findByRole("alert")).toHaveTextContent(
+ "Status unavailable",
+ );
+ expect(
+ screen.getByRole("button", { name: "Scan again" }),
+ ).toBeInTheDocument();
+ });
+});
diff --git a/packages/views/settings/components/settings-navigation.test.ts b/packages/views/settings/components/settings-navigation.test.ts
index a60e060780..fa93c726f5 100644
--- a/packages/views/settings/components/settings-navigation.test.ts
+++ b/packages/views/settings/components/settings-navigation.test.ts
@@ -23,11 +23,12 @@ describe("settings location", () => {
"tab=preferences&section=style",
{ tab: "appearance", section: "theme", integration: null },
],
- ["tab=lark", { tab: "channels", section: null, integration: "lark" }],
+ ["tab=lark", { tab: "channels", section: null, integration: null }],
[
"tab=integrations&integration=slack",
- { tab: "channels", section: null, integration: "slack" },
+ { tab: "channels", section: null, integration: null },
],
+ ["tab=channels&integration=telegram", { tab: "channels", section: null, integration: null }],
["tab=integrations", { tab: "channels", section: null, integration: null }],
[
"tab=integrations&integration=vcs",
diff --git a/packages/views/settings/components/settings-navigation.ts b/packages/views/settings/components/settings-navigation.ts
index 7ac75ffaaf..f2d745d214 100644
--- a/packages/views/settings/components/settings-navigation.ts
+++ b/packages/views/settings/components/settings-navigation.ts
@@ -30,7 +30,7 @@ export interface SettingsLocation {
tab: string;
/** In-page anchor to scroll to (see `SettingsSection`/`SettingsRow`). */
section: string | null;
- /** Detail page within Channels. */
+ /** Reserved for settings locations outside messaging. */
integration: string | null;
}
@@ -64,6 +64,8 @@ export function resolveSettingsLocation(
return { tab: "code", section, integration: null };
case "repositories":
return { tab: "code", section: section ?? "repositories", integration: null };
+ case "channels":
+ return { tab: "channels", section, integration: null };
case "integrations": {
const composioCallback =
params.has("connected") ||
@@ -80,12 +82,12 @@ export function resolveSettingsLocation(
return {
tab: "channels",
section: null,
- integration: isChannelIntegration(integration) ? integration : null,
+ integration: null,
};
}
default:
if (isChannelIntegration(tab)) {
- return { tab: "channels", section: null, integration: tab };
+ return { tab: "channels", section: null, integration: null };
}
return { tab, section, integration };
}
diff --git a/packages/views/settings/components/slack-tab.test.tsx b/packages/views/settings/components/slack-tab.test.tsx
deleted file mode 100644
index 2055a014e2..0000000000
--- a/packages/views/settings/components/slack-tab.test.tsx
+++ /dev/null
@@ -1,181 +0,0 @@
-// @vitest-environment jsdom
-
-import { type ReactNode } from "react";
-import { describe, it, expect, beforeEach, vi } from "vitest";
-import { render, screen, waitFor } from "@testing-library/react";
-import userEvent from "@testing-library/user-event";
-import { I18nProvider } from "@multica/core/i18n/react";
-import enCommon from "../../locales/en/common.json";
-import enSettings from "../../locales/en/settings.json";
-
-type MemberRole = "owner" | "admin" | "member" | "guest";
-
-const membersRef = vi.hoisted(() => ({
- current: [{ user_id: "user-1", role: "owner" as MemberRole }],
-}));
-const installationsRef = vi.hoisted(() => ({
- current: {
- installations: [] as unknown[],
- configured: true,
- install_supported: true,
- },
-}));
-const mockRegisterBYO = vi.hoisted(() => vi.fn());
-const mockDeleteInstallation = vi.hoisted(() => vi.fn());
-const mockOpenExternal = vi.hoisted(() => vi.fn());
-const mockInvalidate = vi.hoisted(() => vi.fn());
-
-vi.mock("@tanstack/react-query", () => ({
- useQuery: (opts: { queryKey: unknown[]; enabled?: boolean }) => {
- if (opts.enabled === false) return { data: undefined, isLoading: false };
- const key = JSON.stringify(opts.queryKey);
- if (key.includes("members")) return { data: membersRef.current, isLoading: false };
- if (key.includes("installations")) return { data: installationsRef.current, isLoading: false };
- return { data: undefined, isLoading: false };
- },
- useQueryClient: () => ({ invalidateQueries: mockInvalidate }),
- queryOptions: <T,>(opts: T) => opts,
-}));
-
-vi.mock("@multica/core/hooks", () => ({ useWorkspaceId: () => "workspace-1" }));
-
-vi.mock("@multica/core/workspace/queries", () => ({
- memberListOptions: () => ({ queryKey: ["members"], queryFn: vi.fn() }),
-}));
-
-vi.mock("@multica/core/workspace/hooks", () => ({
- useActorName: () => ({
- getAgentName: (agentId: string) => `Agent ${agentId}`,
- getMemberName: () => "Unknown",
- getSquadName: () => "Unknown Squad",
- getActorName: () => "Unknown",
- getActorInitials: () => "??",
- getActorAvatarUrl: () => null,
- }),
-}));
-
-vi.mock("../../common/actor-avatar", () => ({
- ActorAvatar: ({ actorId }: { actorId: string }) => (
- <span data-testid="actor-avatar" data-actor-id={actorId} />
- ),
-}));
-
-vi.mock("@multica/core/slack", () => ({
- slackInstallationsOptions: () => ({
- queryKey: ["slack", "installations"],
- queryFn: vi.fn(),
- }),
- slackKeys: { installations: (wsId: string) => ["slack", "installations", wsId] },
-}));
-
-vi.mock("@multica/core/api", () => ({
- api: {
- registerSlackBYO: mockRegisterBYO,
- deleteSlackInstallation: mockDeleteInstallation,
- },
-}));
-
-vi.mock("@multica/core/auth", () => {
- const useAuthStore = Object.assign(
- (sel?: (s: { user: { id: string } }) => unknown) =>
- sel ? sel({ user: { id: "user-1" } }) : { user: { id: "user-1" } },
- { getState: () => ({ user: { id: "user-1" } }) },
- );
- return { useAuthStore };
-});
-
-vi.mock("sonner", () => ({
- toast: { success: vi.fn(), error: vi.fn(), message: vi.fn() },
-}));
-
-vi.mock("../../platform", () => ({ openExternal: mockOpenExternal }));
-
-import { SlackAgentBindButton, SlackTab } from "./slack-tab";
-
-const TEST_RESOURCES = { en: { common: enCommon, settings: enSettings } };
-
-function renderUI(children: ReactNode) {
- return render(
- <I18nProvider locale="en" resources={TEST_RESOURCES}>
- {children}
- </I18nProvider>,
- );
-}
-
-function resetFixtures() {
- vi.clearAllMocks();
- membersRef.current = [{ user_id: "user-1", role: "owner" }];
- installationsRef.current = { installations: [], configured: true, install_supported: true };
-}
-
-describe("SlackAgentBindButton", () => {
- beforeEach(resetFixtures);
-
- it("opens the BYO dialog and submits the pasted bot + app tokens", async () => {
- mockRegisterBYO.mockResolvedValue({ id: "i1", agent_id: "agent-1", status: "active" });
- renderUI(<SlackAgentBindButton agentId="agent-1" agentName="Bot" />);
- await userEvent.click(screen.getByTestId("slack-agent-connect"));
- const botInput = await screen.findByTestId("slack-byo-bot-token");
- await userEvent.type(botInput, "xoxb-bot");
- await userEvent.type(screen.getByTestId("slack-byo-app-token"), "xapp-1-A0X-1-secret");
- await userEvent.click(screen.getByTestId("slack-byo-submit"));
- await waitFor(() =>
- expect(mockRegisterBYO).toHaveBeenCalledWith("workspace-1", "agent-1", {
- bot_token: "xoxb-bot",
- app_token: "xapp-1-A0X-1-secret",
- }),
- );
- // No OAuth redirect anymore — install is a direct API call.
- expect(mockOpenExternal).not.toHaveBeenCalled();
- });
-
- it("shows the connected badge (not the CTA) when the agent already has an active install", () => {
- installationsRef.current = {
- installations: [{ id: "i1", agent_id: "agent-1", status: "active", team_id: "T1" }],
- configured: true,
- install_supported: true,
- };
- renderUI(<SlackAgentBindButton agentId="agent-1" />);
- expect(screen.getByTestId("slack-agent-bot-connected")).toBeTruthy();
- expect(screen.getByTestId("slack-agent-bot-disconnect")).toBeTruthy();
- expect(screen.queryByTestId("slack-agent-connect")).toBeNull();
- });
-
- it("renders nothing for a non-manager", () => {
- membersRef.current = [{ user_id: "user-1", role: "member" }];
- const { container } = renderUI(<SlackAgentBindButton agentId="agent-1" />);
- expect(container).toBeEmptyDOMElement();
- });
-
- it("renders nothing when install is unavailable and the agent is unbound", () => {
- installationsRef.current = { installations: [], configured: true, install_supported: false };
- const { container } = renderUI(<SlackAgentBindButton agentId="agent-1" />);
- expect(container).toBeEmptyDOMElement();
- });
-});
-
-describe("SlackTab", () => {
- beforeEach(resetFixtures);
-
- it("surfaces the not-enabled notice when the deployment has no Slack key", () => {
- installationsRef.current = { installations: [], configured: false, install_supported: false };
- renderUI(<SlackTab />);
- expect(screen.getByText(/Slack integration not enabled/i)).toBeTruthy();
- });
-
- it("shows the empty state when configured but nothing is connected", () => {
- renderUI(<SlackTab />);
- expect(screen.getByText(/No bots connected yet/i)).toBeTruthy();
- });
-
- it("lists a connected installation with its agent name and a disconnect control", () => {
- installationsRef.current = {
- installations: [{ id: "i1", agent_id: "agent-7", status: "active", team_id: "T1" }],
- configured: true,
- install_supported: true,
- };
- renderUI(<SlackTab />);
- expect(screen.getByText("Agent agent-7")).toBeTruthy();
- expect(screen.getByText(/Disconnect/i)).toBeTruthy();
- });
-});
diff --git a/packages/views/settings/components/slack-tab.tsx b/packages/views/settings/components/slack-tab.tsx
deleted file mode 100644
index b49e18408f..0000000000
--- a/packages/views/settings/components/slack-tab.tsx
+++ /dev/null
@@ -1,602 +0,0 @@
-"use client";
-
-import { useState } from "react";
-import { useQuery, useQueryClient } from "@tanstack/react-query";
-import { toast } from "sonner";
-import { ChevronRight, ExternalLink, Trash2 } from "@multica/ui/icons";
-import { SlackMark } from "./slack-mark";
-import { cn } from "@multica/ui/lib/utils";
-import { Button } from "@multica/ui/components/ui/button";
-import { Card, CardContent } from "@multica/ui/components/ui/card";
-import {
- Dialog,
- DialogContent,
- DialogFooter,
- DialogHeader,
- DialogTitle,
-} from "@multica/ui/components/ui/dialog";
-import { Input } from "@multica/ui/components/ui/input";
-import { Label } from "@multica/ui/components/ui/label";
-import {
- AlertDialog,
- AlertDialogAction,
- AlertDialogCancel,
- AlertDialogContent,
- AlertDialogDescription,
- AlertDialogFooter,
- AlertDialogHeader,
- AlertDialogTitle,
-} from "@multica/ui/components/ui/alert-dialog";
-import { useAuthStore } from "@multica/core/auth";
-import { useWorkspaceId } from "@multica/core/hooks";
-import { memberListOptions } from "@multica/core/workspace/queries";
-import { useActorName } from "@multica/core/workspace/hooks";
-import { slackInstallationsOptions, slackKeys } from "@multica/core/slack";
-import { api } from "@multica/core/api";
-import type { SlackInstallation } from "@multica/core/types";
-import { ActorAvatar } from "../../common/actor-avatar";
-import { docsLocalePrefix } from "../../common/docs-locale";
-import { openExternal } from "../../platform";
-import { useLocale, useT } from "../../i18n";
-import { TooltipHint } from "@multica/ui/components/common/tooltip-hint";
-
-// SlackTab is the workspace settings panel for Slack bot installations.
-// Listing is member-visible; the disconnect action is admin-only (the backend
-// enforces it; the UI hides the button for non-admins to match).
-//
-// Adding a new installation flows through the Agent detail page: the install
-// path is per-agent (each Multica agent gets exactly one bot — the
-// (workspace_id, agent_id, channel_type) UNIQUE in channel_installation), so
-// asking the user to pick an agent here would re-create that page's picker.
-export function SlackTab() {
- const { t } = useT("settings");
- const wsId = useWorkspaceId();
- const qc = useQueryClient();
- const user = useAuthStore((s) => s.user);
-
- const { data: members = [] } = useQuery(memberListOptions(wsId));
- const currentMember = members.find((m) => m.user_id === user?.id) ?? null;
- const canManage =
- currentMember?.role === "owner" || currentMember?.role === "admin";
-
- const { data, isLoading } = useQuery({
- ...slackInstallationsOptions(wsId),
- enabled: !!wsId,
- });
- const installations = data?.installations ?? [];
- const configured = data?.configured === true;
- // install_supported tracks whether the OAuth client credentials are wired on
- // the server. When false, "Connect Slack" would be rejected, so we hide the
- // connect entry points and surface a "coming soon" notice. Already-installed
- // bots still appear below and remain manageable.
- const installSupported = data?.install_supported === true;
-
- const [disconnectTarget, setDisconnectTarget] = useState<string | null>(null);
- const [disconnecting, setDisconnecting] = useState(false);
-
- async function handleDisconnect() {
- if (!disconnectTarget || disconnecting) return;
- setDisconnecting(true);
- try {
- await api.deleteSlackInstallation(wsId, disconnectTarget);
- await qc.invalidateQueries({ queryKey: slackKeys.installations(wsId) });
- toast.success(t(($) => $.slack.toast_disconnected));
- setDisconnectTarget(null);
- } catch (e) {
- toast.error(
- e instanceof Error ? e.message : t(($) => $.slack.toast_disconnect_failed),
- );
- } finally {
- setDisconnecting(false);
- }
- }
-
- return (
- <div className="space-y-8">
- {!configured ? (
- <Card>
- <CardContent className="space-y-2">
- <p className="text-body font-medium">{t(($) => $.slack.not_enabled_title)}</p>
- <p className="text-caption text-muted-foreground">
- {t(($) => $.slack.not_enabled_description_prefix)}{" "}
- <code className="rounded-xs bg-muted px-1 py-0.5 text-micro">
- MULTICA_SLACK_SECRET_KEY
- </code>{" "}
- {t(($) => $.slack.not_enabled_description_suffix)}{" "}
- {t(($) => $.slack.not_enabled_self_host_hint)}
- </p>
- </CardContent>
- </Card>
- ) : !installSupported && installations.length === 0 ? (
- <Card>
- <CardContent className="space-y-2">
- <p className="text-body font-medium">{t(($) => $.slack.preview_title)}</p>
- <p className="text-caption text-muted-foreground">
- {t(($) => $.slack.preview_description)}
- </p>
- </CardContent>
- </Card>
- ) : (
- <section className="space-y-3">
- <h2 className="text-body font-semibold">{t(($) => $.slack.connected_bots)}</h2>
- {isLoading ? (
- <Card>
- <CardContent>
- <p className="text-body text-muted-foreground">{t(($) => $.slack.loading)}</p>
- </CardContent>
- </Card>
- ) : installations.length === 0 ? (
- <Card>
- <CardContent className="space-y-2">
- <p className="text-body font-medium">{t(($) => $.slack.empty_title)}</p>
- <p className="text-caption text-muted-foreground">
- {t(($) => $.slack.empty_description_prefix)}{" "}
- <strong>{t(($) => $.slack.empty_description_cta)}</strong>{" "}
- {t(($) => $.slack.empty_description_suffix)}
- </p>
- </CardContent>
- </Card>
- ) : (
- <Card>
- <CardContent className="divide-y">
- {installations.map((inst) => (
- <InstallationRow
- key={inst.id}
- installation={inst}
- canManage={canManage}
- onDisconnect={() => setDisconnectTarget(inst.id)}
- />
- ))}
- </CardContent>
- </Card>
- )}
- </section>
- )}
-
- <AlertDialog
- open={!!disconnectTarget}
- onOpenChange={(v) => {
- if (!v && !disconnecting) setDisconnectTarget(null);
- }}
- >
- <AlertDialogContent>
- <AlertDialogHeader>
- <AlertDialogTitle>
- {t(($) => $.slack.disconnect_confirm_title)}
- </AlertDialogTitle>
- <AlertDialogDescription>
- {t(($) => $.slack.disconnect_confirm_description)}
- </AlertDialogDescription>
- </AlertDialogHeader>
- <AlertDialogFooter>
- <AlertDialogCancel disabled={disconnecting}>
- {t(($) => $.slack.disconnect_confirm_cancel)}
- </AlertDialogCancel>
- <AlertDialogAction onClick={handleDisconnect} disabled={disconnecting}>
- {disconnecting
- ? t(($) => $.slack.disconnecting)
- : t(($) => $.slack.disconnect)}
- </AlertDialogAction>
- </AlertDialogFooter>
- </AlertDialogContent>
- </AlertDialog>
- </div>
- );
-}
-
-function InstallationRow({
- installation,
- canManage,
- onDisconnect,
-}: {
- installation: SlackInstallation;
- canManage: boolean;
- onDisconnect: () => void;
-}) {
- const { t } = useT("settings");
- const locale = useLocale();
- const { getAgentName } = useActorName();
- const isActive = installation.status === "active";
- const agentName = getAgentName(installation.agent_id);
- return (
- <div className="flex items-start justify-between gap-4 py-3 first:pt-0 last:pb-0">
- <div className="flex items-start gap-3">
- <ActorAvatar
- actorType="agent"
- actorId={installation.agent_id}
- size="lg"
- enableHoverCard
- profileLink
- />
- <div className="space-y-1">
- <p className="text-body font-medium">
- {agentName}
- {!isActive && (
- <span className="ml-2 rounded-xs bg-muted px-1.5 py-0.5 text-micro text-muted-foreground">
- {t(($) => $.slack.revoked_badge)}
- </span>
- )}
- </p>
- <p className="text-micro text-muted-foreground">
- {t(($) => $.slack.installed_at_label, {
- when: new Date(installation.installed_at).toLocaleString(locale),
- })}
- </p>
- </div>
- </div>
- {canManage && isActive && (
- <Button variant="outline" size="sm" onClick={onDisconnect}>
- <Trash2 className="h-3 w-3" />
- {t(($) => $.slack.disconnect)}
- </Button>
- )}
- </div>
- );
-}
-
-// SLACK_BYO_VIDEO_URL is the optional setup-tutorial video linked from the
-// connect dialog. Leave "" to hide the link; set it once the walkthrough that
-// shows how to create the Slack app + copy its two tokens is recorded.
-const SLACK_BYO_VIDEO_URL = "";
-
-// slackDocsUrl points at the Slack integration guide on the docs site,
-// localized to the viewer's language. The docs site uses /<lang>/ path
-// prefixes (English has none), matching the convention used elsewhere in the
-// app for doc links (e.g. the autopilots webhook docs link).
-function slackDocsUrl(lang: string | undefined): string {
- return `https://multica.ai/docs${docsLocalePrefix(lang)}/slack-bot-integration`;
-}
-
-// SlackAgentBindButton is the per-agent CTA exposed from the agent detail page.
-// Slack uses the bring-your-own-app model: the button opens a dialog where the
-// admin pastes the bot token (xoxb-) + app-level token (xapp-) of the Slack app
-// they created (the backend validates both belong to the same app). Visibility:
-// 1. Non-owner/admin viewers see nothing (the backend gates install/revoke).
-// 2. If this agent already has an active installation, show the connected
-// badge (already-installed bots stay manageable).
-// 3. Otherwise the Connect CTA shows whenever install is available.
-export function SlackAgentBindButton({
- agentId,
- agentName,
- className,
- onShowConnectedDetails,
-}: {
- agentId: string;
- agentName?: string;
- className?: string;
- /**
- * When set, the connected state renders as a compact read-only status row
- * that invokes this callback on click instead of the full badge with inline
- * actions — the agent inspector passes a "jump to the Integrations tab"
- * handler so management actions live in one place.
- */
- onShowConnectedDetails?: () => void;
-}) {
- const { t, i18n } = useT("settings");
- const wsId = useWorkspaceId();
- const qc = useQueryClient();
- const user = useAuthStore((s) => s.user);
-
- const [dialogOpen, setDialogOpen] = useState(false);
- const [botToken, setBotToken] = useState("");
- const [appToken, setAppToken] = useState("");
- const [submitting, setSubmitting] = useState(false);
-
- const { data: listing } = useQuery({
- ...slackInstallationsOptions(wsId),
- enabled: !!wsId,
- });
- const installSupported = listing?.install_supported === true;
-
- const { data: members = [] } = useQuery({
- ...memberListOptions(wsId),
- enabled: !!wsId,
- });
- const currentMember = members.find((m) => m.user_id === user?.id) ?? null;
- const canManage =
- currentMember?.role === "owner" || currentMember?.role === "admin";
-
- if (!canManage) return null;
-
- const existing = listing?.installations.find(
- (inst) => inst.agent_id === agentId && inst.status === "active",
- );
- if (existing) {
- return onShowConnectedDetails ? (
- <SlackAgentBotStatusRow
- onClick={onShowConnectedDetails}
- className={className}
- />
- ) : (
- <SlackAgentBotConnectedBadge installation={existing} className={className} />
- );
- }
-
- if (!installSupported) return null;
-
- function closeDialog() {
- if (submitting) return;
- setDialogOpen(false);
- setBotToken("");
- setAppToken("");
- }
-
- async function handleSubmit() {
- const bot_token = botToken.trim();
- const app_token = appToken.trim();
- if (submitting || !agentId || !bot_token || !app_token) return;
- setSubmitting(true);
- try {
- await api.registerSlackBYO(wsId, agentId, { bot_token, app_token });
- // The slack_installation realtime event also refreshes this list, but
- // invalidate explicitly so the connected badge appears immediately.
- await qc.invalidateQueries({ queryKey: slackKeys.installations(wsId) });
- toast.success(t(($) => $.slack.byo_success_toast));
- setDialogOpen(false);
- setBotToken("");
- setAppToken("");
- } catch (e) {
- toast.error(
- e instanceof Error ? e.message : t(($) => $.slack.byo_failed_toast),
- );
- } finally {
- setSubmitting(false);
- }
- }
-
- const canSubmit =
- botToken.trim() !== "" && appToken.trim() !== "" && !submitting;
-
- return (
- <div
- className={cn("flex flex-wrap items-center gap-2", className)}
- data-testid="slack-agent-bind-buttons"
- >
- <TooltipHint
- label={
- agentName
- ? t(($) => $.slack.bind_button_title, { agent: agentName })
- : undefined
- }
- >
- <Button
- variant="outline"
- size="sm"
- onClick={() => setDialogOpen(true)}
- disabled={!agentId}
- data-testid="slack-agent-connect"
- >
- <SlackMark className="h-3 w-3" />
- {t(($) => $.slack.bind_button)}
- </Button>
- </TooltipHint>
-
- <Dialog
- open={dialogOpen}
- onOpenChange={(v) => (v ? setDialogOpen(true) : closeDialog())}
- >
- <DialogContent className="sm:max-w-lg" data-testid="slack-byo-dialog">
- <DialogHeader>
- <DialogTitle>{t(($) => $.slack.byo_dialog_title)}</DialogTitle>
- </DialogHeader>
-
- {SLACK_BYO_VIDEO_URL ? (
- <button
- type="button"
- onClick={() => openExternal(SLACK_BYO_VIDEO_URL)}
- className="inline-flex w-fit items-center gap-2 text-body font-medium text-primary underline-offset-2 hover:underline"
- >
- <ExternalLink className="h-4 w-4" />
- {t(($) => $.slack.byo_video_cta)}
- </button>
- ) : null}
-
- <button
- type="button"
- onClick={() => openExternal(slackDocsUrl(i18n.language))}
- className="inline-flex w-fit items-center gap-2 text-body font-medium text-primary underline-offset-2 hover:underline"
- data-testid="slack-byo-docs-link"
- >
- <ExternalLink className="h-4 w-4" />
- {t(($) => $.slack.byo_docs_link)}
- </button>
-
- <div className="space-y-4">
- <div className="space-y-1.5">
- <Label htmlFor="slack-byo-bot-token">
- {t(($) => $.slack.byo_bot_token_label)}
- </Label>
- <Input
- id="slack-byo-bot-token"
- data-testid="slack-byo-bot-token"
- value={botToken}
- onChange={(e) => setBotToken(e.target.value)}
- // Slack token prefix: a format hint, not copy.
- // eslint-disable-next-line no-restricted-syntax
- placeholder="xoxb-…"
- autoComplete="off"
- spellCheck={false}
- disabled={submitting}
- />
- </div>
-
- <div className="space-y-1.5">
- <Label htmlFor="slack-byo-app-token">
- {t(($) => $.slack.byo_app_token_label)}
- </Label>
- <Input
- id="slack-byo-app-token"
- data-testid="slack-byo-app-token"
- value={appToken}
- onChange={(e) => setAppToken(e.target.value)}
- // Slack token prefix: a format hint, not copy.
- // eslint-disable-next-line no-restricted-syntax
- placeholder="xapp-…"
- autoComplete="off"
- spellCheck={false}
- disabled={submitting}
- />
- </div>
- </div>
-
- <DialogFooter>
- <Button
- variant="outline"
- size="sm"
- onClick={closeDialog}
- disabled={submitting}
- >
- {t(($) => $.slack.byo_cancel)}
- </Button>
- <Button
- size="sm"
- onClick={handleSubmit}
- disabled={!canSubmit}
- data-testid="slack-byo-submit"
- >
- {submitting
- ? t(($) => $.slack.byo_submitting)
- : t(($) => $.slack.byo_submit)}
- </Button>
- </DialogFooter>
- </DialogContent>
- </Dialog>
- </div>
- );
-}
-
-// SlackAgentBotStatusRow is the compact, read-only connected affordance the
-// agent inspector renders instead of the full badge; it deep-links into the
-// Integrations tab where Manage / Disconnect live.
-function SlackAgentBotStatusRow({
- onClick,
- className,
-}: {
- onClick: () => void;
- className?: string;
-}) {
- const { t } = useT("settings");
- return (
- <button
- type="button"
- onClick={onClick}
- className={cn(
- "flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-caption text-muted-foreground transition-colors hover:bg-muted focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/50",
- className,
- )}
- data-testid="slack-agent-bot-status"
- >
- <span className="inline-block h-1.5 w-1.5 shrink-0 rounded-full bg-emerald-500" />
- <span className="truncate">{t(($) => $.slack.agent_bot_connected_label)}</span>
- <ChevronRight className="ml-auto h-3.5 w-3.5 shrink-0" />
- </button>
- );
-}
-
-// SlackAgentBotConnectedBadge is the full "already connected" affordance the
-// Integrations tab renders in place of the Connect button. Two rows: status +
-// soft-destructive Disconnect, then a secondary "Open in Slack" link to the
-// installed workspace. Only owners/admins ever reach this component.
-function SlackAgentBotConnectedBadge({
- installation,
- className,
-}: {
- installation: SlackInstallation;
- className?: string;
-}) {
- const { t } = useT("settings");
- const wsId = useWorkspaceId();
- const qc = useQueryClient();
-
- const [confirmOpen, setConfirmOpen] = useState(false);
- const [disconnecting, setDisconnecting] = useState(false);
-
- async function handleDisconnect() {
- if (disconnecting) return;
- setDisconnecting(true);
- try {
- await api.deleteSlackInstallation(wsId, installation.id);
- await qc.invalidateQueries({ queryKey: slackKeys.installations(wsId) });
- toast.success(t(($) => $.slack.toast_disconnected));
- setConfirmOpen(false);
- } catch (e) {
- toast.error(
- e instanceof Error ? e.message : t(($) => $.slack.toast_disconnect_failed),
- );
- } finally {
- setDisconnecting(false);
- }
- }
-
- return (
- <div
- className={cn("space-y-2", className)}
- data-testid="slack-agent-bot-connected"
- >
- <div className="flex items-center justify-between gap-3">
- <span className="inline-flex min-w-0 items-center gap-2 text-caption text-muted-foreground">
- <span className="inline-block h-1.5 w-1.5 shrink-0 rounded-full bg-emerald-500" />
- <span className="truncate">{t(($) => $.slack.agent_bot_connected_label)}</span>
- </span>
- <TooltipHint label={t(($) => $.slack.agent_bot_disconnect_tooltip)}>
- <Button
- variant="destructive"
- size="sm"
- onClick={() => setConfirmOpen(true)}
- disabled={disconnecting}
- aria-label={t(($) => $.slack.disconnect)}
- data-testid="slack-agent-bot-disconnect"
- >
- <Trash2 className="h-3 w-3" />
- {disconnecting
- ? t(($) => $.slack.disconnecting)
- : t(($) => $.slack.disconnect)}
- </Button>
- </TooltipHint>
- </div>
-
- {installation.team_id && (
- <TooltipHint label={t(($) => $.slack.agent_bot_manage_tooltip)}>
- <button
- type="button"
- onClick={() =>
- openExternal(`https://app.slack.com/client/${installation.team_id}`)
- }
- className="inline-flex items-center gap-1 text-caption text-muted-foreground underline-offset-2 transition-colors hover:text-foreground hover:underline"
- >
- <ExternalLink className="h-3 w-3" />
- {t(($) => $.slack.agent_bot_manage_link)}
- </button>
- </TooltipHint>
- )}
-
- <AlertDialog
- open={confirmOpen}
- onOpenChange={(v) => {
- if (!v && !disconnecting) setConfirmOpen(false);
- }}
- >
- <AlertDialogContent>
- <AlertDialogHeader>
- <AlertDialogTitle>
- {t(($) => $.slack.disconnect_confirm_title)}
- </AlertDialogTitle>
- <AlertDialogDescription>
- {t(($) => $.slack.disconnect_confirm_description)}
- </AlertDialogDescription>
- </AlertDialogHeader>
- <AlertDialogFooter>
- <AlertDialogCancel disabled={disconnecting}>
- {t(($) => $.slack.disconnect_confirm_cancel)}
- </AlertDialogCancel>
- <AlertDialogAction onClick={handleDisconnect} disabled={disconnecting}>
- {disconnecting
- ? t(($) => $.slack.disconnecting)
- : t(($) => $.slack.disconnect)}
- </AlertDialogAction>
- </AlertDialogFooter>
- </AlertDialogContent>
- </AlertDialog>
- </div>
- );
-}
diff --git a/packages/views/settings/components/telegram-tab.test.tsx b/packages/views/settings/components/telegram-tab.test.tsx
deleted file mode 100644
index 9d1c394369..0000000000
--- a/packages/views/settings/components/telegram-tab.test.tsx
+++ /dev/null
@@ -1,331 +0,0 @@
-// @vitest-environment jsdom
-
-import { type ReactNode } from "react";
-import { describe, it, expect, beforeEach, vi } from "vitest";
-import { render, screen, waitFor } from "@testing-library/react";
-import userEvent from "@testing-library/user-event";
-import { I18nProvider } from "@multica/core/i18n/react";
-import enCommon from "../../locales/en/common.json";
-import enSettings from "../../locales/en/settings.json";
-
-type MemberRole = "owner" | "admin" | "member" | "guest";
-
-const membersRef = vi.hoisted(() => ({
- current: [{ user_id: "user-1", role: "owner" as MemberRole }],
-}));
-const installationsRef = vi.hoisted(() => ({
- current: {
- installations: [] as unknown[],
- configured: true,
- install_supported: true,
- },
-}));
-const mockRegister = vi.hoisted(() => vi.fn());
-const mockDeleteInstallation = vi.hoisted(() => vi.fn());
-const mockOpenExternal = vi.hoisted(() => vi.fn());
-const mockInvalidate = vi.hoisted(() => vi.fn());
-const mockToastError = vi.hoisted(() => vi.fn());
-const telegramQueryErrorRef = vi.hoisted(() => ({ current: false }));
-const telegramQueryLoadingRef = vi.hoisted(() => ({ current: false }));
-
-vi.mock("@tanstack/react-query", () => ({
- useQuery: (opts: { queryKey: unknown[]; enabled?: boolean }) => {
- if (opts.enabled === false) return { data: undefined, isLoading: false };
- const key = JSON.stringify(opts.queryKey);
- if (key.includes("members")) return { data: membersRef.current, isLoading: false };
- if (key.includes("installations")) {
- return {
- data: telegramQueryLoadingRef.current ? undefined : installationsRef.current,
- isLoading: telegramQueryLoadingRef.current,
- isError: telegramQueryErrorRef.current,
- };
- }
- return { data: undefined, isLoading: false };
- },
- useQueryClient: () => ({ invalidateQueries: mockInvalidate }),
- queryOptions: <T,>(opts: T) => opts,
-}));
-
-vi.mock("@multica/core/hooks", () => ({ useWorkspaceId: () => "workspace-1" }));
-
-vi.mock("@multica/core/workspace/queries", () => ({
- memberListOptions: () => ({ queryKey: ["members"], queryFn: vi.fn() }),
-}));
-
-vi.mock("@multica/core/workspace/hooks", () => ({
- useActorName: () => ({
- getAgentName: (agentId: string) => `Agent ${agentId}`,
- getMemberName: () => "Unknown",
- getSquadName: () => "Unknown Squad",
- getActorName: () => "Unknown",
- getActorInitials: () => "??",
- getActorAvatarUrl: () => null,
- }),
-}));
-
-vi.mock("../../common/actor-avatar", () => ({
- ActorAvatar: ({ actorId }: { actorId: string }) => (
- <span data-testid="actor-avatar" data-actor-id={actorId} />
- ),
-}));
-
-vi.mock("@multica/core/telegram", () => ({
- telegramInstallationsOptions: () => ({
- queryKey: ["telegram", "installations"],
- queryFn: vi.fn(),
- }),
- telegramKeys: { installations: (wsId: string) => ["telegram", "installations", wsId] },
-}));
-
-vi.mock("@multica/core/api", () => ({
- api: {
- registerTelegramBot: mockRegister,
- deleteTelegramInstallation: mockDeleteInstallation,
- },
-}));
-
-vi.mock("@multica/core/auth", () => {
- const useAuthStore = Object.assign(
- (sel?: (s: { user: { id: string } }) => unknown) =>
- sel ? sel({ user: { id: "user-1" } }) : { user: { id: "user-1" } },
- { getState: () => ({ user: { id: "user-1" } }) },
- );
- return { useAuthStore };
-});
-
-vi.mock("sonner", () => ({
- toast: { success: vi.fn(), error: mockToastError, message: vi.fn() },
-}));
-
-vi.mock("../../platform", () => ({ openExternal: mockOpenExternal }));
-
-import { TelegramAgentBindButton, TelegramTab } from "./telegram-tab";
-
-const TEST_RESOURCES = { en: { common: enCommon, settings: enSettings } };
-
-function renderUI(children: ReactNode) {
- return render(
- <I18nProvider locale="en" resources={TEST_RESOURCES}>
- {children}
- </I18nProvider>,
- );
-}
-
-function resetFixtures() {
- vi.clearAllMocks();
- membersRef.current = [{ user_id: "user-1", role: "owner" }];
- installationsRef.current = { installations: [], configured: true, install_supported: true };
- telegramQueryErrorRef.current = false;
- telegramQueryLoadingRef.current = false;
-}
-
-describe("TelegramAgentBindButton", () => {
- beforeEach(resetFixtures);
-
- it("opens the connect dialog and submits the pasted bot token", async () => {
- mockRegister.mockResolvedValue({ id: "i1", agent_id: "agent-1", status: "active" });
- renderUI(<TelegramAgentBindButton agentId="agent-1" agentName="Bot" />);
- await userEvent.click(screen.getByTestId("telegram-agent-connect"));
- const tokenInput = await screen.findByTestId("telegram-bot-token");
- expect(tokenInput).toHaveAttribute("type", "password");
- await userEvent.type(tokenInput, "123456789:AAtesttoken");
- await userEvent.click(screen.getByTestId("telegram-connect-submit"));
- await waitFor(() =>
- expect(mockRegister).toHaveBeenCalledWith("workspace-1", "agent-1", {
- bot_token: "123456789:AAtesttoken",
- }),
- );
- expect(mockOpenExternal).not.toHaveBeenCalled();
- });
-
- it("opens the localized Telegram setup guide", async () => {
- renderUI(<TelegramAgentBindButton agentId="agent-1" agentName="Bot" />);
- await userEvent.click(screen.getByTestId("telegram-agent-connect"));
- await userEvent.click(await screen.findByTestId("telegram-docs-link"));
- expect(mockOpenExternal).toHaveBeenCalledWith(
- "https://multica.ai/docs/telegram-bot-integration",
- );
- });
-
- it("does not report success for a malformed install response", async () => {
- mockRegister.mockResolvedValue({});
- renderUI(<TelegramAgentBindButton agentId="agent-1" agentName="Bot" />);
- await userEvent.click(screen.getByTestId("telegram-agent-connect"));
- await userEvent.type(await screen.findByTestId("telegram-bot-token"), "123456789:AAtesttoken");
- await userEvent.click(screen.getByTestId("telegram-connect-submit"));
- await waitFor(() => expect(mockToastError).toHaveBeenCalled());
- expect(mockInvalidate).not.toHaveBeenCalled();
- });
-
- it("shows the connected badge (not the CTA) when the agent already has an active install", () => {
- installationsRef.current = {
- installations: [
- { id: "i1", agent_id: "agent-1", status: "active", bot_username: "my_bot" },
- ],
- configured: true,
- install_supported: true,
- };
- renderUI(<TelegramAgentBindButton agentId="agent-1" />);
- expect(screen.getByTestId("telegram-agent-bot-connected")).toBeTruthy();
- expect(screen.getByTestId("telegram-agent-bot-disconnect")).toBeTruthy();
- expect(screen.queryByTestId("telegram-agent-connect")).toBeNull();
- });
-
- it("opens the connected bot in Telegram", async () => {
- installationsRef.current = {
- installations: [
- { id: "i1", agent_id: "agent-1", status: "active", bot_username: "my_bot" },
- ],
- configured: true,
- install_supported: true,
- };
- renderUI(<TelegramAgentBindButton agentId="agent-1" />);
-
- await userEvent.click(screen.getByRole("button", { name: /Open in Telegram/i }));
-
- expect(mockOpenExternal).toHaveBeenCalledWith("https://t.me/my_bot");
- });
-
- it("disconnects an agent bot only after confirmation", async () => {
- mockDeleteInstallation.mockResolvedValue(undefined);
- installationsRef.current = {
- installations: [
- { id: "i1", agent_id: "agent-1", status: "active", bot_username: "my_bot" },
- ],
- configured: true,
- install_supported: true,
- };
- renderUI(<TelegramAgentBindButton agentId="agent-1" />);
-
- await userEvent.click(screen.getByTestId("telegram-agent-bot-disconnect"));
- expect(mockDeleteInstallation).not.toHaveBeenCalled();
- const actions = await screen.findAllByRole("button", { name: /^Disconnect$/i });
- await userEvent.click(actions.at(-1)!);
-
- await waitFor(() =>
- expect(mockDeleteInstallation).toHaveBeenCalledWith("workspace-1", "i1"),
- );
- expect(mockInvalidate).toHaveBeenCalled();
- });
-
- it("keeps an agent bot connected when disconnect fails", async () => {
- mockDeleteInstallation.mockRejectedValue(new Error("network failed"));
- installationsRef.current = {
- installations: [
- { id: "i1", agent_id: "agent-1", status: "active", bot_username: "my_bot" },
- ],
- configured: true,
- install_supported: true,
- };
- renderUI(<TelegramAgentBindButton agentId="agent-1" />);
-
- await userEvent.click(screen.getByTestId("telegram-agent-bot-disconnect"));
- const actions = await screen.findAllByRole("button", { name: /^Disconnect$/i });
- await userEvent.click(actions.at(-1)!);
-
- await waitFor(() => expect(mockToastError).toHaveBeenCalledWith("network failed"));
- expect(screen.getByTestId("telegram-agent-bot-connected")).toBeTruthy();
- expect(mockInvalidate).not.toHaveBeenCalled();
- });
-
- it("renders nothing for a non-manager", () => {
- membersRef.current = [{ user_id: "user-1", role: "member" }];
- const { container } = renderUI(<TelegramAgentBindButton agentId="agent-1" />);
- expect(container).toBeEmptyDOMElement();
- });
-
- it("renders nothing when install is unavailable and the agent is unbound", () => {
- installationsRef.current = { installations: [], configured: true, install_supported: false };
- const { container } = renderUI(<TelegramAgentBindButton agentId="agent-1" />);
- expect(container).toBeEmptyDOMElement();
- });
-});
-
-describe("TelegramTab", () => {
- beforeEach(resetFixtures);
-
- it("shows a loading state without claiming Telegram is disabled", () => {
- telegramQueryLoadingRef.current = true;
- renderUI(<TelegramTab />);
- expect(screen.getByText("Loading…")).toBeTruthy();
- expect(screen.queryByText(/Telegram integration not enabled/i)).toBeNull();
- });
-
- it("surfaces the not-enabled notice when the deployment has no Telegram key", () => {
- installationsRef.current = { installations: [], configured: false, install_supported: false };
- renderUI(<TelegramTab />);
- expect(screen.getByText(/Telegram integration not enabled/i)).toBeTruthy();
- });
-
- it("shows the empty state when configured but nothing is connected", () => {
- renderUI(<TelegramTab />);
- expect(screen.getByText(/No bots connected yet/i)).toBeTruthy();
- });
-
- it("lists a connected installation with its agent name and a disconnect control", () => {
- installationsRef.current = {
- installations: [
- { id: "i1", agent_id: "agent-7", status: "active", bot_username: "my_bot" },
- ],
- configured: true,
- install_supported: true,
- };
- renderUI(<TelegramTab />);
- expect(screen.getByText("Agent agent-7")).toBeTruthy();
- expect(screen.getByText("@my_bot")).toBeTruthy();
- expect(screen.getByText(/Disconnect/i)).toBeTruthy();
- });
-
- it("disconnects only after confirmation and refreshes the installation list", async () => {
- mockDeleteInstallation.mockResolvedValue(undefined);
- installationsRef.current = {
- installations: [
- { id: "i1", agent_id: "agent-7", status: "active", bot_username: "my_bot" },
- ],
- configured: true,
- install_supported: true,
- };
- renderUI(<TelegramTab />);
- await userEvent.click(screen.getByRole("button", { name: /Disconnect/i }));
- expect(mockDeleteInstallation).not.toHaveBeenCalled();
- const actions = await screen.findAllByRole("button", { name: /^Disconnect$/i });
- await userEvent.click(actions.at(-1)!);
- await waitFor(() =>
- expect(mockDeleteInstallation).toHaveBeenCalledWith("workspace-1", "i1"),
- );
- expect(mockInvalidate).toHaveBeenCalled();
- });
-
- it("keeps the installation visible when disconnect fails", async () => {
- mockDeleteInstallation.mockRejectedValue(new Error("network failed"));
- installationsRef.current = {
- installations: [
- { id: "i1", agent_id: "agent-7", status: "active", bot_username: "my_bot" },
- ],
- configured: true,
- install_supported: true,
- };
- renderUI(<TelegramTab />);
- await userEvent.click(screen.getByRole("button", { name: /Disconnect/i }));
- const actions = await screen.findAllByRole("button", { name: /^Disconnect$/i });
- await userEvent.click(actions.at(-1)!);
- await waitFor(() => expect(mockToastError).toHaveBeenCalledWith("network failed"));
- expect(screen.getByText("@my_bot")).toBeTruthy();
- expect(mockInvalidate).not.toHaveBeenCalled();
- });
-
- // Malformed-response defense (CLAUDE.md → API Compatibility): a response
- // missing `installations` must not crash the panel.
- it("tolerates a malformed installations response", () => {
- installationsRef.current = { configured: true } as never;
- renderUI(<TelegramTab />);
- expect(screen.getByText(/No bots connected yet/i)).toBeTruthy();
- });
-
- it("shows a load error instead of pretending Telegram is disabled", () => {
- telegramQueryErrorRef.current = true;
- renderUI(<TelegramTab />);
- expect(screen.getByText(/Failed to load Telegram installations/i)).toBeTruthy();
- expect(screen.queryByText(/Telegram integration not enabled/i)).toBeNull();
- });
-});
diff --git a/packages/views/settings/components/telegram-tab.tsx b/packages/views/settings/components/telegram-tab.tsx
deleted file mode 100644
index b401cdab89..0000000000
--- a/packages/views/settings/components/telegram-tab.tsx
+++ /dev/null
@@ -1,557 +0,0 @@
-"use client";
-
-import { useState } from "react";
-import { useQuery, useQueryClient } from "@tanstack/react-query";
-import { toast } from "sonner";
-import { ChevronRight, ExternalLink, Trash2 } from "@multica/ui/icons";
-import { TelegramMark } from "./telegram-mark";
-import { cn } from "@multica/ui/lib/utils";
-import { Button } from "@multica/ui/components/ui/button";
-import { Card, CardContent } from "@multica/ui/components/ui/card";
-import {
- Dialog,
- DialogContent,
- DialogFooter,
- DialogHeader,
- DialogTitle,
-} from "@multica/ui/components/ui/dialog";
-import { Input } from "@multica/ui/components/ui/input";
-import { Label } from "@multica/ui/components/ui/label";
-import {
- AlertDialog,
- AlertDialogAction,
- AlertDialogCancel,
- AlertDialogContent,
- AlertDialogDescription,
- AlertDialogFooter,
- AlertDialogHeader,
- AlertDialogTitle,
-} from "@multica/ui/components/ui/alert-dialog";
-import { useAuthStore } from "@multica/core/auth";
-import { useWorkspaceId } from "@multica/core/hooks";
-import { memberListOptions } from "@multica/core/workspace/queries";
-import { useActorName } from "@multica/core/workspace/hooks";
-import { telegramInstallationsOptions, telegramKeys } from "@multica/core/telegram";
-import { api } from "@multica/core/api";
-import type { TelegramInstallation } from "@multica/core/types";
-import { ActorAvatar } from "../../common/actor-avatar";
-import { docsLocalePrefix } from "../../common/docs-locale";
-import { openExternal } from "../../platform";
-import { useLocale, useT } from "../../i18n";
-import { TooltipHint } from "@multica/ui/components/common/tooltip-hint";
-
-// TelegramTab is the workspace settings panel for Telegram bot installations,
-// mirroring SlackTab: listing is member-visible; the disconnect action is
-// admin-only (backend-enforced; the UI hides the button to match). Adding a
-// new installation flows through the Agent detail page — the install path is
-// per-agent (one bot per agent, the (workspace_id, agent_id, channel_type)
-// UNIQUE in channel_installation).
-export function TelegramTab() {
- const { t } = useT("settings");
- const wsId = useWorkspaceId();
- const qc = useQueryClient();
- const user = useAuthStore((s) => s.user);
-
- const { data: members = [] } = useQuery(memberListOptions(wsId));
- const currentMember = members.find((m) => m.user_id === user?.id) ?? null;
- const canManage =
- currentMember?.role === "owner" || currentMember?.role === "admin";
-
- const { data, isLoading, isError } = useQuery({
- ...telegramInstallationsOptions(wsId),
- enabled: !!wsId,
- });
- const installations = data?.installations ?? [];
- const configured = data?.configured === true;
-
- const [disconnectTarget, setDisconnectTarget] = useState<string | null>(null);
- const [disconnecting, setDisconnecting] = useState(false);
-
- async function handleDisconnect() {
- if (!disconnectTarget || disconnecting) return;
- setDisconnecting(true);
- try {
- // Await the server before touching cache/UI (repo rule: no optimistic
- // removal on flows that confirm/destroy).
- await api.deleteTelegramInstallation(wsId, disconnectTarget);
- await qc.invalidateQueries({ queryKey: telegramKeys.installations(wsId) });
- toast.success(t(($) => $.telegram.toast_disconnected));
- setDisconnectTarget(null);
- } catch (e) {
- toast.error(
- e instanceof Error ? e.message : t(($) => $.telegram.toast_disconnect_failed),
- );
- } finally {
- setDisconnecting(false);
- }
- }
-
- return (
- <div className="space-y-8">
- {isError ? (
- <Card>
- <CardContent>
- <p className="text-body text-muted-foreground">
- {t(($) => $.telegram.load_failed)}
- </p>
- </CardContent>
- </Card>
- ) : isLoading ? (
- <Card>
- <CardContent>
- <p className="text-body text-muted-foreground">{t(($) => $.telegram.loading)}</p>
- </CardContent>
- </Card>
- ) : !configured ? (
- <Card>
- <CardContent className="space-y-2">
- <p className="text-body font-medium">{t(($) => $.telegram.not_enabled_title)}</p>
- <p className="text-caption text-muted-foreground">
- {t(($) => $.telegram.not_enabled_description_prefix)}{" "}
- <code className="rounded-xs bg-muted px-1 py-0.5 text-micro">
- MULTICA_TELEGRAM_SECRET_KEY
- </code>{" "}
- {t(($) => $.telegram.not_enabled_description_suffix)}{" "}
- {t(($) => $.telegram.not_enabled_self_host_hint)}
- </p>
- </CardContent>
- </Card>
- ) : (
- <section className="space-y-3">
- <h2 className="text-body font-semibold">{t(($) => $.telegram.connected_bots)}</h2>
- {installations.length === 0 ? (
- <Card>
- <CardContent className="space-y-2">
- <p className="text-body font-medium">{t(($) => $.telegram.empty_title)}</p>
- <p className="text-caption text-muted-foreground">
- {t(($) => $.telegram.empty_description_prefix)}{" "}
- <strong>{t(($) => $.telegram.empty_description_cta)}</strong>{" "}
- {t(($) => $.telegram.empty_description_suffix)}
- </p>
- </CardContent>
- </Card>
- ) : (
- <Card>
- <CardContent className="divide-y">
- {installations.map((inst) => (
- <InstallationRow
- key={inst.id}
- installation={inst}
- canManage={canManage}
- onDisconnect={() => setDisconnectTarget(inst.id)}
- />
- ))}
- </CardContent>
- </Card>
- )}
- </section>
- )}
-
- <AlertDialog
- open={!!disconnectTarget}
- onOpenChange={(v) => {
- if (!v && !disconnecting) setDisconnectTarget(null);
- }}
- >
- <AlertDialogContent>
- <AlertDialogHeader>
- <AlertDialogTitle>
- {t(($) => $.telegram.disconnect_confirm_title)}
- </AlertDialogTitle>
- <AlertDialogDescription>
- {t(($) => $.telegram.disconnect_confirm_description)}
- </AlertDialogDescription>
- </AlertDialogHeader>
- <AlertDialogFooter>
- <AlertDialogCancel disabled={disconnecting}>
- {t(($) => $.telegram.disconnect_confirm_cancel)}
- </AlertDialogCancel>
- <AlertDialogAction onClick={handleDisconnect} disabled={disconnecting}>
- {disconnecting
- ? t(($) => $.telegram.disconnecting)
- : t(($) => $.telegram.disconnect)}
- </AlertDialogAction>
- </AlertDialogFooter>
- </AlertDialogContent>
- </AlertDialog>
- </div>
- );
-}
-
-function InstallationRow({
- installation,
- canManage,
- onDisconnect,
-}: {
- installation: TelegramInstallation;
- canManage: boolean;
- onDisconnect: () => void;
-}) {
- const { t } = useT("settings");
- const locale = useLocale();
- const { getAgentName } = useActorName();
- const isActive = installation.status === "active";
- const agentName = getAgentName(installation.agent_id);
- return (
- <div className="flex items-start justify-between gap-4 py-3 first:pt-0 last:pb-0">
- <div className="flex items-start gap-3">
- <ActorAvatar
- actorType="agent"
- actorId={installation.agent_id}
- size="lg"
- enableHoverCard
- profileLink
- />
- <div className="space-y-1">
- <p className="text-body font-medium">
- {agentName}
- {installation.bot_username ? (
- <span className="ml-2 text-caption text-muted-foreground">
- @{installation.bot_username}
- </span>
- ) : null}
- {!isActive && (
- <span className="ml-2 rounded-xs bg-muted px-1.5 py-0.5 text-micro text-muted-foreground">
- {t(($) => $.telegram.revoked_badge)}
- </span>
- )}
- </p>
- <p className="text-micro text-muted-foreground">
- {t(($) => $.telegram.installed_at_label, {
- when: new Date(installation.installed_at).toLocaleString(locale),
- })}
- </p>
- </div>
- </div>
- {canManage && isActive && (
- <Button variant="outline" size="sm" onClick={onDisconnect}>
- <Trash2 className="h-3 w-3" />
- {t(($) => $.telegram.disconnect)}
- </Button>
- )}
- </div>
- );
-}
-
-// telegramDocsUrl points at the Telegram integration guide on the docs site,
-// localized like the Slack docs link.
-function telegramDocsUrl(lang: string | undefined): string {
- return `https://multica.ai/docs${docsLocalePrefix(lang)}/telegram-bot-integration`;
-}
-
-// TelegramAgentBindButton is the per-agent CTA on the agent detail page.
-// Telegram uses the paste-a-token model: the admin creates a bot with
-// @BotFather and pastes its token; the backend validates via getMe before
-// persisting. Visibility mirrors SlackAgentBindButton (owner/admin only).
-export function TelegramAgentBindButton({
- agentId,
- agentName,
- className,
- onShowConnectedDetails,
-}: {
- agentId: string;
- agentName?: string;
- className?: string;
- /** Compact read-only connected row that invokes this instead of the full
- * badge — the agent inspector passes a "jump to the Integrations tab"
- * handler so management actions live in one place. */
- onShowConnectedDetails?: () => void;
-}) {
- const { t, i18n } = useT("settings");
- const wsId = useWorkspaceId();
- const qc = useQueryClient();
- const user = useAuthStore((s) => s.user);
-
- const [dialogOpen, setDialogOpen] = useState(false);
- const [botToken, setBotToken] = useState("");
- const [submitting, setSubmitting] = useState(false);
-
- const { data: listing } = useQuery({
- ...telegramInstallationsOptions(wsId),
- enabled: !!wsId,
- });
- const installSupported = listing?.install_supported === true;
-
- const { data: members = [] } = useQuery({
- ...memberListOptions(wsId),
- enabled: !!wsId,
- });
- const currentMember = members.find((m) => m.user_id === user?.id) ?? null;
- const canManage =
- currentMember?.role === "owner" || currentMember?.role === "admin";
-
- if (!canManage) return null;
-
- const existing = listing?.installations.find(
- (inst) => inst.agent_id === agentId && inst.status === "active",
- );
- if (existing) {
- return onShowConnectedDetails ? (
- <TelegramAgentBotStatusRow
- onClick={onShowConnectedDetails}
- className={className}
- />
- ) : (
- <TelegramAgentBotConnectedBadge installation={existing} className={className} />
- );
- }
-
- if (!installSupported) return null;
-
- function closeDialog() {
- if (submitting) return;
- setDialogOpen(false);
- setBotToken("");
- }
-
- async function handleSubmit() {
- const bot_token = botToken.trim();
- if (submitting || !agentId || !bot_token) return;
- setSubmitting(true);
- try {
- const installation = await api.registerTelegramBot(wsId, agentId, { bot_token });
- if (!installation.id || installation.status !== "active") {
- throw new Error("Telegram connection returned an invalid installation");
- }
- // The telegram_installation realtime event also refreshes this list, but
- // invalidate explicitly so the connected badge appears immediately.
- await qc.invalidateQueries({ queryKey: telegramKeys.installations(wsId) });
- toast.success(t(($) => $.telegram.connect_success_toast));
- setDialogOpen(false);
- setBotToken("");
- } catch (e) {
- toast.error(
- e instanceof Error ? e.message : t(($) => $.telegram.connect_failed_toast),
- );
- } finally {
- setSubmitting(false);
- }
- }
-
- const canSubmit = botToken.trim() !== "" && !submitting;
-
- return (
- <div
- className={cn("flex flex-wrap items-center gap-2", className)}
- data-testid="telegram-agent-bind-buttons"
- >
- <TooltipHint
- label={
- agentName
- ? t(($) => $.telegram.bind_button_title, { agent: agentName })
- : undefined
- }
- >
- <Button
- variant="outline"
- size="sm"
- onClick={() => setDialogOpen(true)}
- disabled={!agentId}
- data-testid="telegram-agent-connect"
- >
- <TelegramMark className="h-3 w-3" />
- {t(($) => $.telegram.bind_button)}
- </Button>
- </TooltipHint>
-
- <Dialog
- open={dialogOpen}
- onOpenChange={(v) => (v ? setDialogOpen(true) : closeDialog())}
- >
- <DialogContent className="sm:max-w-lg" data-testid="telegram-connect-dialog">
- <DialogHeader>
- <DialogTitle>{t(($) => $.telegram.connect_dialog_title)}</DialogTitle>
- </DialogHeader>
-
- <p className="text-caption text-muted-foreground">
- {t(($) => $.telegram.connect_dialog_description)}
- </p>
-
- <button
- type="button"
- onClick={() => openExternal(telegramDocsUrl(i18n.language))}
- className="inline-flex w-fit items-center gap-2 text-body font-medium text-primary underline-offset-2 hover:underline"
- data-testid="telegram-docs-link"
- >
- <ExternalLink className="h-4 w-4" />
- {t(($) => $.telegram.connect_docs_link)}
- </button>
-
- <div className="space-y-1.5">
- <Label htmlFor="telegram-bot-token">
- {t(($) => $.telegram.bot_token_label)}
- </Label>
- <Input
- id="telegram-bot-token"
- data-testid="telegram-bot-token"
- type="password"
- value={botToken}
- onChange={(e) => setBotToken(e.target.value)}
- // Telegram token shape: a format hint, not copy.
- // eslint-disable-next-line no-restricted-syntax
- placeholder="123456789:AA…"
- autoComplete="off"
- spellCheck={false}
- disabled={submitting}
- />
- </div>
-
- <DialogFooter>
- <Button
- variant="outline"
- size="sm"
- onClick={closeDialog}
- disabled={submitting}
- >
- {t(($) => $.telegram.connect_cancel)}
- </Button>
- <Button
- size="sm"
- onClick={handleSubmit}
- disabled={!canSubmit}
- data-testid="telegram-connect-submit"
- >
- {submitting
- ? t(($) => $.telegram.connect_submitting)
- : t(($) => $.telegram.connect_submit)}
- </Button>
- </DialogFooter>
- </DialogContent>
- </Dialog>
- </div>
- );
-}
-
-// TelegramAgentBotStatusRow is the compact, read-only connected affordance the
-// agent inspector renders; it deep-links into the Integrations tab.
-function TelegramAgentBotStatusRow({
- onClick,
- className,
-}: {
- onClick: () => void;
- className?: string;
-}) {
- const { t } = useT("settings");
- return (
- <button
- type="button"
- onClick={onClick}
- className={cn(
- "flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-caption text-muted-foreground transition-colors hover:bg-muted focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/50",
- className,
- )}
- data-testid="telegram-agent-bot-status"
- >
- <span className="inline-block h-1.5 w-1.5 shrink-0 rounded-full bg-emerald-500" />
- <span className="truncate">{t(($) => $.telegram.agent_bot_connected_label)}</span>
- <ChevronRight className="ml-auto h-3.5 w-3.5 shrink-0" />
- </button>
- );
-}
-
-// TelegramAgentBotConnectedBadge is the full "already connected" affordance:
-// status + Disconnect, then an "Open in Telegram" deep link to the bot.
-function TelegramAgentBotConnectedBadge({
- installation,
- className,
-}: {
- installation: TelegramInstallation;
- className?: string;
-}) {
- const { t } = useT("settings");
- const wsId = useWorkspaceId();
- const qc = useQueryClient();
-
- const [confirmOpen, setConfirmOpen] = useState(false);
- const [disconnecting, setDisconnecting] = useState(false);
-
- async function handleDisconnect() {
- if (disconnecting) return;
- setDisconnecting(true);
- try {
- await api.deleteTelegramInstallation(wsId, installation.id);
- await qc.invalidateQueries({ queryKey: telegramKeys.installations(wsId) });
- toast.success(t(($) => $.telegram.toast_disconnected));
- setConfirmOpen(false);
- } catch (e) {
- toast.error(
- e instanceof Error ? e.message : t(($) => $.telegram.toast_disconnect_failed),
- );
- } finally {
- setDisconnecting(false);
- }
- }
-
- return (
- <div
- className={cn("space-y-2", className)}
- data-testid="telegram-agent-bot-connected"
- >
- <div className="flex items-center justify-between gap-3">
- <span className="inline-flex min-w-0 items-center gap-2 text-caption text-muted-foreground">
- <span className="inline-block h-1.5 w-1.5 shrink-0 rounded-full bg-emerald-500" />
- <span className="truncate">
- {t(($) => $.telegram.agent_bot_connected_label)}
- {installation.bot_username ? ` · @${installation.bot_username}` : ""}
- </span>
- </span>
- <TooltipHint label={t(($) => $.telegram.agent_bot_disconnect_tooltip)}>
- <Button
- variant="destructive"
- size="sm"
- onClick={() => setConfirmOpen(true)}
- disabled={disconnecting}
- aria-label={t(($) => $.telegram.disconnect)}
- data-testid="telegram-agent-bot-disconnect"
- >
- <Trash2 className="h-3 w-3" />
- {disconnecting
- ? t(($) => $.telegram.disconnecting)
- : t(($) => $.telegram.disconnect)}
- </Button>
- </TooltipHint>
- </div>
-
- {installation.bot_username && (
- <TooltipHint label={t(($) => $.telegram.agent_bot_manage_tooltip)}>
- <button
- type="button"
- onClick={() => openExternal(`https://t.me/${installation.bot_username}`)}
- className="inline-flex items-center gap-1 text-caption text-muted-foreground underline-offset-2 transition-colors hover:text-foreground hover:underline"
- >
- <ExternalLink className="h-3 w-3" />
- {t(($) => $.telegram.agent_bot_manage_link)}
- </button>
- </TooltipHint>
- )}
-
- <AlertDialog
- open={confirmOpen}
- onOpenChange={(v) => {
- if (!v && !disconnecting) setConfirmOpen(false);
- }}
- >
- <AlertDialogContent>
- <AlertDialogHeader>
- <AlertDialogTitle>
- {t(($) => $.telegram.disconnect_confirm_title)}
- </AlertDialogTitle>
- <AlertDialogDescription>
- {t(($) => $.telegram.disconnect_confirm_description)}
- </AlertDialogDescription>
- </AlertDialogHeader>
- <AlertDialogFooter>
- <AlertDialogCancel disabled={disconnecting}>
- {t(($) => $.telegram.disconnect_confirm_cancel)}
- </AlertDialogCancel>
- <AlertDialogAction onClick={handleDisconnect} disabled={disconnecting}>
- {disconnecting
- ? t(($) => $.telegram.disconnecting)
- : t(($) => $.telegram.disconnect)}
- </AlertDialogAction>
- </AlertDialogFooter>
- </AlertDialogContent>
- </AlertDialog>
- </div>
- );
-}
diff --git a/packages/views/settings/components/use-messaging-channels.test.ts b/packages/views/settings/components/use-messaging-channels.test.ts
new file mode 100644
index 0000000000..7058c262b3
--- /dev/null
+++ b/packages/views/settings/components/use-messaging-channels.test.ts
@@ -0,0 +1,25 @@
+// @vitest-environment node
+import { describe, expect, it } from "vitest";
+import { channelChatLink, type ChannelConnection } from "./use-messaging-channels";
+
+describe("channel chat destinations", () => {
+ it.each([
+ ["feishu", "applink.feishu.cn"],
+ ["lark", "applink.larksuite.com"],
+ [undefined, "applink.feishu.cn"],
+ ])("opens the %s bot conversation with the application id", (region, host) => {
+ expect(channelChatLink({ channel: "lark", installation: { app_id: "cli_a&b", region } } as ChannelConnection))
+ .toBe(`https://${host}/client/bot/open?appId=cli_a%26b`);
+ });
+
+ it("opens Slack in the correct workspace", () => {
+ expect(channelChatLink({ channel: "slack", installation: { team_id: "T1", bot_user_id: "U2" } } as ChannelConnection))
+ .toBe("https://app.slack.com/client/T1/U2");
+ });
+
+ it("does not offer a broken link when a bot identity is missing", () => {
+ for (const channel of ["lark", "slack", "telegram", "wecom", "dingtalk"] as const) {
+ expect(channelChatLink({ channel, installation: {} } as ChannelConnection)).toBeUndefined();
+ }
+ });
+});
diff --git a/packages/views/settings/components/use-messaging-channels.ts b/packages/views/settings/components/use-messaging-channels.ts
new file mode 100644
index 0000000000..1608254e48
--- /dev/null
+++ b/packages/views/settings/components/use-messaging-channels.ts
@@ -0,0 +1,93 @@
+"use client";
+
+import { useQuery } from "@tanstack/react-query";
+import { useWorkspaceId } from "@multica/core/hooks";
+import { useCurrentMember } from "@multica/core/permissions";
+import { larkInstallationsOptions } from "@multica/core/lark";
+import { slackInstallationsOptions } from "@multica/core/slack";
+import { dingtalkInstallationsOptions } from "@multica/core/dingtalk";
+import { wecomInstallationsOptions } from "@multica/core/wecom";
+import { telegramInstallationsOptions } from "@multica/core/telegram";
+import type {
+ Agent,
+ LarkInstallation,
+ SlackInstallation,
+ DingTalkInstallation,
+ WecomInstallation,
+ TelegramInstallation,
+} from "@multica/core/types";
+import type { ChannelIntegration } from "./settings-navigation";
+
+export type ChannelConnection =
+ | { channel: "lark"; installation: LarkInstallation }
+ | { channel: "slack"; installation: SlackInstallation }
+ | { channel: "dingtalk"; installation: DingTalkInstallation }
+ | { channel: "wecom"; installation: WecomInstallation }
+ | { channel: "telegram"; installation: TelegramInstallation };
+
+export function channelChatLink(
+ connection: ChannelConnection,
+): string | undefined {
+ switch (connection.channel) {
+ case "lark":
+ return connection.installation.app_id
+ ? `https://${connection.installation.region === "lark" ? "applink.larksuite.com" : "applink.feishu.cn"}/client/bot/open?appId=${encodeURIComponent(connection.installation.app_id)}`
+ : undefined;
+ case "slack":
+ return connection.installation.team_id &&
+ connection.installation.bot_user_id
+ ? `https://app.slack.com/client/${encodeURIComponent(connection.installation.team_id)}/${encodeURIComponent(connection.installation.bot_user_id)}`
+ : undefined;
+ case "telegram":
+ return connection.installation.bot_username
+ ? `https://t.me/${encodeURIComponent(connection.installation.bot_username)}`
+ : undefined;
+ default:
+ return undefined;
+ }
+}
+
+export function useMessagingChannels() {
+ const wsId = useWorkspaceId();
+ const { member, userId, role } = useCurrentMember(wsId);
+ const enabled = !!wsId && !!member;
+ const lark = useQuery({ ...larkInstallationsOptions(wsId), enabled });
+ const slack = useQuery({ ...slackInstallationsOptions(wsId), enabled });
+ const dingtalk = useQuery({ ...dingtalkInstallationsOptions(wsId), enabled });
+ const wecom = useQuery({ ...wecomInstallationsOptions(wsId), enabled });
+ const telegram = useQuery({ ...telegramInstallationsOptions(wsId), enabled });
+ const queries = { lark, slack, dingtalk, wecom, telegram };
+ const connections: ChannelConnection[] = [
+ ...(lark.data?.installations ?? []).map((installation) => ({
+ channel: "lark" as const,
+ installation,
+ })),
+ ...(slack.data?.installations ?? []).map((installation) => ({
+ channel: "slack" as const,
+ installation,
+ })),
+ ...(dingtalk.data?.installations ?? []).map((installation) => ({
+ channel: "dingtalk" as const,
+ installation,
+ })),
+ ...(wecom.data?.installations ?? []).map((installation) => ({
+ channel: "wecom" as const,
+ installation,
+ })),
+ ...(telegram.data?.installations ?? []).map((installation) => ({
+ channel: "telegram" as const,
+ installation,
+ })),
+ ].filter(({ installation }) => installation.status === "active");
+ const isAdmin = role === "owner" || role === "admin";
+ const canManage = (channel: ChannelIntegration, agent: Agent) =>
+ !!member &&
+ (isAdmin ||
+ ((channel === "lark" || channel === "dingtalk") &&
+ agent.owner_id === userId));
+ const available = (channel: ChannelIntegration) =>
+ queries[channel].data?.configured === true &&
+ queries[channel].data?.install_supported === true;
+
+ return { wsId, queries, connections, isAdmin, canManage, available };
+}
diff --git a/packages/views/settings/components/wecom-scan-install-dialog.test.tsx b/packages/views/settings/components/wecom-channel-authorization.test.tsx
similarity index 82%
rename from packages/views/settings/components/wecom-scan-install-dialog.test.tsx
rename to packages/views/settings/components/wecom-channel-authorization.test.tsx
index 799d9997fb..80f8bbdcb1 100644
--- a/packages/views/settings/components/wecom-scan-install-dialog.test.tsx
+++ b/packages/views/settings/components/wecom-channel-authorization.test.tsx
@@ -1,7 +1,13 @@
// @vitest-environment jsdom
import { describe, it, expect, beforeEach, afterEach, vi } from "vitest";
-import { act, cleanup, fireEvent, render, screen } from "@testing-library/react";
+import {
+ act,
+ cleanup,
+ fireEvent,
+ render,
+ screen,
+} from "@testing-library/react";
import { I18nProvider } from "@multica/core/i18n/react";
import enCommon from "../../locales/en/common.json";
import enSettings from "../../locales/en/settings.json";
@@ -37,7 +43,9 @@ vi.mock("@tanstack/react-query", () => ({
}));
vi.mock("@multica/core/wecom", () => ({
- wecomKeys: { installations: (wsId: string) => ["wecom", "installations", wsId] },
+ wecomKeys: {
+ installations: (wsId: string) => ["wecom", "installations", wsId],
+ },
}));
vi.mock("@multica/core/api", () => ({
@@ -45,7 +53,9 @@ vi.mock("@multica/core/api", () => ({
ApiError: FakeApiError,
// Same contract as the real helper: the body's `code`, when there is one.
errorCode: (e: unknown) =>
- e instanceof FakeApiError ? (e.body as { code?: string } | undefined)?.code : undefined,
+ e instanceof FakeApiError
+ ? (e.body as { code?: string } | undefined)?.code
+ : undefined,
}));
vi.mock("sonner", () => ({
@@ -55,10 +65,12 @@ vi.mock("sonner", () => ({
// react-qr-code renders an <svg> that jsdom does not need; a stub keeps the
// assertion on "the QR is showing" rather than on its pixels.
vi.mock("react-qr-code", () => ({
- QRCode: ({ value }: { value: string }) => <div data-testid="qr" data-value={value} />,
+ QRCode: ({ value }: { value: string }) => (
+ <div data-testid="qr" data-value={value} />
+ ),
}));
-import { WecomScanInstallDialog } from "./wecom-scan-install-dialog";
+import { WecomChannelAuthorization } from "./wecom-channel-authorization";
const TEST_RESOURCES = { en: { common: enCommon, settings: enSettings } };
@@ -71,7 +83,11 @@ async function renderDialog(onClose = vi.fn()) {
await act(async () => {
render(
<I18nProvider locale="en" resources={TEST_RESOURCES}>
- <WecomScanInstallDialog wsId="workspace-1" agentId="agent-1" onClose={onClose} />
+ <WecomChannelAuthorization
+ wsId="workspace-1"
+ agentId="agent-1"
+ onClose={onClose}
+ />
</I18nProvider>,
);
});
@@ -87,13 +103,16 @@ beforeEach(() => {
// jsdom has no crypto.randomUUID in every environment version.
if (!globalThis.crypto?.randomUUID) {
Object.defineProperty(globalThis, "crypto", {
- value: { ...globalThis.crypto, randomUUID: () => "11111111-1111-1111-1111-111111111111" },
+ value: {
+ ...globalThis.crypto,
+ randomUUID: () => "11111111-1111-1111-1111-111111111111",
+ },
configurable: true,
});
}
});
-describe("WecomScanInstallDialog", () => {
+describe("WecomChannelAuthorization", () => {
it("shows the preparing state before the QR exists, then renders it", async () => {
mockBegin.mockResolvedValue({
session_id: "session-1",
@@ -119,7 +138,9 @@ describe("WecomScanInstallDialog", () => {
await advanceTime(1000);
const qr = screen.getByTestId("qr");
expect(qr.getAttribute("data-value")).toContain("scode=abc");
- expect(screen.getByTestId("wecom-scan-expiry").textContent).toContain("240");
+ expect(screen.getByTestId("wecom-scan-expiry").textContent).toContain(
+ "240",
+ );
});
it("invalidates the installations cache and closes on success", async () => {
@@ -188,7 +209,9 @@ describe("WecomScanInstallDialog", () => {
await advanceTime(1000);
const err = screen.getByTestId("wecom-scan-error");
- expect(err.textContent).toContain(enSettings.wecom.scan_error_internal_error);
+ expect(err.textContent).toContain(
+ enSettings.wecom.scan_error_internal_error,
+ );
});
// The two ways a scanned bot fails to bind need different actions from the
@@ -223,7 +246,9 @@ describe("WecomScanInstallDialog", () => {
status: "creating",
poll_interval_seconds: 1,
});
- mockStatus.mockRejectedValue(new FakeApiError(404, "install session not found"));
+ mockStatus.mockRejectedValue(
+ new FakeApiError(404, "install session not found"),
+ );
await renderDialog();
await advanceTime(1000);
@@ -233,12 +258,16 @@ describe("WecomScanInstallDialog", () => {
});
it("surfaces a 503 begin as the unconfigured reason", async () => {
- mockBegin.mockRejectedValue(new FakeApiError(503, "wecom scan install not enabled"));
+ mockBegin.mockRejectedValue(
+ new FakeApiError(503, "wecom scan install not enabled"),
+ );
await renderDialog();
const err = screen.getByTestId("wecom-scan-error");
- expect(err.textContent).toContain(enSettings.wecom.scan_error_integration_unconfigured);
+ expect(err.textContent).toContain(
+ enSettings.wecom.scan_error_integration_unconfigured,
+ );
// Nothing to poll when begin never produced a session.
expect(mockStatus).not.toHaveBeenCalled();
});
@@ -278,22 +307,35 @@ describe("WecomScanInstallDialog", () => {
it.each([
[409, "wecom_agent_already_connected", "scan_error_already_connected"],
[429, "wecom_scan_install_rate_limited", "scan_error_rate_limited"],
- [503, "wecom_scan_install_unavailable", "scan_error_integration_unconfigured"],
- ] as const)("shows a %i %s begin refusal as %s", async (status, code, key) => {
- const sentence = "the server's own English sentence";
- mockBegin.mockRejectedValue(new FakeApiError(status, sentence, { error: sentence, code }));
+ [
+ 503,
+ "wecom_scan_install_unavailable",
+ "scan_error_integration_unconfigured",
+ ],
+ ] as const)(
+ "shows a %i %s begin refusal as %s",
+ async (status, code, key) => {
+ const sentence = "the server's own English sentence";
+ mockBegin.mockRejectedValue(
+ new FakeApiError(status, sentence, { error: sentence, code }),
+ );
- await renderDialog();
+ await renderDialog();
- const err = screen.getByTestId("wecom-scan-error");
- expect(err.textContent).toBe(enSettings.wecom[key]);
- expect(screen.queryByText(sentence, { exact: false })).toBeNull();
- expect(mockStatus).not.toHaveBeenCalled();
- });
+ const err = screen.getByTestId("wecom-scan-error");
+ expect(err.textContent).toBe(enSettings.wecom[key]);
+ expect(screen.queryByText(sentence, { exact: false })).toBeNull();
+ expect(mockStatus).not.toHaveBeenCalled();
+ },
+ );
it("reports a malformed begin response as an error instead of polling forever", async () => {
// parseWithFallback degrades an unparseable body to an empty session id.
- mockBegin.mockResolvedValue({ session_id: "", status: "error", poll_interval_seconds: 1 });
+ mockBegin.mockResolvedValue({
+ session_id: "",
+ status: "error",
+ poll_interval_seconds: 1,
+ });
await renderDialog();
@@ -309,7 +351,8 @@ describe("WecomScanInstallDialog", () => {
const realCrypto = globalThis.crypto;
// A non-secure context keeps getRandomValues and loses randomUUID.
vi.stubGlobal("crypto", {
- getRandomValues: (b: Uint8Array<ArrayBuffer>) => realCrypto.getRandomValues(b),
+ getRandomValues: (b: Uint8Array<ArrayBuffer>) =>
+ realCrypto.getRandomValues(b),
});
try {
mockBegin.mockResolvedValue({
diff --git a/packages/views/settings/components/wecom-scan-install-dialog.tsx b/packages/views/settings/components/wecom-channel-authorization.tsx
similarity index 75%
rename from packages/views/settings/components/wecom-scan-install-dialog.tsx
rename to packages/views/settings/components/wecom-channel-authorization.tsx
index 8408702869..34a15c300e 100644
--- a/packages/views/settings/components/wecom-scan-install-dialog.tsx
+++ b/packages/views/settings/components/wecom-channel-authorization.tsx
@@ -20,14 +20,7 @@ import { toast } from "sonner";
// throws "Element type is invalid" the moment the QR mounts.
import { QRCode } from "react-qr-code";
import { Button } from "@multica/ui/components/ui/button";
-import {
- Dialog,
- DialogContent,
- DialogDescription,
- DialogFooter,
- DialogHeader,
- DialogTitle,
-} from "@multica/ui/components/ui/dialog";
+import { DialogFooter } from "@multica/ui/components/ui/dialog";
import { api, ApiError, errorCode } from "@multica/core/api";
import { createSafeId } from "@multica/core/utils";
import { wecomKeys } from "@multica/core/wecom";
@@ -63,18 +56,18 @@ const BEGIN_ERROR_REASONS: Record<string, ScanErrorReason> = {
};
function isKnownScanError(reason: string | null): reason is ScanErrorReason {
- return reason !== null && (SCAN_ERROR_KEYS as readonly string[]).includes(reason);
+ return (
+ reason !== null && (SCAN_ERROR_KEYS as readonly string[]).includes(reason)
+ );
}
-export function WecomScanInstallDialog({
+export function WecomChannelAuthorization({
wsId,
agentId,
- agentName,
onClose,
}: {
wsId: string;
agentId: string;
- agentName?: string;
onClose: () => void;
}) {
const { t } = useT("settings");
@@ -124,7 +117,9 @@ export function WecomScanInstallDialog({
const code = errorCode(e);
setErrorReason(
(code && BEGIN_ERROR_REASONS[code]) ??
- (e instanceof ApiError && e.status === 503 ? "integration_unconfigured" : "internal_error"),
+ (e instanceof ApiError && e.status === 503
+ ? "integration_unconfigured"
+ : "internal_error"),
);
} finally {
if (!closedRef.current) setBeginning(false);
@@ -168,8 +163,10 @@ export function WecomScanInstallDialog({
setExpiresInSeconds(res.expires_in_seconds);
}
if (res.status === "success") {
- await qc.invalidateQueries({ queryKey: wecomKeys.installations(wsId) });
- toast.success(t(($) => $.wecom.scan_success_toast));
+ await qc.invalidateQueries({
+ queryKey: wecomKeys.installations(wsId),
+ });
+ toast.success(t(($) => $.channels.connect_success));
// The close itself is deliberately NOT scheduled here: `status` is a
// dependency of this effect, so setting it to "success" re-runs the
// effect and the cleanup would cancel the very timer meant to close
@@ -219,8 +216,12 @@ export function WecomScanInstallDialog({
? {
expired: t(($) => $.wecom.scan_error_expired),
generate_failed: t(($) => $.wecom.scan_error_generate_failed),
- integration_unconfigured: t(($) => $.wecom.scan_error_integration_unconfigured),
- installation_conflict: t(($) => $.wecom.scan_error_installation_conflict),
+ integration_unconfigured: t(
+ ($) => $.wecom.scan_error_integration_unconfigured,
+ ),
+ installation_conflict: t(
+ ($) => $.wecom.scan_error_installation_conflict,
+ ),
bind_failed: t(($) => $.wecom.scan_error_bind_failed),
wecom_protocol_error: t(($) => $.wecom.scan_error_wecom_protocol_error),
internal_error: t(($) => $.wecom.scan_error_internal_error),
@@ -231,70 +232,64 @@ export function WecomScanInstallDialog({
: t(($) => $.wecom.scan_error_internal_error);
return (
- <Dialog
- open
- onOpenChange={(o) => {
- if (!o) onClose();
- }}
- >
- <DialogContent className="max-w-sm" data-testid="wecom-scan-dialog">
- <DialogHeader>
- <DialogTitle>{t(($) => $.wecom.scan_dialog_title)}</DialogTitle>
- <DialogDescription>
- {agentName
- ? t(($) => $.wecom.bind_button_title, { agent: agentName })
- : t(($) => $.wecom.scan_hint)}
- </DialogDescription>
- </DialogHeader>
-
- <div className="flex flex-col items-center gap-4 py-2">
- {(beginning || status === "creating") && !qrCodeURL && status !== "error" && (
- <p className="text-body text-muted-foreground" data-testid="wecom-scan-starting">
+ <>
+ <div className="flex flex-col items-center gap-4 py-2">
+ {(beginning || status === "creating") &&
+ !qrCodeURL &&
+ status !== "error" && (
+ <p
+ className="text-body text-muted-foreground"
+ data-testid="wecom-scan-starting"
+ >
{t(($) => $.wecom.scan_starting)}
</p>
)}
- {status === "pending" && qrCodeURL && (
- <>
- {/* White plate regardless of theme: a QR needs light quiet zones
+ {status === "pending" && qrCodeURL && (
+ <>
+ {/* White plate regardless of theme: a QR needs light quiet zones
to scan, and the dark-mode surface token would invert it. */}
- <div className="rounded-md border bg-white p-3">
- <QRCode value={qrCodeURL} size={192} />
- </div>
- <p className="text-caption text-muted-foreground text-center">
- {t(($) => $.wecom.scan_hint)}
+ <div className="rounded-md border bg-white p-3">
+ <QRCode value={qrCodeURL} size={192} />
+ </div>
+ <p className="text-caption text-muted-foreground text-center">
+ {t(($) => $.wecom.scan_hint)}
+ </p>
+ {expiresInSeconds !== null && expiresInSeconds > 0 && (
+ <p
+ className="text-caption text-muted-foreground"
+ data-testid="wecom-scan-expiry"
+ >
+ {t(($) => $.wecom.scan_expires_in, {
+ seconds: expiresInSeconds,
+ })}
</p>
- {expiresInSeconds !== null && expiresInSeconds > 0 && (
- <p className="text-caption text-muted-foreground" data-testid="wecom-scan-expiry">
- {t(($) => $.wecom.scan_expires_in, { seconds: expiresInSeconds })}
- </p>
- )}
- </>
- )}
+ )}
+ </>
+ )}
- {status === "error" && (
- <div className="text-center" data-testid="wecom-scan-error">
- <p className="text-body">{scanErrorText}</p>
- </div>
- )}
- </div>
+ {status === "error" && (
+ <div className="text-center" data-testid="wecom-scan-error">
+ <p className="text-body">{scanErrorText}</p>
+ </div>
+ )}
+ </div>
- <DialogFooter>
- <Button variant="outline" size="sm" onClick={onClose}>
- {t(($) => $.wecom.scan_close)}
+ <DialogFooter>
+ <Button variant="outline" size="sm" onClick={onClose}>
+ {t(($) => $.wecom.scan_close)}
+ </Button>
+ {status === "error" && (
+ <Button
+ size="sm"
+ onClick={() => void beginSession()}
+ disabled={beginning}
+ data-testid="wecom-scan-retry"
+ >
+ {t(($) => $.wecom.scan_again)}
</Button>
- {status === "error" && (
- <Button
- size="sm"
- onClick={() => void beginSession()}
- disabled={beginning}
- data-testid="wecom-scan-retry"
- >
- {t(($) => $.wecom.scan_again)}
- </Button>
- )}
- </DialogFooter>
- </DialogContent>
- </Dialog>
+ )}
+ </DialogFooter>
+ </>
);
}
diff --git a/packages/views/settings/components/wecom-tab.test.tsx b/packages/views/settings/components/wecom-tab.test.tsx
deleted file mode 100644
index 1d036a0cea..0000000000
--- a/packages/views/settings/components/wecom-tab.test.tsx
+++ /dev/null
@@ -1,359 +0,0 @@
-// @vitest-environment jsdom
-
-import { type ReactNode } from "react";
-import { describe, it, expect, beforeEach, afterEach, vi } from "vitest";
-import { cleanup, render, screen, waitFor, within } from "@testing-library/react";
-import userEvent from "@testing-library/user-event";
-import { I18nProvider } from "@multica/core/i18n/react";
-import enCommon from "../../locales/en/common.json";
-import enSettings from "../../locales/en/settings.json";
-
-// wecom-tab.test.tsx — the Settings → Integrations WeCom panel and the per-agent
-// bind button. Mirrors dingtalk-tab.test.tsx. Covers the admin gate, the BYO
-// install dialog + credential trimming, the connected badge, the not-enabled /
-// empty states, and confirm-before-disconnect.
-//
-// Co-authored analysis: seacen (PR #5833 review).
-
-type MemberRole = "owner" | "admin" | "member" | "guest";
-
-const membersRef = vi.hoisted(() => ({
- current: [{ user_id: "user-1", role: "owner" as MemberRole }],
-}));
-const installationsRef = vi.hoisted(() => ({
- current: {
- installations: [],
- configured: true,
- install_supported: true,
- } as {
- installations: unknown[];
- configured: boolean;
- install_supported: boolean;
- scan_install_supported?: boolean;
- },
-}));
-const mockRegisterBYO = vi.hoisted(() => vi.fn());
-const mockDeleteInstallation = vi.hoisted(() => vi.fn());
-const mockInvalidate = vi.hoisted(() => vi.fn());
-
-vi.mock("@tanstack/react-query", () => ({
- useQuery: (opts: { queryKey: unknown[]; enabled?: boolean }) => {
- if (opts.enabled === false) return { data: undefined, isLoading: false };
- const key = JSON.stringify(opts.queryKey);
- if (key.includes("members")) return { data: membersRef.current, isLoading: false };
- if (key.includes("installations")) return { data: installationsRef.current, isLoading: false };
- return { data: undefined, isLoading: false };
- },
- useQueryClient: () => ({ invalidateQueries: mockInvalidate }),
- queryOptions: <T,>(opts: T) => opts,
-}));
-
-vi.mock("@multica/core/hooks", () => ({ useWorkspaceId: () => "workspace-1" }));
-
-vi.mock("@multica/core/workspace/queries", () => ({
- memberListOptions: () => ({ queryKey: ["members"], queryFn: vi.fn() }),
-}));
-
-vi.mock("@multica/core/workspace/hooks", () => ({
- useActorName: () => ({
- getAgentName: (agentId: string) => `Agent ${agentId}`,
- getMemberName: () => "Unknown",
- getSquadName: () => "Unknown Squad",
- getActorName: () => "Unknown",
- getActorInitials: () => "??",
- getActorAvatarUrl: () => null,
- }),
-}));
-
-vi.mock("../../common/actor-avatar", () => ({
- ActorAvatar: ({ actorId }: { actorId: string }) => (
- <span data-testid="actor-avatar" data-actor-id={actorId} />
- ),
-}));
-
-vi.mock("@multica/core/wecom", () => ({
- wecomInstallationsOptions: () => ({
- queryKey: ["wecom", "installations"],
- queryFn: vi.fn(),
- }),
- wecomKeys: { installations: (wsId: string) => ["wecom", "installations", wsId] },
-}));
-
-vi.mock("@multica/core/api", () => ({
- api: {
- registerWecomBYO: mockRegisterBYO,
- deleteWecomInstallation: mockDeleteInstallation,
- },
- // The real one digs the code out of an ApiError body; the fake reads it off
- // whatever the test threw, so a test can drive one branch of the switch.
- errorCode: (e: unknown) =>
- e && typeof e === "object" ? (e as { code?: string }).code : undefined,
-}));
-
-vi.mock("@multica/core/auth", () => {
- const useAuthStore = Object.assign(
- (sel?: (s: { user: { id: string } }) => unknown) =>
- sel ? sel({ user: { id: "user-1" } }) : { user: { id: "user-1" } },
- { getState: () => ({ user: { id: "user-1" } }) },
- );
- return { useAuthStore };
-});
-
-vi.mock("sonner", () => ({
- toast: { success: vi.fn(), error: vi.fn(), message: vi.fn() },
-}));
-
-// The scan dialog has its own test; here it only has to be the thing that opens.
-vi.mock("./wecom-scan-install-dialog", () => ({
- WecomScanInstallDialog: ({ agentId }: { agentId: string }) => (
- <div data-testid="wecom-scan-dialog-stub" data-agent-id={agentId} />
- ),
-}));
-
-import { toast } from "sonner";
-import { WecomAgentBindButton, WecomTab } from "./wecom-tab";
-
-const TEST_RESOURCES = { en: { common: enCommon, settings: enSettings } };
-
-afterEach(cleanup);
-
-function renderUI(children: ReactNode) {
- return render(
- <I18nProvider locale="en" resources={TEST_RESOURCES}>
- {children}
- </I18nProvider>,
- );
-}
-
-function resetFixtures() {
- vi.clearAllMocks();
- membersRef.current = [{ user_id: "user-1", role: "owner" }];
- installationsRef.current = { installations: [], configured: true, install_supported: true };
-}
-
-describe("WecomAgentBindButton", () => {
- beforeEach(resetFixtures);
-
- // Scanning needs a QR provider on top of the secret key, so the server says
- // separately whether it works. Anything but an explicit true — an older
- // server sends nothing — leaves only the BYO form, rather than a button that
- // 503s.
- it.each([undefined, false])("offers no scan option when scan_install_supported is %s", async (flag) => {
- installationsRef.current.scan_install_supported = flag;
- renderUI(<WecomAgentBindButton agentId="agent-1" agentName="Bot" />);
- await userEvent.click(screen.getByTestId("wecom-agent-connect"));
- await screen.findByTestId("wecom-byo-bot-id");
- expect(screen.queryByTestId("wecom-scan-option")).toBeNull();
- });
-
- it("opens the scan dialog for this agent from the scan option", async () => {
- installationsRef.current.scan_install_supported = true;
- renderUI(<WecomAgentBindButton agentId="agent-1" agentName="Bot" />);
- await userEvent.click(screen.getByTestId("wecom-agent-connect"));
- await userEvent.click(await screen.findByTestId("wecom-scan-option"));
- const dialog = await screen.findByTestId("wecom-scan-dialog-stub");
- expect(dialog.getAttribute("data-agent-id")).toBe("agent-1");
- // The BYO dialog closes behind it rather than stacking two modals.
- expect(screen.queryByTestId("wecom-byo-bot-id")).toBeNull();
- });
-
- it("opens the BYO dialog and submits the trimmed bot id + secret", async () => {
- mockRegisterBYO.mockResolvedValue({ id: "i1", agent_id: "agent-1", status: "active" });
- renderUI(<WecomAgentBindButton agentId="agent-1" agentName="Bot" />);
- await userEvent.click(screen.getByTestId("wecom-agent-connect"));
- await userEvent.type(await screen.findByTestId("wecom-byo-bot-id"), " aibot_xyz ");
- await userEvent.type(screen.getByTestId("wecom-byo-secret"), " s3cr3t ");
- await userEvent.click(screen.getByTestId("wecom-byo-submit"));
- await waitFor(() =>
- // Credential trimming: leading/trailing whitespace is stripped before send.
- expect(mockRegisterBYO).toHaveBeenCalledWith("workspace-1", "agent-1", {
- bot_id: "aibot_xyz",
- secret: "s3cr3t",
- }),
- );
- });
-
- // The whole point of the server sending a code: a zh-Hans admin gets the
- // Chinese sentence, not the English one the API happens to carry.
- it("renders the localized sentence for a coded failure, not the server's English", async () => {
- mockRegisterBYO.mockRejectedValue(
- Object.assign(new Error("this bot is already connected to another agent in this workspace"), {
- code: "wecom_bot_owned_by_same_workspace",
- }),
- );
- renderUI(<WecomAgentBindButton agentId="agent-1" agentName="Bot" />);
- await userEvent.click(screen.getByTestId("wecom-agent-connect"));
- await userEvent.type(await screen.findByTestId("wecom-byo-bot-id"), "aibot_xyz");
- await userEvent.type(screen.getByTestId("wecom-byo-secret"), "s3cr3t");
- await userEvent.click(screen.getByTestId("wecom-byo-submit"));
- await waitFor(() =>
- expect(toast.error).toHaveBeenCalledWith(enSettings.wecom.byo_conflict_same_workspace),
- );
- });
-
- // The 503 branch: we could not reach WeCom, so nothing was verified and
- // nothing was changed. The admin must not read this as "your secret is
- // wrong" — that sends them to rotate one that was fine, and a rotated WeCom
- // secret cannot be recovered. Separate code, separate sentence.
- it("tells the admin their credentials were not changed when WeCom was unreachable", async () => {
- mockRegisterBYO.mockRejectedValue(
- Object.assign(new Error("could not reach WeCom to verify this bot"), {
- code: "wecom_credentials_unverifiable",
- }),
- );
- renderUI(<WecomAgentBindButton agentId="agent-1" agentName="Bot" />);
- await userEvent.click(screen.getByTestId("wecom-agent-connect"));
- await userEvent.type(await screen.findByTestId("wecom-byo-bot-id"), "aibot_xyz");
- await userEvent.type(screen.getByTestId("wecom-byo-secret"), "s3cr3t");
- await userEvent.click(screen.getByTestId("wecom-byo-submit"));
- await waitFor(() =>
- expect(toast.error).toHaveBeenCalledWith(enSettings.wecom.byo_credentials_unverifiable),
- );
- });
-
- // WeCom refusing the pair is the one outcome entitled to blame the
- // credentials, and it must not reuse byo_rejected — that sentence means
- // "you left a field out".
- it("renders the credentials-rejected sentence, distinct from the missing-field one", async () => {
- mockRegisterBYO.mockRejectedValue(
- Object.assign(new Error("WeCom rejected this Bot ID and secret"), {
- code: "wecom_credentials_rejected",
- }),
- );
- renderUI(<WecomAgentBindButton agentId="agent-1" agentName="Bot" />);
- await userEvent.click(screen.getByTestId("wecom-agent-connect"));
- await userEvent.type(await screen.findByTestId("wecom-byo-bot-id"), "aibot_xyz");
- await userEvent.type(screen.getByTestId("wecom-byo-secret"), "s3cr3t");
- await userEvent.click(screen.getByTestId("wecom-byo-submit"));
- await waitFor(() =>
- expect(toast.error).toHaveBeenCalledWith(enSettings.wecom.byo_credentials_rejected),
- );
- expect(toast.error).not.toHaveBeenCalledWith(enSettings.wecom.byo_rejected);
- });
-
- // A server that sends no code must still say something useful, so the
- // fallback cannot regress into the generic toast.
- it("falls back to the server's message when no code is attached", async () => {
- mockRegisterBYO.mockRejectedValue(new Error("something the server said"));
- renderUI(<WecomAgentBindButton agentId="agent-1" agentName="Bot" />);
- await userEvent.click(screen.getByTestId("wecom-agent-connect"));
- await userEvent.type(await screen.findByTestId("wecom-byo-bot-id"), "aibot_xyz");
- await userEvent.type(screen.getByTestId("wecom-byo-secret"), "s3cr3t");
- await userEvent.click(screen.getByTestId("wecom-byo-submit"));
- await waitFor(() =>
- expect(toast.error).toHaveBeenCalledWith("something the server said"),
- );
- });
-
- // The bot's chat name reaches the server, and only when it was typed.
- //
- // WeCom delivers a group @-mention as literal text with no structured
- // mention list, so a name containing a space ("Multica Bot") swallows the
- // slash command typed after it. The name is the only way to tell where the
- // mention ends — and it cannot be discovered, because the smart bot exposes
- // no REST surface to ask. Left blank, the request omits it entirely so a
- // re-install keeps whatever name the row already carries.
- it("sends the bot's chat name when one is given, and omits it when not", async () => {
- mockRegisterBYO.mockResolvedValue({ id: "i-1" });
- renderUI(<WecomAgentBindButton agentId="agent-1" />);
- await userEvent.click(screen.getByTestId("wecom-agent-connect"));
- await userEvent.type(await screen.findByTestId("wecom-byo-bot-id"), "aib94");
- await userEvent.type(screen.getByTestId("wecom-byo-secret"), "s3cret");
- await userEvent.type(screen.getByTestId("wecom-byo-bot-name"), " Multica Bot ");
- await userEvent.click(screen.getByTestId("wecom-byo-submit"));
-
- await waitFor(() => expect(mockRegisterBYO).toHaveBeenCalled());
- expect(mockRegisterBYO.mock.calls[0]?.[2].bot_name).toBe("Multica Bot");
-
- cleanup();
- mockRegisterBYO.mockClear();
- mockRegisterBYO.mockResolvedValue({ id: "i-2" });
- renderUI(<WecomAgentBindButton agentId="agent-2" />);
- await userEvent.click(screen.getByTestId("wecom-agent-connect"));
- await userEvent.type(await screen.findByTestId("wecom-byo-bot-id"), "aib95");
- await userEvent.type(screen.getByTestId("wecom-byo-secret"), "s3cret");
- await userEvent.click(screen.getByTestId("wecom-byo-submit"));
-
- await waitFor(() => expect(mockRegisterBYO).toHaveBeenCalled());
- expect(mockRegisterBYO.mock.calls[0]?.[2].bot_name).toBeUndefined();
- });
-
- it("shows the connected badge (not the CTA) when the agent has an active install", () => {
- installationsRef.current = {
- installations: [{ id: "i1", agent_id: "agent-1", bot_id: "aibot_x", status: "active" }],
- configured: true,
- install_supported: true,
- };
- renderUI(<WecomAgentBindButton agentId="agent-1" />);
- expect(screen.getByTestId("wecom-agent-bot-connected")).toBeTruthy();
- expect(screen.queryByTestId("wecom-agent-connect")).toBeNull();
- });
-
- it("treats a revoked install as unbound — shows the CTA, not the connected badge", () => {
- installationsRef.current = {
- installations: [{ id: "i1", agent_id: "agent-1", bot_id: "aibot_x", status: "revoked" }],
- configured: true,
- install_supported: true,
- };
- renderUI(<WecomAgentBindButton agentId="agent-1" agentName="Bot" />);
- expect(screen.getByTestId("wecom-agent-connect")).toBeTruthy();
- expect(screen.queryByTestId("wecom-agent-bot-connected")).toBeNull();
- });
-
- it("renders nothing for a non-manager (member)", () => {
- membersRef.current = [{ user_id: "user-1", role: "member" }];
- const { container } = renderUI(<WecomAgentBindButton agentId="agent-1" />);
- expect(container).toBeEmptyDOMElement();
- });
-
- it("renders nothing when install is unavailable and the agent is unbound", () => {
- installationsRef.current = { installations: [], configured: true, install_supported: false };
- const { container } = renderUI(<WecomAgentBindButton agentId="agent-1" />);
- expect(container).toBeEmptyDOMElement();
- });
-});
-
-describe("WecomTab", () => {
- beforeEach(resetFixtures);
-
- it("surfaces the not-enabled notice when the deployment has no WeCom key", () => {
- installationsRef.current = { installations: [], configured: false, install_supported: false };
- renderUI(<WecomTab />);
- expect(screen.getByText(/WeCom integration not enabled/i)).toBeTruthy();
- });
-
- it("shows the empty state when configured but nothing is connected", () => {
- renderUI(<WecomTab />);
- expect(screen.getByText(/No bots connected yet/i)).toBeTruthy();
- });
-
- it("lists a connected installation with its agent name and a disconnect control", () => {
- installationsRef.current = {
- installations: [{ id: "i1", agent_id: "agent-7", bot_id: "aibot_x", status: "active" }],
- configured: true,
- install_supported: true,
- };
- renderUI(<WecomTab />);
- expect(screen.getByText("Agent agent-7")).toBeTruthy();
- expect(screen.getByRole("button", { name: /disconnect/i })).toBeTruthy();
- });
-
- it("confirms before disconnecting, then calls deleteWecomInstallation", async () => {
- mockDeleteInstallation.mockResolvedValue(undefined);
- installationsRef.current = {
- installations: [{ id: "i1", agent_id: "agent-7", bot_id: "aibot_x", status: "active" }],
- configured: true,
- install_supported: true,
- };
- renderUI(<WecomTab />);
- // The row control only opens the confirm dialog — it must NOT delete yet.
- await userEvent.click(screen.getByRole("button", { name: /disconnect/i }));
- expect(mockDeleteInstallation).not.toHaveBeenCalled();
- // Confirm inside the alert dialog.
- const dialog = await screen.findByRole("alertdialog");
- await userEvent.click(within(dialog).getByRole("button", { name: /disconnect/i }));
- await waitFor(() =>
- expect(mockDeleteInstallation).toHaveBeenCalledWith("workspace-1", "i1"),
- );
- });
-});
diff --git a/packages/views/settings/components/wecom-tab.tsx b/packages/views/settings/components/wecom-tab.tsx
deleted file mode 100644
index 381ef97f6b..0000000000
--- a/packages/views/settings/components/wecom-tab.tsx
+++ /dev/null
@@ -1,635 +0,0 @@
-"use client";
-
-import { useState } from "react";
-import { useQuery, useQueryClient } from "@tanstack/react-query";
-import { toast } from "sonner";
-import { ChevronRight, Trash2 } from "@multica/ui/icons";
-import { WecomMark } from "./wecom-mark";
-import { cn } from "@multica/ui/lib/utils";
-import { Button } from "@multica/ui/components/ui/button";
-import { Card, CardContent } from "@multica/ui/components/ui/card";
-import {
- Dialog,
- DialogContent,
- DialogFooter,
- DialogHeader,
- DialogTitle,
-} from "@multica/ui/components/ui/dialog";
-import { Input } from "@multica/ui/components/ui/input";
-import { Label } from "@multica/ui/components/ui/label";
-import {
- AlertDialog,
- AlertDialogAction,
- AlertDialogCancel,
- AlertDialogContent,
- AlertDialogDescription,
- AlertDialogFooter,
- AlertDialogHeader,
- AlertDialogTitle,
-} from "@multica/ui/components/ui/alert-dialog";
-import { useAuthStore } from "@multica/core/auth";
-import { useWorkspaceId } from "@multica/core/hooks";
-import { memberListOptions } from "@multica/core/workspace/queries";
-import { useActorName } from "@multica/core/workspace/hooks";
-import { wecomInstallationsOptions, wecomKeys } from "@multica/core/wecom";
-import { errorCode } from "@multica/core/api";
-import { api } from "@multica/core/api";
-import type { WecomInstallation } from "@multica/core/types";
-import { WecomScanInstallDialog } from "./wecom-scan-install-dialog";
-import { ActorAvatar } from "../../common/actor-avatar";
-import { useT } from "../../i18n";
-import { TooltipHint } from "@multica/ui/components/common/tooltip-hint";
-
-// WecomTab is the workspace settings panel for WeCom smart-bot
-// installations. Listing is member-visible; the disconnect action is
-// admin-only (the backend enforces it; the UI hides the button for non-
-// admins to match).
-//
-// Adding a new installation flows through the Agent detail page: the install
-// path is per-agent (each Multica agent gets exactly one bot — the
-// (workspace_id, agent_id, channel_type) UNIQUE in channel_installation), so
-// asking the user to pick an agent here would re-create that page's picker.
-export function WecomTab() {
- const { t } = useT("settings");
- const wsId = useWorkspaceId();
- const qc = useQueryClient();
- const user = useAuthStore((s) => s.user);
-
- const { data: members = [] } = useQuery(memberListOptions(wsId));
- const currentMember = members.find((m) => m.user_id === user?.id) ?? null;
- const canManage =
- currentMember?.role === "owner" || currentMember?.role === "admin";
-
- const { data, isLoading } = useQuery({
- ...wecomInstallationsOptions(wsId),
- enabled: !!wsId,
- });
- const installations = data?.installations ?? [];
- const configured = data?.configured === true;
- const installSupported = data?.install_supported === true;
-
- const [disconnectTarget, setDisconnectTarget] = useState<string | null>(null);
- const [disconnecting, setDisconnecting] = useState(false);
-
- async function handleDisconnect() {
- if (!disconnectTarget || disconnecting) return;
- setDisconnecting(true);
- try {
- await api.deleteWecomInstallation(wsId, disconnectTarget);
- await qc.invalidateQueries({ queryKey: wecomKeys.installations(wsId) });
- toast.success(t(($) => $.wecom.toast_disconnected));
- setDisconnectTarget(null);
- } catch (e) {
- toast.error(
- e instanceof Error ? e.message : t(($) => $.wecom.toast_disconnect_failed),
- );
- } finally {
- setDisconnecting(false);
- }
- }
-
- return (
- <div className="space-y-8">
- {!configured ? (
- <Card>
- <CardContent className="space-y-2">
- <p className="text-body font-medium">{t(($) => $.wecom.not_enabled_title)}</p>
- <p className="text-caption text-muted-foreground">
- {t(($) => $.wecom.not_enabled_description_prefix)}{" "}
- <code className="rounded-xs bg-muted px-1 py-0.5 text-micro">
- MULTICA_WECOM_SECRET_KEY
- </code>{" "}
- {t(($) => $.wecom.not_enabled_description_suffix)}{" "}
- {t(($) => $.wecom.not_enabled_self_host_hint)}
- </p>
- </CardContent>
- </Card>
- ) : !installSupported && installations.length === 0 ? (
- <Card>
- <CardContent className="space-y-2">
- <p className="text-body font-medium">{t(($) => $.wecom.preview_title)}</p>
- <p className="text-caption text-muted-foreground">
- {t(($) => $.wecom.preview_description)}
- </p>
- </CardContent>
- </Card>
- ) : (
- <section className="space-y-3">
- <h2 className="text-body font-semibold">{t(($) => $.wecom.connected_bots)}</h2>
- {isLoading ? (
- <Card>
- <CardContent>
- <p className="text-body text-muted-foreground">{t(($) => $.wecom.loading)}</p>
- </CardContent>
- </Card>
- ) : installations.length === 0 ? (
- <Card>
- <CardContent className="space-y-2">
- <p className="text-body font-medium">{t(($) => $.wecom.empty_title)}</p>
- <p className="text-caption text-muted-foreground">
- {t(($) => $.wecom.empty_description_prefix)}{" "}
- <strong>{t(($) => $.wecom.empty_description_cta)}</strong>{" "}
- {t(($) => $.wecom.empty_description_suffix)}
- </p>
- </CardContent>
- </Card>
- ) : (
- <Card>
- <CardContent className="divide-y">
- {installations.map((inst) => (
- <InstallationRow
- key={inst.id}
- installation={inst}
- canManage={canManage}
- onDisconnect={() => setDisconnectTarget(inst.id)}
- />
- ))}
- </CardContent>
- </Card>
- )}
- </section>
- )}
-
- <AlertDialog
- open={!!disconnectTarget}
- onOpenChange={(v) => {
- if (!v && !disconnecting) setDisconnectTarget(null);
- }}
- >
- <AlertDialogContent>
- <AlertDialogHeader>
- <AlertDialogTitle>
- {t(($) => $.wecom.disconnect_confirm_title)}
- </AlertDialogTitle>
- <AlertDialogDescription>
- {t(($) => $.wecom.disconnect_confirm_description)}
- </AlertDialogDescription>
- </AlertDialogHeader>
- <AlertDialogFooter>
- <AlertDialogCancel disabled={disconnecting}>
- {t(($) => $.wecom.disconnect_confirm_cancel)}
- </AlertDialogCancel>
- <AlertDialogAction onClick={handleDisconnect} disabled={disconnecting}>
- {disconnecting
- ? t(($) => $.wecom.disconnecting)
- : t(($) => $.wecom.disconnect)}
- </AlertDialogAction>
- </AlertDialogFooter>
- </AlertDialogContent>
- </AlertDialog>
- </div>
- );
-}
-
-function InstallationRow({
- installation,
- canManage,
- onDisconnect,
-}: {
- installation: WecomInstallation;
- canManage: boolean;
- onDisconnect: () => void;
-}) {
- const { t } = useT("settings");
- const { getAgentName } = useActorName();
- const isActive = installation.status === "active";
- const agentName = getAgentName(installation.agent_id);
- return (
- <div className="flex items-start justify-between gap-4 py-3 first:pt-0 last:pb-0">
- <div className="flex items-start gap-3">
- <ActorAvatar
- actorType="agent"
- actorId={installation.agent_id}
- size="lg"
- enableHoverCard
- profileLink
- />
- <div className="space-y-1">
- <p className="text-body font-medium">
- {agentName}
- {!isActive && (
- <span className="ml-2 rounded-xs bg-muted px-1.5 py-0.5 text-micro text-muted-foreground">
- {t(($) => $.wecom.revoked_badge)}
- </span>
- )}
- </p>
- <p className="text-micro text-muted-foreground">
- {t(($) => $.wecom.bot_id_label, { botId: installation.bot_id })}
- </p>
- </div>
- </div>
- {canManage && isActive && (
- <Button variant="outline" size="sm" onClick={onDisconnect}>
- <Trash2 className="h-3 w-3" />
- {t(($) => $.wecom.disconnect)}
- </Button>
- )}
- </div>
- );
-}
-
-// WecomAgentBindButton is the per-agent CTA exposed from the agent detail
-// page. Wecom smart-bot uses the bring-your-own-bot model: the button opens
-// a dialog where the admin pastes the bot's stable identifier (bot_id) and
-// its long-connection secret from the WeCom admin console.
-// Visibility:
-// 1. Non-owner/admin viewers see nothing (the backend gates install/revoke).
-// 2. If this agent already has an active installation, show the connected
-// badge.
-// 3. Otherwise the Connect CTA shows whenever install is available.
-export function WecomAgentBindButton({
- agentId,
- agentName,
- className,
- onShowConnectedDetails,
-}: {
- agentId: string;
- agentName?: string;
- className?: string;
- onShowConnectedDetails?: () => void;
-}) {
- const { t } = useT("settings");
- const wsId = useWorkspaceId();
- const qc = useQueryClient();
- const user = useAuthStore((s) => s.user);
-
- const [dialogOpen, setDialogOpen] = useState(false);
- const [scanOpen, setScanOpen] = useState(false);
- const [botId, setBotId] = useState("");
- const [secret, setSecret] = useState("");
- const [botName, setBotName] = useState("");
- const [submitting, setSubmitting] = useState(false);
-
- const { data: listing } = useQuery({
- ...wecomInstallationsOptions(wsId),
- enabled: !!wsId,
- });
- const installSupported = listing?.install_supported === true;
- // Scan needs a QR provider on top of the secret key, so it can be off where
- // BYO works. When it is off the dialog shows only the BYO fields.
- const scanSupported = listing?.scan_install_supported === true;
-
- const { data: members = [] } = useQuery({
- ...memberListOptions(wsId),
- enabled: !!wsId,
- });
- const currentMember = members.find((m) => m.user_id === user?.id) ?? null;
- const canManage =
- currentMember?.role === "owner" || currentMember?.role === "admin";
-
- if (!canManage) return null;
-
- const existing = listing?.installations.find(
- (inst) => inst.agent_id === agentId && inst.status === "active",
- );
- if (existing) {
- return onShowConnectedDetails ? (
- <WecomAgentBotStatusRow
- onClick={onShowConnectedDetails}
- className={className}
- />
- ) : (
- <WecomAgentBotConnectedBadge installation={existing} className={className} />
- );
- }
-
- if (!installSupported) return null;
-
- function closeDialog() {
- if (submitting) return;
- setDialogOpen(false);
- setBotId("");
- setSecret("");
- setBotName("");
- }
-
- async function handleSubmit() {
- const bot_id = botId.trim();
- const secretTrimmed = secret.trim();
- if (submitting || !agentId || !bot_id || !secretTrimmed) return;
- setSubmitting(true);
- try {
- await api.registerWecomBYO(wsId, agentId, {
- bot_id,
- secret: secretTrimmed,
- bot_name: botName.trim() || undefined,
- });
- await qc.invalidateQueries({ queryKey: wecomKeys.installations(wsId) });
- toast.success(t(($) => $.wecom.byo_success_toast));
- setDialogOpen(false);
- setBotId("");
- setSecret("");
- setBotName("");
- } catch (e) {
- // The server sends a stable `code` alongside the English sentence, so
- // the admin reads the failure in their own language. The sentence is
- // still the fallback: an older server, or a failure that has not been
- // given a code, sends none.
- let localized: string | undefined;
- switch (errorCode(e)) {
- case "wecom_bot_owned_by_same_workspace":
- localized = t(($) => $.wecom.byo_conflict_same_workspace);
- break;
- case "wecom_bot_owned_by_archived_agent":
- localized = t(($) => $.wecom.byo_conflict_archived_agent);
- break;
- case "wecom_bot_owned_by_another_workspace":
- localized = t(($) => $.wecom.byo_conflict_other_workspace);
- break;
- case "wecom_install_rejected":
- localized = t(($) => $.wecom.byo_rejected);
- break;
- // Distinct from the two above on purpose: "you left a field out",
- // "WeCom said no" and "we couldn't ask WeCom" are three different
- // things for the admin to do, so they get three different sentences.
- case "wecom_credentials_rejected":
- localized = t(($) => $.wecom.byo_credentials_rejected);
- break;
- case "wecom_credentials_unverifiable":
- localized = t(($) => $.wecom.byo_credentials_unverifiable);
- break;
- case "wecom_install_failed":
- localized = t(($) => $.wecom.byo_install_failed);
- break;
- }
- toast.error(
- localized ??
- (e instanceof Error ? e.message : t(($) => $.wecom.byo_failed_toast)),
- );
- } finally {
- setSubmitting(false);
- }
- }
-
- const canSubmit =
- botId.trim() !== "" && secret.trim() !== "" && !submitting;
-
- return (
- <div
- className={cn("flex flex-wrap items-center gap-2", className)}
- data-testid="wecom-agent-bind-buttons"
- >
- <TooltipHint
- label={
- agentName
- ? t(($) => $.wecom.bind_button_title, { agent: agentName })
- : undefined
- }
- >
- <Button
- variant="outline"
- size="sm"
- onClick={() => setDialogOpen(true)}
- disabled={!agentId}
- data-testid="wecom-agent-connect"
- >
- <WecomMark className="h-3 w-3" />
- {t(($) => $.wecom.bind_button)}
- </Button>
- </TooltipHint>
-
- <Dialog
- open={dialogOpen}
- onOpenChange={(v) => (v ? setDialogOpen(true) : closeDialog())}
- >
- <DialogContent className="sm:max-w-lg" data-testid="wecom-byo-dialog">
- <DialogHeader>
- <DialogTitle>{t(($) => $.wecom.byo_dialog_title)}</DialogTitle>
- </DialogHeader>
-
- <div className="space-y-4">
- {scanSupported && (
- <div className="space-y-3">
- <button
- type="button"
- className="w-full rounded-md border p-3 text-left transition-colors hover:bg-accent"
- onClick={() => {
- setDialogOpen(false);
- setScanOpen(true);
- }}
- disabled={submitting}
- data-testid="wecom-scan-option"
- >
- <span className="text-body font-medium">
- {t(($) => $.wecom.scan_option_title)}
- </span>
- <span className="text-caption text-muted-foreground mt-0.5 block">
- {t(($) => $.wecom.scan_option_description)}
- </span>
- </button>
- <div className="space-y-0.5">
- <p className="text-body font-medium">
- {t(($) => $.wecom.byo_option_title)}
- </p>
- <p className="text-caption text-muted-foreground">
- {t(($) => $.wecom.byo_option_description)}
- </p>
- </div>
- </div>
- )}
-
- <div className="space-y-1.5">
- <Label htmlFor="wecom-byo-bot-id">
- {t(($) => $.wecom.byo_bot_id_label)}
- </Label>
- <Input
- id="wecom-byo-bot-id"
- data-testid="wecom-byo-bot-id"
- value={botId}
- onChange={(e) => setBotId(e.target.value)}
- placeholder={t(($) => $.wecom.byo_bot_id_placeholder)}
- autoComplete="off"
- spellCheck={false}
- disabled={submitting}
- />
- </div>
-
- <div className="space-y-1.5">
- <Label htmlFor="wecom-byo-secret">
- {t(($) => $.wecom.byo_secret_label)}
- </Label>
- <Input
- id="wecom-byo-secret"
- data-testid="wecom-byo-secret"
- type="password"
- value={secret}
- onChange={(e) => setSecret(e.target.value)}
- placeholder={t(($) => $.wecom.byo_secret_placeholder)}
- autoComplete="off"
- spellCheck={false}
- disabled={submitting}
- />
- </div>
-
- <div className="space-y-1.5">
- <Label htmlFor="wecom-byo-bot-name">
- {t(($) => $.wecom.byo_bot_name_label)}
- </Label>
- <Input
- id="wecom-byo-bot-name"
- data-testid="wecom-byo-bot-name"
- value={botName}
- onChange={(e) => setBotName(e.target.value)}
- placeholder={t(($) => $.wecom.byo_bot_name_placeholder)}
- autoComplete="off"
- spellCheck={false}
- disabled={submitting}
- />
- <p className="text-caption text-muted-foreground">
- {t(($) => $.wecom.byo_bot_name_hint)}
- </p>
- </div>
- </div>
-
- <DialogFooter>
- <Button
- variant="outline"
- size="sm"
- onClick={closeDialog}
- disabled={submitting}
- >
- {t(($) => $.wecom.byo_cancel)}
- </Button>
- <Button
- size="sm"
- onClick={handleSubmit}
- disabled={!canSubmit}
- data-testid="wecom-byo-submit"
- >
- {submitting
- ? t(($) => $.wecom.byo_submitting)
- : t(($) => $.wecom.byo_submit)}
- </Button>
- </DialogFooter>
- </DialogContent>
- </Dialog>
-
- {scanOpen && (
- <WecomScanInstallDialog
- wsId={wsId}
- agentId={agentId}
- agentName={agentName}
- onClose={() => setScanOpen(false)}
- />
- )}
- </div>
- );
-}
-
-function WecomAgentBotStatusRow({
- onClick,
- className,
-}: {
- onClick: () => void;
- className?: string;
-}) {
- const { t } = useT("settings");
- return (
- <button
- type="button"
- onClick={onClick}
- className={cn(
- "flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-caption text-muted-foreground transition-colors hover:bg-muted focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/50",
- className,
- )}
- data-testid="wecom-agent-bot-status"
- >
- <span className="inline-block h-1.5 w-1.5 shrink-0 rounded-full bg-emerald-500" />
- <span className="truncate">{t(($) => $.wecom.agent_bot_connected_label)}</span>
- <ChevronRight className="ml-auto h-3.5 w-3.5 shrink-0" />
- </button>
- );
-}
-
-function WecomAgentBotConnectedBadge({
- installation,
- className,
-}: {
- installation: WecomInstallation;
- className?: string;
-}) {
- const { t } = useT("settings");
- const wsId = useWorkspaceId();
- const qc = useQueryClient();
-
- const [confirmOpen, setConfirmOpen] = useState(false);
- const [disconnecting, setDisconnecting] = useState(false);
-
- async function handleDisconnect() {
- if (disconnecting) return;
- setDisconnecting(true);
- try {
- await api.deleteWecomInstallation(wsId, installation.id);
- await qc.invalidateQueries({ queryKey: wecomKeys.installations(wsId) });
- toast.success(t(($) => $.wecom.toast_disconnected));
- setConfirmOpen(false);
- } catch (e) {
- toast.error(
- e instanceof Error ? e.message : t(($) => $.wecom.toast_disconnect_failed),
- );
- } finally {
- setDisconnecting(false);
- }
- }
-
- return (
- <div
- className={cn("space-y-2", className)}
- data-testid="wecom-agent-bot-connected"
- >
- <div className="flex items-center justify-between gap-3">
- <span className="inline-flex min-w-0 items-center gap-2 text-caption text-muted-foreground">
- <span className="inline-block h-1.5 w-1.5 shrink-0 rounded-full bg-emerald-500" />
- <span className="truncate">
- {t(($) => $.wecom.agent_bot_connected_label_with_id, {
- botId: installation.bot_id,
- })}
- </span>
- </span>
- <TooltipHint label={t(($) => $.wecom.agent_bot_disconnect_tooltip)}>
- <Button
- variant="destructive"
- size="sm"
- onClick={() => setConfirmOpen(true)}
- disabled={disconnecting}
- aria-label={t(($) => $.wecom.disconnect)}
- data-testid="wecom-agent-bot-disconnect"
- >
- <Trash2 className="h-3 w-3" />
- {disconnecting
- ? t(($) => $.wecom.disconnecting)
- : t(($) => $.wecom.disconnect)}
- </Button>
- </TooltipHint>
- </div>
-
- <AlertDialog
- open={confirmOpen}
- onOpenChange={(v) => {
- if (!v && !disconnecting) setConfirmOpen(false);
- }}
- >
- <AlertDialogContent>
- <AlertDialogHeader>
- <AlertDialogTitle>
- {t(($) => $.wecom.disconnect_confirm_title)}
- </AlertDialogTitle>
- <AlertDialogDescription>
- {t(($) => $.wecom.disconnect_confirm_description)}
- </AlertDialogDescription>
- </AlertDialogHeader>
- <AlertDialogFooter>
- <AlertDialogCancel disabled={disconnecting}>
- {t(($) => $.wecom.disconnect_confirm_cancel)}
- </AlertDialogCancel>
- <AlertDialogAction onClick={handleDisconnect} disabled={disconnecting}>
- {disconnecting
- ? t(($) => $.wecom.disconnecting)
- : t(($) => $.wecom.disconnect)}
- </AlertDialogAction>
- </AlertDialogFooter>
- </AlertDialogContent>
- </AlertDialog>
- </div>
- );
-}
diff --git a/server/internal/handler/wecom_web.go b/server/internal/handler/wecom_web.go
index d21b0c5643..85023302fa 100644
--- a/server/internal/handler/wecom_web.go
+++ b/server/internal/handler/wecom_web.go
@@ -46,6 +46,7 @@ type WecomInstallationResponse struct {
WorkspaceID string `json:"workspace_id"`
AgentID string `json:"agent_id"`
BotID string `json:"bot_id"`
+ BotName string `json:"bot_name,omitempty"`
InstallerUserID string `json:"installer_user_id"`
Status string `json:"status"`
}
@@ -56,6 +57,7 @@ func wecomInstallationToResponse(inst wecom.Installation) WecomInstallationRespo
WorkspaceID: uuidToString(inst.WorkspaceID),
AgentID: uuidToString(inst.AgentID),
BotID: inst.BotID,
+ BotName: inst.BotDisplayName,
InstallerUserID: uuidToString(inst.InstallerUserID),
Status: string(inst.Status),
}
diff --git a/server/internal/handler/wecom_web_test.go b/server/internal/handler/wecom_web_test.go
index 48ff227e53..10fc9623ea 100644
--- a/server/internal/handler/wecom_web_test.go
+++ b/server/internal/handler/wecom_web_test.go
@@ -7,6 +7,7 @@ package handler
import (
"context"
+ "encoding/json"
"net/http"
"net/http/httptest"
"strings"
@@ -17,6 +18,30 @@ import (
"github.com/multica-ai/multica/server/internal/integrations/wecom"
)
+func TestWecomInstallationResponseIncludesDisplayNameWithoutCredentials(t *testing.T) {
+ inst := wecom.Installation{BotID: "bot-1", BotDisplayName: "Support Bot", SecretEncrypted: []byte("private-credential")}
+ response := wecomInstallationToResponse(inst)
+ if response.BotName != "Support Bot" {
+ t.Fatalf("bot name = %q, want Support Bot", response.BotName)
+ }
+ body, err := json.Marshal(response)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var fields map[string]any
+ if err := json.Unmarshal(body, &fields); err != nil {
+ t.Fatal(err)
+ }
+ if fields["bot_name"] != "Support Bot" || fields["bot_id"] != "bot-1" {
+ t.Fatalf("missing public bot identity: %s", body)
+ }
+ for _, key := range []string{"secret", "secret_encrypted", "SecretEncrypted"} {
+ if _, ok := fields[key]; ok {
+ t.Fatalf("response exposed credential field %q", key)
+ }
+ }
+}
+
// fakeRedeemer records whether the handler ever got as far as the service.
// A body the ceiling rejects must never reach it.
type fakeRedeemer struct{ calls int }