Skip to content

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

Go

feat(wecom): WeCom (企业微信) smart-bot integration via the Channel engine (MUL-5226) (#5833)

leroy-chen040bb97b0f02
diff --git a/.env.example b/.env.example
index deaa15c41d..e59d9f0486 100644
--- a/.env.example
+++ b/.env.example
@@ -171,6 +171,31 @@ GOOGLE_CLIENT_SECRET=
# Set explicitly only when your OAuth callback URL differs from local frontend.
GOOGLE_REDIRECT_URI=${FRONTEND_ORIGIN}/auth/callback
+# WeCom smart-bot ("智能机器人" / aibot) integration.
+# MULTICA_WECOM_* drives the bidirectional chat integration (users message
+# the smart bot in their WeCom client, an agent replies over the same
+# WebSocket long connection).
+#
+# MULTICA_WECOM_SECRET_KEY 32-byte base64 master key that encrypts each
+# installation's smart-bot secret at rest.
+# Empty = the wecom integration is disabled
+# and the wecom Web-UI endpoints return 503.
+# Generate with: openssl rand -base64 32
+#
+# Per-installation credentials (bot_id, secret) are NOT env vars — they
+# live in the channel_installation table. Create an installation from the
+# WeCom settings tab in the app (Settings → Integrations → WeCom), which
+# seals the smart-bot secret with MULTICA_WECOM_SECRET_KEY before storing it.
+#
+# SINGLE-REPLICA CONSTRAINT: unlike Slack/Lark (stateless HTTP outbound), the
+# WeCom smart bot's only outbound path is an in-process WebSocket long
+# connection. Agent replies and inbox pushes are delivered only by the backend
+# replica that currently holds a given bot's connection lease. If you run more
+# than one backend replica, responses produced on a replica that does not hold
+# the lease are dropped and the user sees nothing. Until cross-replica outbound
+# routing lands, run the WeCom-enabled backend as a SINGLE replica.
+MULTICA_WECOM_SECRET_KEY=
+
# S3 / CloudFront
# S3_BUCKET — bucket NAME only (e.g. "my-bucket"). Do NOT include the
# ".s3.<region>.amazonaws.com" suffix; the server builds the public URL
diff --git a/SELF_HOSTING.md b/SELF_HOSTING.md
index 8ac94ae304..960d0b5e7a 100644
--- a/SELF_HOSTING.md
+++ b/SELF_HOSTING.md
@@ -374,6 +374,8 @@ The Usage / Runtime dashboards read from a derived `task_usage_hourly` table pop
Multiple backend replicas are safe: each replica ticks every 30 seconds and tries to claim the current 5-minute UTC plan, but the unique key `(job_name, scope_kind, scope_id, plan_time)` means only one wins each plan. Inspect steady-state operation:
+> **Exception — WeCom (企业微信) smart bot must run single-replica.** Unlike Slack and Lark, whose outbound is stateless HTTP that any replica can perform, the WeCom smart bot's only outbound path is an in-process WebSocket long connection. Agent replies and inbox pushes are delivered only by the replica currently holding a given bot's connection lease. If you run more than one backend replica with WeCom enabled (`MULTICA_WECOM_SECRET_KEY` set), responses produced on a replica that does not hold the lease are silently dropped and the WeCom user sees nothing. Until cross-replica outbound routing lands, run the WeCom-enabled backend as a single replica. Everything else (including the rollup scheduler above) is multi-replica safe.
+
```sql
SELECT plan_time, status, attempt, runner_id,
error_code, error_msg, started_at, finished_at
diff --git a/apps/web/app/wecom/bind/page.tsx b/apps/web/app/wecom/bind/page.tsx
new file mode 100644
index 0000000000..295ee10e33
--- /dev/null
+++ b/apps/web/app/wecom/bind/page.tsx
@@ -0,0 +1,23 @@
+"use client";
+
+import { Suspense } from "react";
+import { useSearchParams } from "next/navigation";
+import { WecomBindPage } from "@multica/views/wecom";
+
+// /wecom/bind?token=<raw> is the smart-bot's "link your Multica account"
+// destination. Suspense wraps useSearchParams per Next.js 15's CSR-bailout
+// rule; the loading text never paints in practice because the redemption
+// page itself renders the "redeeming…" state immediately.
+function WecomBindPageContent() {
+ const searchParams = useSearchParams();
+ const token = searchParams.get("token");
+ return <WecomBindPage token={token} />;
+}
+
+export default function Page() {
+ return (
+ <Suspense fallback={null}>
+ <WecomBindPageContent />
+ </Suspense>
+ );
+}
diff --git a/docker-compose.selfhost.yml b/docker-compose.selfhost.yml
index 53306e30a0..cbe405e790 100644
--- a/docker-compose.selfhost.yml
+++ b/docker-compose.selfhost.yml
@@ -140,6 +140,12 @@ services:
MULTICA_VCS_INTEGRATION_ENABLED: ${MULTICA_VCS_INTEGRATION_ENABLED:-true}
# VCS integration at-rest encryption key for token-based providers
MULTICA_VCS_SECRET_KEY: ${MULTICA_VCS_SECRET_KEY:-}
+ # WeCom smart-bot integration. MULTICA_WECOM_SECRET_KEY is the
+ # opt-in: unset = integration disabled. It encrypts each installation's
+ # smart-bot secret at rest. The server needs it to unseal a bot's
+ # subscribe credentials at connection time, and to seal the secret when
+ # an installation is created from the WeCom settings tab.
+ MULTICA_WECOM_SECRET_KEY: ${MULTICA_WECOM_SECRET_KEY:-}
restart: unless-stopped
frontend:
diff --git a/packages/core/api/client.ts b/packages/core/api/client.ts
index a01df4008b..67eba13a58 100644
--- a/packages/core/api/client.ts
+++ b/packages/core/api/client.ts
@@ -165,6 +165,10 @@ import type {
ListDingTalkInstallationsResponse,
RegisterDingTalkBYORequest,
RedeemDingTalkBindingTokenResponse,
+ WecomInstallation,
+ ListWecomInstallationsResponse,
+ RegisterWecomBYORequest,
+ RedeemWecomBindingTokenResponse,
Squad,
SquadMember,
SquadMemberStatusListResponse,
@@ -286,6 +290,12 @@ import {
EMPTY_DINGTALK_INSTALLATION,
EMPTY_LIST_DINGTALK_INSTALLATIONS_RESPONSE,
EMPTY_REDEEM_DINGTALK_BINDING_TOKEN_RESPONSE,
+ WecomInstallationSchema,
+ ListWecomInstallationsResponseSchema,
+ RedeemWecomBindingTokenResponseSchema,
+ EMPTY_WECOM_INSTALLATION,
+ EMPTY_LIST_WECOM_INSTALLATIONS_RESPONSE,
+ EMPTY_REDEEM_WECOM_BINDING_TOKEN_RESPONSE,
EMPTY_BILLING_BALANCE,
EMPTY_BILLING_TRANSACTIONS_PAGE,
EMPTY_BILLING_BATCHES_PAGE,
@@ -3522,4 +3532,66 @@ export class ApiClient {
{ endpoint: "POST /api/dingtalk/binding/redeem" },
);
}
+ // WeCom smart-bot ("智能机器人" / aibot) integration. The bot dials a
+ // WebSocket long connection to wss://openws.work.weixin.qq.com and stays
+ // authenticated with (bot_id, secret); no public callback URL is required.
+ // These three methods drive the Settings-page BYO Connect dialog + list +
+ // disconnect only — the inbound WebSocket loop runs entirely server-side.
+ async listWecomInstallations(workspaceId: string): Promise<ListWecomInstallationsResponse> {
+ const raw = await this.fetch<unknown>(`/api/workspaces/${workspaceId}/wecom/installations`);
+ return parseWithFallback(
+ raw,
+ ListWecomInstallationsResponseSchema,
+ EMPTY_LIST_WECOM_INSTALLATIONS_RESPONSE,
+ { endpoint: "GET /api/workspaces/:id/wecom/installations" },
+ );
+ }
+
+ // registerWecomBYO performs a bring-your-own-app install: the admin pastes
+ // the bot id and long-connection secret from the WeCom admin console,
+ // and the backend seals the secret with MULTICA_WECOM_SECRET_KEY before
+ // persisting, returning the new installation.
+ async registerWecomBYO(
+ workspaceId: string,
+ agentId: string,
+ body: RegisterWecomBYORequest,
+ ): Promise<WecomInstallation> {
+ const search = new URLSearchParams({ agent_id: agentId });
+ const raw = await this.fetch<unknown>(
+ `/api/workspaces/${workspaceId}/wecom/install/byo?${search.toString()}`,
+ {
+ method: "POST",
+ body: JSON.stringify(body),
+ },
+ );
+ return parseWithFallback(raw, WecomInstallationSchema, EMPTY_WECOM_INSTALLATION, {
+ endpoint: "POST /api/workspaces/:id/wecom/install/byo",
+ });
+ }
+
+ async deleteWecomInstallation(workspaceId: string, installationId: string): Promise<void> {
+ await this.fetch(`/api/workspaces/${workspaceId}/wecom/installations/${installationId}`, {
+ method: "DELETE",
+ });
+ }
+
+ // redeemWecomBindingToken binds the WeCom aibot userid carried by the
+ // token to the logged-in Multica user. Called by the /wecom/bind redeem
+ // page after the user clicks through the "link your Multica account"
+ // prompt the bot sent in WeCom. Status codes:
+ // 410 Gone → invalid / expired / already consumed
+ // 409 Conflict → the WeCom user is already bound to a different user
+ // 403 Forbidden → the logged-in user is not a workspace member
+ async redeemWecomBindingToken(token: string): Promise<RedeemWecomBindingTokenResponse> {
+ const raw = await this.fetch<unknown>(`/api/wecom/binding/redeem`, {
+ method: "POST",
+ body: JSON.stringify({ token }),
+ });
+ return parseWithFallback(
+ raw,
+ RedeemWecomBindingTokenResponseSchema,
+ EMPTY_REDEEM_WECOM_BINDING_TOKEN_RESPONSE,
+ { endpoint: "POST /api/wecom/binding/redeem" },
+ );
+ }
}
diff --git a/packages/core/api/schemas.test.ts b/packages/core/api/schemas.test.ts
index ee7c8a1b57..01b89bbcf3 100644
--- a/packages/core/api/schemas.test.ts
+++ b/packages/core/api/schemas.test.ts
@@ -1,6 +1,12 @@
import { describe, expect, it } from "vitest";
import {
AppConfigSchema,
+ WecomInstallationSchema,
+ ListWecomInstallationsResponseSchema,
+ RedeemWecomBindingTokenResponseSchema,
+ EMPTY_WECOM_INSTALLATION,
+ EMPTY_LIST_WECOM_INSTALLATIONS_RESPONSE,
+ EMPTY_REDEEM_WECOM_BINDING_TOKEN_RESPONSE,
AgentTaskListSchema,
AutopilotRunSchema,
FALLBACK_AUTOPILOT_RUN,
@@ -1237,3 +1243,65 @@ describe("RuntimeModelListRequestSchema", () => {
);
});
});
+
+// WeCom smart-bot installation schemas. These gate UI affordances (the Connect
+// 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("parses a well-formed installation", () => {
+ const parsed = WecomInstallationSchema.parse({
+ id: "i1",
+ workspace_id: "w1",
+ agent_id: "a1",
+ bot_id: "aibot_xyz",
+ installer_user_id: "u1",
+ status: "active",
+ });
+ expect(parsed.bot_id).toBe("aibot_xyz");
+ expect(parsed.status).toBe("active");
+ });
+
+ it("defaults a missing status to 'revoked', never 'active'", () => {
+ // A broken read must not render a bot as connected when it may not be.
+ const parsed = WecomInstallationSchema.parse({ id: "i1" });
+ expect(parsed.status).toBe("revoked");
+ expect(parsed.bot_id).toBe("");
+ });
+
+ it("keeps unknown forward-compat fields (loose) instead of failing the parse", () => {
+ const parsed = WecomInstallationSchema.parse({ id: "i1", future_field: "keep" });
+ expect((parsed as unknown as { future_field?: string }).future_field).toBe("keep");
+ });
+
+ it("defaults 'configured' to false so a malformed list renders the operator state", () => {
+ const parsed = ListWecomInstallationsResponseSchema.parse({});
+ expect(parsed.configured).toBe(false);
+ expect(parsed.installations).toEqual([]);
+ });
+
+ it("falls back to the empty list when the response is not an object", () => {
+ const parsed = parseWithFallback(
+ "not json",
+ ListWecomInstallationsResponseSchema,
+ EMPTY_LIST_WECOM_INSTALLATIONS_RESPONSE,
+ { endpoint: "GET /api/workspaces/:id/wecom/installations" },
+ );
+ expect(parsed).toEqual(EMPTY_LIST_WECOM_INSTALLATIONS_RESPONSE);
+ expect(parsed.configured).toBe(false);
+ });
+
+ it("falls back on a malformed installation and redeem response", () => {
+ const inst = parseWithFallback(42, WecomInstallationSchema, EMPTY_WECOM_INSTALLATION, {
+ endpoint: "POST /api/workspaces/:id/wecom/install/byo",
+ });
+ expect(inst).toEqual(EMPTY_WECOM_INSTALLATION);
+
+ const redeem = parseWithFallback(
+ null,
+ RedeemWecomBindingTokenResponseSchema,
+ EMPTY_REDEEM_WECOM_BINDING_TOKEN_RESPONSE,
+ { endpoint: "POST /api/wecom/binding/redeem" },
+ );
+ expect(redeem).toEqual(EMPTY_REDEEM_WECOM_BINDING_TOKEN_RESPONSE);
+ });
+});
diff --git a/packages/core/api/schemas.ts b/packages/core/api/schemas.ts
index ecd6c57e12..4f261973fb 100644
--- a/packages/core/api/schemas.ts
+++ b/packages/core/api/schemas.ts
@@ -28,6 +28,9 @@ import type {
DingTalkInstallation,
ListDingTalkInstallationsResponse,
RedeemDingTalkBindingTokenResponse,
+ WecomInstallation,
+ ListWecomInstallationsResponse,
+ RedeemWecomBindingTokenResponse,
GroupedIssuesResponse,
GitHubConnectResponse,
GitHubPullRequest,
@@ -2196,3 +2199,51 @@ export const EMPTY_REDEEM_DINGTALK_BINDING_TOKEN_RESPONSE: RedeemDingTalkBinding
installation_id: "",
dingtalk_user_id: "",
};
+
+// WeCom smart-bot ("智能机器人" / aibot) installation responses. `.loose()` so a
+// newer backend field never fails the parse on an older desktop build (see
+// CLAUDE.md → API Compatibility). Defaults are chosen so a malformed response
+// degrades safely: `configured` defaults false (renders the "ask your operator"
+// state rather than a Connect dialog whose submit is guaranteed to fail), and a
+// missing `status` defaults to "revoked" rather than "active" so a broken read
+// never shows a bot as connected when it may not be.
+export const WecomInstallationSchema = z.object({
+ id: z.string(),
+ workspace_id: z.string().default(""),
+ agent_id: z.string().default(""),
+ bot_id: z.string().default(""),
+ installer_user_id: z.string().default(""),
+ status: z.string().default("revoked"),
+}).loose();
+
+export const EMPTY_WECOM_INSTALLATION: WecomInstallation = {
+ id: "",
+ workspace_id: "",
+ agent_id: "",
+ bot_id: "",
+ installer_user_id: "",
+ status: "revoked",
+};
+
+export const ListWecomInstallationsResponseSchema = z.object({
+ installations: z.array(WecomInstallationSchema).default([]),
+ configured: z.boolean().default(false),
+ install_supported: z.boolean().optional(),
+}).loose();
+
+export const EMPTY_LIST_WECOM_INSTALLATIONS_RESPONSE: ListWecomInstallationsResponse = {
+ installations: [],
+ configured: false,
+};
+
+export const RedeemWecomBindingTokenResponseSchema = z.object({
+ workspace_id: z.string().default(""),
+ installation_id: z.string().default(""),
+ wecom_user_id: z.string().default(""),
+}).loose();
+
+export const EMPTY_REDEEM_WECOM_BINDING_TOKEN_RESPONSE: RedeemWecomBindingTokenResponse = {
+ workspace_id: "",
+ installation_id: "",
+ wecom_user_id: "",
+};
diff --git a/packages/core/package.json b/packages/core/package.json
index 029e751686..ebcea46715 100644
--- a/packages/core/package.json
+++ b/packages/core/package.json
@@ -107,6 +107,8 @@
"./slack/queries": "./slack/queries.ts",
"./dingtalk": "./dingtalk/index.ts",
"./dingtalk/queries": "./dingtalk/queries.ts",
+ "./wecom": "./wecom/index.ts",
+ "./wecom/queries": "./wecom/queries.ts",
"./feedback": "./feedback/index.ts",
"./feedback/mutations": "./feedback/mutations.ts",
"./realtime": "./realtime/index.ts",
diff --git a/packages/core/realtime/use-realtime-sync.ts b/packages/core/realtime/use-realtime-sync.ts
index a134b246c3..54af3c7d3d 100644
--- a/packages/core/realtime/use-realtime-sync.ts
+++ b/packages/core/realtime/use-realtime-sync.ts
@@ -27,6 +27,7 @@ import { githubKeys } from "../github/queries";
import { larkKeys } from "../lark/queries";
import { slackKeys } from "../slack/queries";
import { dingtalkKeys } from "../dingtalk/queries";
+import { wecomKeys } from "../wecom/queries";
import {
onIssueCreated,
onIssueUpdated,
@@ -805,6 +806,10 @@ export function useRealtimeSync(
const wsId = getCurrentWsId();
if (wsId) qc.invalidateQueries({ queryKey: ["vcs", wsId] });
},
+ wecom_installation: () => {
+ const wsId = getCurrentWsId();
+ if (wsId) qc.invalidateQueries({ queryKey: wecomKeys.installations(wsId) });
+ },
pull_request: () => {
// PR list is keyed by issue id, not workspace, so we invalidate all
// PR queries — the open issue detail page will refetch its own list.
diff --git a/packages/core/types/index.ts b/packages/core/types/index.ts
index 80214a6f44..2fcd3904c3 100644
--- a/packages/core/types/index.ts
+++ b/packages/core/types/index.ts
@@ -197,6 +197,12 @@ export type {
RegisterDingTalkBYORequest,
RedeemDingTalkBindingTokenResponse,
} from "./dingtalk";
+export type {
+ WecomInstallation,
+ ListWecomInstallationsResponse,
+ RegisterWecomBYORequest,
+ RedeemWecomBindingTokenResponse,
+} from "./wecom";
export type {
Autopilot,
AutopilotStatus,
diff --git a/packages/core/types/wecom.ts b/packages/core/types/wecom.ts
new file mode 100644
index 0000000000..cf1adc86ea
--- /dev/null
+++ b/packages/core/types/wecom.ts
@@ -0,0 +1,46 @@
+/**
+ * A WeCom smart-bot ("智能机器人" / aibot) installation bound to a single
+ * Multica agent. Wire shape mirrors `WecomInstallationResponse` in
+ * `server/internal/handler/wecom_web.go`. Any new field the backend adds MUST
+ * default to optional so older desktop builds keep parsing the response — see
+ * CLAUDE.md → API Compatibility.
+ */
+export interface WecomInstallation {
+ id: string;
+ workspace_id: string;
+ agent_id: string;
+ /** The smart-bot identifier assigned by the WeCom admin console. */
+ bot_id: string;
+ installer_user_id: string;
+ status: "active" | "revoked" | string;
+}
+
+export interface ListWecomInstallationsResponse {
+ installations: WecomInstallation[];
+ /** Whether MULTICA_WECOM_SECRET_KEY is set on this deployment. When false the
+ * BYO Connect button is hidden and the panel renders an "ask the operator"
+ * state. */
+ configured: boolean;
+ /** Whether the install path is available (true whenever configured). Kept as
+ * a separate flag for parity with Slack / Lark; optional so a desktop build
+ * that predates it treats it as off. */
+ install_supported?: boolean;
+}
+
+/** Request body for the Web UI's BYO Connect dialog. Two fields, both copied
+ * from the WeCom admin console's smart-bot page: the bot's stable
+ * identifier and its long-connection secret. The backend seals the secret
+ * with the deployment's MULTICA_WECOM_SECRET_KEY before writing it, so
+ * plaintext never lands in the DB. */
+export interface RegisterWecomBYORequest {
+ bot_id: string;
+ secret: string;
+}
+
+/** Post-redemption echo: the WeCom aibot userid the token carried is now
+ * bound to the logged-in Multica user in this workspace/installation. */
+export interface RedeemWecomBindingTokenResponse {
+ workspace_id: string;
+ installation_id: string;
+ wecom_user_id: string;
+}
diff --git a/packages/core/wecom/index.ts b/packages/core/wecom/index.ts
new file mode 100644
index 0000000000..0a63611aca
--- /dev/null
+++ b/packages/core/wecom/index.ts
@@ -0,0 +1 @@
+export { wecomKeys, wecomInstallationsOptions } from "./queries";
diff --git a/packages/core/wecom/queries.ts b/packages/core/wecom/queries.ts
new file mode 100644
index 0000000000..092004d369
--- /dev/null
+++ b/packages/core/wecom/queries.ts
@@ -0,0 +1,20 @@
+import { queryOptions } from "@tanstack/react-query";
+import { api } from "../api";
+
+/**
+ * Query key namespace for everything wecom-installation-related. Realtime sync
+ * invalidates `installations(wsId)` on `wecom_installation:*` events so the
+ * Settings panel updates without a manual refetch when another tab / an admin
+ * on another machine connects or disconnects a bot.
+ */
+export const wecomKeys = {
+ all: (wsId: string) => ["wecom", wsId] as const,
+ installations: (wsId: string) => [...wecomKeys.all(wsId), "installations"] as const,
+};
+
+export const wecomInstallationsOptions = (wsId: string) =>
+ queryOptions({
+ queryKey: wecomKeys.installations(wsId),
+ queryFn: () => api.listWecomInstallations(wsId),
+ enabled: !!wsId,
+ });
diff --git a/packages/views/agents/components/agent-overview-pane.tsx b/packages/views/agents/components/agent-overview-pane.tsx
index 9da7b0a46f..42bdf765e3 100644
--- a/packages/views/agents/components/agent-overview-pane.tsx
+++ b/packages/views/agents/components/agent-overview-pane.tsx
@@ -14,6 +14,7 @@ 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 {
AlertDialog,
AlertDialogAction,
@@ -175,11 +176,16 @@ export function AgentOverviewPane({
const { data: dingtalkListing } = useQuery({
...dingtalkInstallationsOptions(wsId),
});
+ const { data: wecomListing } = useQuery({
+ ...wecomInstallationsOptions(wsId),
+ enabled: !!wsId,
+ });
const integrationsConfigured =
larkListing?.configured === true ||
slackListing?.configured === true ||
- dingtalkListing?.configured === true;
+ dingtalkListing?.configured === true ||
+ wecomListing?.configured === true;
const visibleCapabilityTabs = useMemo(() => {
const showMcp = runtime
diff --git a/packages/views/agents/components/tabs/integrations-tab.test.tsx b/packages/views/agents/components/tabs/integrations-tab.test.tsx
index d84d97e920..c660e0b75a 100644
--- a/packages/views/agents/components/tabs/integrations-tab.test.tsx
+++ b/packages/views/agents/components/tabs/integrations-tab.test.tsx
@@ -61,6 +61,13 @@ vi.mock("@multica/core/slack", () => ({
}),
}));
+vi.mock("@multica/core/wecom", () => ({
+ wecomInstallationsOptions: () => ({
+ queryKey: ["wecom", "installations"],
+ queryFn: vi.fn(),
+ }),
+}));
+
vi.mock("@multica/core/auth", () => {
const useAuthStore = Object.assign(
(sel?: (s: { user: { id: string } }) => unknown) =>
@@ -94,6 +101,14 @@ vi.mock("../../../settings/components/slack-tab", () => ({
),
}));
+// 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} />
+ ),
+}));
+
import { IntegrationsTab } from "./integrations-tab";
const TEST_RESOURCES = {
@@ -184,16 +199,17 @@ describe("IntegrationsTab", () => {
membersRef.current = [{ user_id: "user-1", role: "member" }];
renderTab(<IntegrationsTab agent={{ ...agent, owner_id: "user-2" }} />);
expect(
- screen.getByText(/Only workspace owners and admins can connect an agent/i),
- ).toBeTruthy();
+ screen.getAllByText(/Only workspace owners and admins can connect an agent/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();
});
it("lets a non-admin agent owner bind Lark but keeps Slack admin-only", () => {
// The agent's owner (user-1) is only a plain workspace member. Lark
// authorizes the agent owner (canManageAgent), so the Lark bind entry
- // renders and receives owner_id; Slack's and DingTalk's routes stay
+ // renders and receives owner_id; Slack, DingTalk and WeCom routes stay
// admin-only, so each shows the read-only note instead of a CTA (MUL-4213).
membersRef.current = [{ user_id: "user-1", role: "member" }];
renderTab(<IntegrationsTab agent={agent} />);
@@ -201,10 +217,12 @@ describe("IntegrationsTab", () => {
expect(larkButton.getAttribute("data-agent-id")).toBe("agent-1");
expect(larkButton.getAttribute("data-agent-owner-id")).toBe("user-1");
expect(screen.queryByTestId("slack-bind-button")).toBeNull();
- // The Slack and DingTalk sections each fall back to the shared members note.
+ expect(screen.queryByTestId("wecom-bind-button")).toBeNull();
+ // The Slack, DingTalk and WeCom sections each fall back to the shared
+ // members note.
expect(
screen.getAllByText(/Only workspace owners and admins can connect an agent/i),
- ).toHaveLength(2);
+ ).toHaveLength(3);
});
it("renders the bind entry (not coming-soon) when installs are unavailable but the agent is already bound", () => {
diff --git a/packages/views/agents/components/tabs/integrations-tab.tsx b/packages/views/agents/components/tabs/integrations-tab.tsx
index af849fe8ed..bce67ee7bc 100644
--- a/packages/views/agents/components/tabs/integrations-tab.tsx
+++ b/packages/views/agents/components/tabs/integrations-tab.tsx
@@ -8,10 +8,12 @@ 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 { memberListOptions } from "@multica/core/workspace/queries";
import { LarkAgentBindButton } from "../../../settings/components/lark-tab";
import { SlackAgentBindButton } from "../../../settings/components/slack-tab";
import { DingTalkAgentBindButton } from "../../../settings/components/dingtalk-tab";
+import { WecomAgentBindButton } from "../../../settings/components/wecom-tab";
import { useT } from "../../../i18n";
/**
@@ -48,6 +50,10 @@ export function IntegrationsTab({ agent }: { agent: Agent }) {
const { data: dingtalkListing } = useQuery({
...dingtalkInstallationsOptions(wsId),
});
+ const { data: wecomListing } = useQuery({
+ ...wecomInstallationsOptions(wsId),
+ enabled: !!wsId,
+ });
const { data: members = [] } = useQuery({
...memberListOptions(wsId),
enabled: !!wsId,
@@ -67,6 +73,7 @@ export function IntegrationsTab({ agent }: { agent: Agent }) {
// backend would 403.
const canManageLark = isWorkspaceAdmin || isAgentOwner;
const canManageSlack = isWorkspaceAdmin;
+ const canManageWecom = isWorkspaceAdmin;
const hasActiveInstall =
listing?.installations.some(
(inst) => inst.agent_id === agent.id && inst.status === "active",
@@ -84,11 +91,18 @@ export function IntegrationsTab({ agent }: { agent: Agent }) {
// matching Slack rather than Lark's owner-or-admin rule.
const canManageDingtalk = isWorkspaceAdmin;
+ 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;
+
// A member who can manage no platform (not a workspace admin and not this
// agent's owner) gets the read-only note instead of the sections.
// Members can still view connected bots in the (member-visible)
// Settings → Integrations listing.
- if (!canManageLark && !canManageSlack && !canManageDingtalk) {
+ if (!canManageLark && !canManageSlack && !canManageDingtalk && !canManageWecom) {
return (
<div className="space-y-6">
<p className="text-caption text-muted-foreground">
@@ -223,6 +237,40 @@ export function IntegrationsTab({ agent }: { agent: Agent }) {
)}
</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">
+ <MessagesSquare 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>
</div>
);
}
diff --git a/packages/views/locales/en/common.json b/packages/views/locales/en/common.json
index 9bce79f512..19489ca4ae 100644
--- a/packages/views/locales/en/common.json
+++ b/packages/views/locales/en/common.json
@@ -90,5 +90,20 @@
"expandable_description": {
"expand": "Show more",
"collapse": "Show less"
+ },
+ "wecom_bind": {
+ "page_title": "Link your Multica account",
+ "redeeming": "Linking your account…",
+ "needs_auth_description": "Sign in to Multica to complete the link. The token in the link binds your WeCom identity to this Multica user, so you must be logged in first.",
+ "sign_in": "Sign in",
+ "done_title": "You're linked.",
+ "done_description": "Your next message to the smart bot in WeCom will go straight to the agent. You can close this tab.",
+ "error_title": "Couldn't complete the link",
+ "error_admin_hint": "If this keeps happening, message the bot again in WeCom to get a fresh link.",
+ "error_missing_token": "The link is missing its token. Message the bot again in WeCom to get a new one.",
+ "error_expired": "This link is invalid or expired (links are valid for 15 minutes). Message the bot again to get a new one.",
+ "error_already_bound": "This WeCom identity is already linked to a different Multica user. Account transfers must go through an explicit unbind first.",
+ "error_not_member": "You're signed in to a Multica account that isn't a member of this workspace.",
+ "error_unknown": "Something went wrong. Try again, and if the problem persists, contact the workspace admin."
}
}
diff --git a/packages/views/locales/en/settings.json b/packages/views/locales/en/settings.json
index 0d4c8b74de..a698367678 100644
--- a/packages/views/locales/en/settings.json
+++ b/packages/views/locales/en/settings.json
@@ -725,6 +725,46 @@
"byo_success_toast": "DingTalk bot connected",
"byo_failed_toast": "Could not connect the DingTalk bot"
},
+ "wecom": {
+ "section_title": "WeCom",
+ "page_description": "Connect each Multica Agent to its own WeCom smart bot. Members message the bot in WeCom and the Agent replies through a long WebSocket connection — no public callback URL is required.",
+ "not_enabled_title": "WeCom integration not enabled",
+ "not_enabled_description_prefix": "Set",
+ "not_enabled_description_suffix": "on the server to enable WeCom smart-bot installations.",
+ "not_enabled_self_host_hint": "Self-hosters: see the project README for details.",
+ "preview_title": "WeCom install coming soon",
+ "preview_description": "The at-rest key is set, but this deployment has not fully enabled WeCom installs yet.",
+ "connected_bots": "Connected bots",
+ "loading": "Loading…",
+ "empty_title": "No bots connected yet",
+ "empty_description_prefix": "Open an Agent in this workspace and click",
+ "empty_description_cta": "Connect WeCom",
+ "empty_description_suffix": "to install a smart bot for it.",
+ "revoked_badge": "revoked",
+ "bot_id_label": "Bot ID: {{botId}}",
+ "disconnect": "Disconnect",
+ "disconnecting": "Disconnecting…",
+ "disconnect_confirm_title": "Disconnect this WeCom bot?",
+ "disconnect_confirm_description": "The bot will stop receiving WeCom messages for this workspace. The installation row is kept for audit; you can re-install later from the same Agent.",
+ "disconnect_confirm_cancel": "Cancel",
+ "toast_disconnected": "Disconnected WeCom bot",
+ "toast_disconnect_failed": "Disconnect failed",
+ "bind_button": "Connect WeCom",
+ "bind_button_title": "Connect {{agent}} to a WeCom smart bot",
+ "agent_bot_connected_label": "Connected to WeCom",
+ "agent_bot_connected_label_with_id": "Connected to WeCom — {{botId}}",
+ "agent_bot_disconnect_tooltip": "Unbind this smart bot from the Agent. The bot will stop receiving WeCom messages.",
+ "byo_dialog_title": "Connect a WeCom smart bot",
+ "byo_bot_id_label": "Bot ID",
+ "byo_bot_id_placeholder": "e.g. aibot_xxxxxxxxxxxxxxxx",
+ "byo_secret_label": "Long-connection secret",
+ "byo_secret_placeholder": "Paste the secret shown once in the console",
+ "byo_submit": "Connect",
+ "byo_submitting": "Connecting…",
+ "byo_cancel": "Cancel",
+ "byo_success_toast": "WeCom bot connected",
+ "byo_failed_toast": "Could not connect the WeCom bot"
+ },
"repositories": {
"section_title": "Repositories",
"description": "Git repositories associated with this workspace. Agents use these to clone and work on code.",
diff --git a/packages/views/locales/ja/common.json b/packages/views/locales/ja/common.json
index eaaa57d0d5..149a36376e 100644
--- a/packages/views/locales/ja/common.json
+++ b/packages/views/locales/ja/common.json
@@ -90,5 +90,20 @@
"expandable_description": {
"expand": "詳細を表示",
"collapse": "折りたたむ"
+ },
+ "wecom_bind": {
+ "page_title": "Multica アカウントをリンク",
+ "redeeming": "アカウントをリンク中…",
+ "needs_auth_description": "リンクを完了するには Multica にサインインしてください。トークンは WeCom の ID を、サインイン中の Multica ユーザーに紐付けます。",
+ "sign_in": "サインイン",
+ "done_title": "リンクされました。",
+ "done_description": "次回 WeCom でスマートボットに送るメッセージはそのままエージェントに届きます。このタブは閉じて構いません。",
+ "error_title": "リンクを完了できませんでした",
+ "error_admin_hint": "繰り返し失敗する場合は、WeCom でボットに再度メッセージを送って新しいリンクを取得してください。",
+ "error_missing_token": "リンクにトークンがありません。WeCom でボットに再度メッセージを送って新しいリンクを取得してください。",
+ "error_expired": "リンクが無効または期限切れです(有効期限は 15 分)。ボットに再度メッセージを送って新しいリンクを取得してください。",
+ "error_already_bound": "この WeCom ID は別の Multica ユーザーにリンクされています。アカウントの移行には明示的な解除が必要です。",
+ "error_not_member": "サインインしている Multica アカウントはこのワークスペースのメンバーではありません。",
+ "error_unknown": "問題が発生しました。もう一度試し、それでも解決しない場合はワークスペース管理者にお問い合わせください。"
}
}
diff --git a/packages/views/locales/ja/settings.json b/packages/views/locales/ja/settings.json
index e20015c106..0e8f3c7553 100644
--- a/packages/views/locales/ja/settings.json
+++ b/packages/views/locales/ja/settings.json
@@ -724,6 +724,46 @@
"byo_success_toast": "DingTalk ボットを接続しました",
"byo_failed_toast": "DingTalk ボットを接続できませんでした"
},
+ "wecom": {
+ "section_title": "WeCom",
+ "page_description": "各 Multica エージェントを専用の WeCom スマートボットに接続します。WebSocket ロングコネクションで受信するため、公開コールバック URL は不要です。",
+ "not_enabled_title": "WeCom 連携が有効化されていません",
+ "not_enabled_description_prefix": "サーバー側で",
+ "not_enabled_description_suffix": "を設定すると WeCom スマートボットのインストールが有効になります。",
+ "not_enabled_self_host_hint": "セルフホスト運用の方はプロジェクトの README を参照してください。",
+ "preview_title": "WeCom インストールは近日提供予定",
+ "preview_description": "保存時暗号化キーは設定済みですが、このデプロイでは WeCom のインストールがまだ有効になっていません。",
+ "connected_bots": "接続済みのボット",
+ "loading": "読み込み中…",
+ "empty_title": "まだボットが接続されていません",
+ "empty_description_prefix": "このワークスペースでエージェントを開き",
+ "empty_description_cta": "WeCom を接続",
+ "empty_description_suffix": "をクリックしてスマートボットをインストールします。",
+ "revoked_badge": "無効化済み",
+ "bot_id_label": "Bot ID: {{botId}}",
+ "disconnect": "接続を解除",
+ "disconnecting": "解除中…",
+ "disconnect_confirm_title": "この WeCom ボットを解除しますか?",
+ "disconnect_confirm_description": "このボットはこのワークスペースの WeCom メッセージを受け取らなくなります。監査のためレコードは保持され、同じエージェントから再インストールできます。",
+ "disconnect_confirm_cancel": "キャンセル",
+ "toast_disconnected": "WeCom ボットを解除しました",
+ "toast_disconnect_failed": "接続解除に失敗しました",
+ "bind_button": "WeCom を接続",
+ "bind_button_title": "{{agent}} を WeCom スマートボットに接続",
+ "agent_bot_connected_label": "WeCom に接続済み",
+ "agent_bot_connected_label_with_id": "WeCom に接続済み — {{botId}}",
+ "agent_bot_disconnect_tooltip": "このスマートボットをエージェントから解除します。WeCom のメッセージを受け取らなくなります。",
+ "byo_dialog_title": "WeCom スマートボットを接続",
+ "byo_bot_id_label": "Bot ID",
+ "byo_bot_id_placeholder": "例: aibot_xxxxxxxxxxxxxxxx",
+ "byo_secret_label": "ロングコネクション Secret",
+ "byo_secret_placeholder": "管理コンソールに一度だけ表示される Secret を貼り付けます",
+ "byo_submit": "接続",
+ "byo_submitting": "接続中…",
+ "byo_cancel": "キャンセル",
+ "byo_success_toast": "WeCom ボットを接続しました",
+ "byo_failed_toast": "WeCom ボットを接続できませんでした"
+ },
"repositories": {
"section_title": "リポジトリ",
"description": "このワークスペースに関連付けられた Git リポジトリです。エージェントはこれらをクローンしてコードを作業します。",
diff --git a/packages/views/locales/ko/common.json b/packages/views/locales/ko/common.json
index 5d6c52fc8c..40d32a465f 100644
--- a/packages/views/locales/ko/common.json
+++ b/packages/views/locales/ko/common.json
@@ -90,5 +90,20 @@
"expandable_description": {
"expand": "자세히 보기",
"collapse": "접기"
+ },
+ "wecom_bind": {
+ "page_title": "Multica 계정 연결",
+ "redeeming": "계정을 연결하는 중…",
+ "needs_auth_description": "연결을 완료하려면 Multica에 로그인하세요. 토큰은 WeCom 신원을 현재 로그인한 Multica 사용자에게 연결해요.",
+ "sign_in": "로그인",
+ "done_title": "연결되었어요.",
+ "done_description": "다음에 WeCom에서 스마트봇에 보내는 메시지는 바로 에이전트로 전달됩니다. 이 탭은 닫아도 됩니다.",
+ "error_title": "연결을 완료하지 못했어요",
+ "error_admin_hint": "계속 실패하면 WeCom에서 봇에 다시 메시지를 보내 새 링크를 받으세요.",
+ "error_missing_token": "링크에 토큰이 없어요. WeCom에서 봇에 다시 메시지를 보내 새 링크를 받으세요.",
+ "error_expired": "링크가 유효하지 않거나 만료되었어요(15분 이내). 봇에 다시 메시지를 보내 새 링크를 받으세요.",
+ "error_already_bound": "이 WeCom 신원은 다른 Multica 사용자에게 연결되어 있어요. 계정 이전은 명시적 해제가 필요해요.",
+ "error_not_member": "로그인한 Multica 계정이 이 워크스페이스의 멤버가 아니에요.",
+ "error_unknown": "문제가 발생했어요. 다시 시도해 보고, 계속되면 워크스페이스 관리자에게 문의하세요."
}
}
diff --git a/packages/views/locales/ko/settings.json b/packages/views/locales/ko/settings.json
index e2e1121733..b751d21587 100644
--- a/packages/views/locales/ko/settings.json
+++ b/packages/views/locales/ko/settings.json
@@ -828,5 +828,45 @@
"byo_cancel": "취소",
"byo_success_toast": "DingTalk 봇을 연결했어요",
"byo_failed_toast": "DingTalk 봇을 연결하지 못했어요"
+ },
+ "wecom": {
+ "section_title": "WeCom",
+ "page_description": "각 Multica 에이전트를 전용 WeCom 스마트봇에 연결합니다. WebSocket 롱 커넥션으로 메시지를 받으므로 공개 콜백 URL이 필요 없어요.",
+ "not_enabled_title": "WeCom 통합이 활성화되지 않았어요",
+ "not_enabled_description_prefix": "서버에서",
+ "not_enabled_description_suffix": "를 설정하면 WeCom 스마트봇 설치가 활성화돼요.",
+ "not_enabled_self_host_hint": "셀프호스팅 사용자는 프로젝트 README를 참고해 주세요.",
+ "preview_title": "WeCom 설치는 곧 제공됩니다",
+ "preview_description": "저장 시 암호화 키는 설정되어 있지만, 이 배포에서는 아직 WeCom 설치가 완전히 활성화되지 않았어요.",
+ "connected_bots": "연결된 봇",
+ "loading": "불러오는 중…",
+ "empty_title": "아직 연결된 봇이 없어요",
+ "empty_description_prefix": "이 워크스페이스에서 에이전트를 열고",
+ "empty_description_cta": "WeCom 연결",
+ "empty_description_suffix": "을 눌러 스마트봇을 설치하세요.",
+ "revoked_badge": "해지됨",
+ "bot_id_label": "Bot ID: {{botId}}",
+ "disconnect": "연결 해제",
+ "disconnecting": "해제 중…",
+ "disconnect_confirm_title": "이 WeCom 봇의 연결을 해제할까요?",
+ "disconnect_confirm_description": "봇이 이 워크스페이스의 WeCom 메시지를 더 이상 받지 않아요. 감사 기록은 유지되며 같은 에이전트에서 다시 설치할 수 있어요.",
+ "disconnect_confirm_cancel": "취소",
+ "toast_disconnected": "WeCom 봇의 연결을 해제했어요",
+ "toast_disconnect_failed": "연결 해제 실패",
+ "bind_button": "WeCom 연결",
+ "bind_button_title": "{{agent}}을(를) WeCom 스마트봇에 연결",
+ "agent_bot_connected_label": "WeCom에 연결됨",
+ "agent_bot_connected_label_with_id": "WeCom에 연결됨 — {{botId}}",
+ "agent_bot_disconnect_tooltip": "이 스마트봇을 에이전트에서 해제합니다. WeCom 메시지를 더 이상 받지 않아요.",
+ "byo_dialog_title": "WeCom 스마트봇 연결",
+ "byo_bot_id_label": "Bot ID",
+ "byo_bot_id_placeholder": "예: aibot_xxxxxxxxxxxxxxxx",
+ "byo_secret_label": "롱 커넥션 Secret",
+ "byo_secret_placeholder": "관리자 콘솔에 한 번만 표시되는 Secret을 붙여넣으세요",
+ "byo_submit": "연결",
+ "byo_submitting": "연결 중…",
+ "byo_cancel": "취소",
+ "byo_success_toast": "WeCom 봇을 연결했어요",
+ "byo_failed_toast": "WeCom 봇을 연결하지 못했어요"
}
}
diff --git a/packages/views/locales/zh-Hans/common.json b/packages/views/locales/zh-Hans/common.json
index deff351afb..716d250add 100644
--- a/packages/views/locales/zh-Hans/common.json
+++ b/packages/views/locales/zh-Hans/common.json
@@ -90,5 +90,20 @@
"expandable_description": {
"expand": "查看详情",
"collapse": "收起"
+ },
+ "wecom_bind": {
+ "page_title": "关联 Multica 账号",
+ "redeeming": "正在关联账号…",
+ "needs_auth_description": "需要登录 Multica 才能完成关联。链接中的 token 会将你在企业微信的身份绑定到当前登录的 Multica 用户。",
+ "sign_in": "登录",
+ "done_title": "已关联。",
+ "done_description": "下次在企业微信向智能机器人发送消息时,会直接送达绑定的智能体。可以关闭此页面。",
+ "error_title": "关联未完成",
+ "error_admin_hint": "如果反复失败,请在企业微信重新向机器人发消息以获取新的链接。",
+ "error_missing_token": "链接缺少 token。请在企业微信重新向机器人发消息以获取新的链接。",
+ "error_expired": "链接无效或已过期(有效期 15 分钟)。请重新向机器人发消息获取新的链接。",
+ "error_already_bound": "该企业微信身份已关联到其他 Multica 用户。账户转移需要先显式解绑。",
+ "error_not_member": "你登录的 Multica 账号不是当前工作区成员。",
+ "error_unknown": "出现未知错误。请稍后再试,如反复失败请联系工作区管理员。"
}
}
diff --git a/packages/views/locales/zh-Hans/settings.json b/packages/views/locales/zh-Hans/settings.json
index cdca6cc959..61316da3af 100644
--- a/packages/views/locales/zh-Hans/settings.json
+++ b/packages/views/locales/zh-Hans/settings.json
@@ -724,6 +724,46 @@
"byo_success_toast": "钉钉机器人已连接",
"byo_failed_toast": "无法连接钉钉机器人"
},
+ "wecom": {
+ "section_title": "企业微信",
+ "page_description": "将每个 Multica 智能体连接到专属的企业微信智能机器人。成员在企业微信中与机器人对话,Agent 通过长连接实时回复——无需公网回调地址。",
+ "not_enabled_title": "企业微信集成未启用",
+ "not_enabled_description_prefix": "在服务器上设置",
+ "not_enabled_description_suffix": "以启用企业微信智能机器人的安装。",
+ "not_enabled_self_host_hint": "自部署用户:详见项目 README。",
+ "preview_title": "企业微信安装即将上线",
+ "preview_description": "静态加密密钥已设置,但本部署尚未完成企业微信安装能力的开通。",
+ "connected_bots": "已连接的机器人",
+ "loading": "加载中…",
+ "empty_title": "尚未连接机器人",
+ "empty_description_prefix": "在本工作区打开一个 Agent,点击",
+ "empty_description_cta": "连接企业微信",
+ "empty_description_suffix": "为其安装智能机器人。",
+ "revoked_badge": "已撤销",
+ "bot_id_label": "Bot ID:{{botId}}",
+ "disconnect": "断开连接",
+ "disconnecting": "正在断开…",
+ "disconnect_confirm_title": "断开此企业微信机器人?",
+ "disconnect_confirm_description": "该机器人将停止接收此工作区的企业微信消息。安装记录会保留以备审计;你之后可以从同一个 Agent 重新安装。",
+ "disconnect_confirm_cancel": "取消",
+ "toast_disconnected": "已断开企业微信机器人",
+ "toast_disconnect_failed": "断开失败",
+ "bind_button": "连接企业微信",
+ "bind_button_title": "把 {{agent}} 连接到企业微信智能机器人",
+ "agent_bot_connected_label": "已连接到企业微信",
+ "agent_bot_connected_label_with_id": "已连接到企业微信 — {{botId}}",
+ "agent_bot_disconnect_tooltip": "将此智能机器人从 Agent 解绑。机器人将停止接收企业微信消息。",
+ "byo_dialog_title": "连接企业微信智能机器人",
+ "byo_bot_id_label": "Bot ID",
+ "byo_bot_id_placeholder": "例如:aibot_xxxxxxxxxxxxxxxx",
+ "byo_secret_label": "长连接 Secret",
+ "byo_secret_placeholder": "粘贴在管理后台仅显示一次的 Secret",
+ "byo_submit": "连接",
+ "byo_submitting": "连接中…",
+ "byo_cancel": "取消",
+ "byo_success_toast": "企业微信机器人已连接",
+ "byo_failed_toast": "无法连接企业微信机器人"
+ },
"repositories": {
"section_title": "代码仓库",
"description": "与该工作区关联的 Git 仓库。智能体会从这里 clone 代码并完成工作。",
diff --git a/packages/views/package.json b/packages/views/package.json
index 70239cb30e..00629790d7 100644
--- a/packages/views/package.json
+++ b/packages/views/package.json
@@ -45,6 +45,7 @@
"./lark": "./lark/index.ts",
"./slack": "./slack/index.ts",
"./dingtalk": "./dingtalk/index.ts",
+ "./wecom": "./wecom/index.ts",
"./invite": "./invite/index.ts",
"./invitations": "./invitations/index.ts",
"./onboarding": "./onboarding/index.ts",
diff --git a/packages/views/settings/components/integrations-tab.test.tsx b/packages/views/settings/components/integrations-tab.test.tsx
index 2e4c25d9a1..908af71833 100644
--- a/packages/views/settings/components/integrations-tab.test.tsx
+++ b/packages/views/settings/components/integrations-tab.test.tsx
@@ -52,6 +52,10 @@ vi.mock("./vcs-tab", () => ({
VCSTab: () => <div data-testid="vcs-tab" />,
}));
+vi.mock("./wecom-tab", () => ({
+ WecomTab: () => <div data-testid="wecom-tab" />,
+}));
+
import { IntegrationsTab } from "./integrations-tab";
afterEach(cleanup);
diff --git a/packages/views/settings/components/integrations-tab.tsx b/packages/views/settings/components/integrations-tab.tsx
index 2b4984c566..94cf1d0eff 100644
--- a/packages/views/settings/components/integrations-tab.tsx
+++ b/packages/views/settings/components/integrations-tab.tsx
@@ -6,6 +6,7 @@ import { ComposioTab } from "./composio-tab";
import { SlackTab } from "./slack-tab";
import { DingTalkTab } from "./dingtalk-tab";
import { VCSTab } from "./vcs-tab";
+import { WecomTab } from "./wecom-tab";
import { ApiError } from "@multica/core/api";
import { composioToolkitsOptions } from "@multica/core/composio";
import { useConfigStore, useFeatureEnabled } from "@multica/core/config";
@@ -15,18 +16,15 @@ import { SettingsSection, SettingsTab } from "./settings-layout";
// Integrations is the umbrella tab for third-party platform connections.
// GitHub has its own top-level tab (see github-tab.tsx); everything else
-// — currently Lark, Composio, Slack, and the self-hosted Git providers (Forgejo /
-// Gitea / GitLab), with Linear etc. to follow — lives in here under its own
-// section heading so additional integrations slot in without changing the IA.
-// IntegrationsTab is just the host; each integration owns its own description
-// and install flow.
+// — currently Lark, Composio, Slack, the self-hosted Git providers (Forgejo /
+// Gitea / GitLab), and WeCom smart-bot, with Linear etc. to follow —
+// lives in here under its own section heading so additional integrations slot
+// in without changing the IA. IntegrationsTab is just the host; each
+// integration owns its own description and install flow.
export function IntegrationsTab() {
const { t } = useT("settings");
const composioEnabled = useFeatureEnabled(COMPOSIO_MCP_APPS_FLAG, false);
- // Composio is hidden entirely until the feature is enabled and a key is
- // configured server-side. A 503 from the toolkits endpoint means the server
- // withheld the integration despite the frontend flag being on.
const composioToolkits = useQuery({
...composioToolkitsOptions(),
enabled: composioEnabled,
@@ -60,6 +58,9 @@ export function IntegrationsTab() {
<VCSTab />
</SettingsSection>
)}
+ <SettingsSection title={t(($) => $.wecom.section_title)}>
+ <WecomTab />
+ </SettingsSection>
</SettingsTab>
);
}
diff --git a/packages/views/settings/components/wecom-tab.test.tsx b/packages/views/settings/components/wecom-tab.test.tsx
new file mode 100644
index 0000000000..cd8afeb5b7
--- /dev/null
+++ b/packages/views/settings/components/wecom-tab.test.tsx
@@ -0,0 +1,214 @@
+// @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: [] as unknown[],
+ configured: true,
+ install_supported: true,
+ },
+}));
+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,
+ },
+}));
+
+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() },
+}));
+
+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);
+
+ 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",
+ }),
+ );
+ });
+
+ 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
new file mode 100644
index 0000000000..2cd007bd49
--- /dev/null
+++ b/packages/views/settings/components/wecom-tab.tsx
@@ -0,0 +1,532 @@
+"use client";
+
+import { useState } from "react";
+import { useQuery, useQueryClient } from "@tanstack/react-query";
+import { toast } from "sonner";
+import { ChevronRight, MessagesSquare, Trash2 } from "lucide-react";
+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 { api } from "@multica/core/api";
+import type { WecomInstallation } from "@multica/core/types";
+import { ActorAvatar } from "../../common/actor-avatar";
+import { useT } from "../../i18n";
+
+// 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">
+ <section className="space-y-1">
+ <p className="text-body text-muted-foreground">
+ {t(($) => $.wecom.page_description)}
+ </p>
+ </section>
+
+ {!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 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 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 [botId, setBotId] = useState("");
+ const [secret, setSecret] = useState("");
+ const [submitting, setSubmitting] = useState(false);
+
+ const { data: listing } = useQuery({
+ ...wecomInstallationsOptions(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 ? (
+ <WecomAgentBotStatusRow
+ onClick={onShowConnectedDetails}
+ className={className}
+ />
+ ) : (
+ <WecomAgentBotConnectedBadge installation={existing} className={className} />
+ );
+ }
+
+ if (!installSupported) return null;
+
+ function closeDialog() {
+ if (submitting) return;
+ setDialogOpen(false);
+ setBotId("");
+ setSecret("");
+ }
+
+ 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 });
+ await qc.invalidateQueries({ queryKey: wecomKeys.installations(wsId) });
+ toast.success(t(($) => $.wecom.byo_success_toast));
+ setDialogOpen(false);
+ setBotId("");
+ setSecret("");
+ } catch (e) {
+ toast.error(
+ 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"
+ >
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={() => setDialogOpen(true)}
+ disabled={!agentId}
+ title={
+ agentName
+ ? t(($) => $.wecom.bind_button_title, { agent: agentName })
+ : undefined
+ }
+ data-testid="wecom-agent-connect"
+ >
+ <MessagesSquare className="h-3 w-3" />
+ {t(($) => $.wecom.bind_button)}
+ </Button>
+
+ <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">
+ <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>
+
+ <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>
+ </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>
+ <Button
+ variant="destructive"
+ size="sm"
+ onClick={() => setConfirmOpen(true)}
+ disabled={disconnecting}
+ title={t(($) => $.wecom.agent_bot_disconnect_tooltip)}
+ 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>
+ </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/packages/views/wecom/bind-page.test.tsx b/packages/views/wecom/bind-page.test.tsx
new file mode 100644
index 0000000000..708730b9e1
--- /dev/null
+++ b/packages/views/wecom/bind-page.test.tsx
@@ -0,0 +1,114 @@
+import { describe, it, expect, vi, beforeEach } from "vitest";
+import { render, screen, waitFor, fireEvent } from "@testing-library/react";
+import type { ReactNode } from "react";
+import { I18nProvider } from "@multica/core/i18n/react";
+import enCommon from "../locales/en/common.json";
+
+// bind-page.test.tsx — the /wecom/bind redeem page. Mirrors lark/bind-page.test.tsx
+// and adds the WeCom error-code → copy mapping (410 / 409 / 403 → distinct
+// user-facing reasons), so a broken redeem never silently shows the wrong state.
+//
+// Co-authored analysis: seacen (PR #5833 review).
+
+const TEST_RESOURCES = { en: { common: enCommon } };
+
+const mockAuthState = vi.hoisted(() => ({
+ user: null as { id: string; email: string } | null,
+ isLoading: false,
+}));
+const mockNavigatePush = vi.hoisted(() => vi.fn());
+const mockRedeemToken = vi.hoisted(() => vi.fn());
+
+vi.mock("@multica/core/auth", () => {
+ const useAuthStore = Object.assign(
+ (sel?: (s: typeof mockAuthState) => unknown) => (sel ? sel(mockAuthState) : mockAuthState),
+ { getState: () => mockAuthState },
+ );
+ return { useAuthStore };
+});
+
+vi.mock("../navigation", () => ({
+ useNavigation: () => ({ push: mockNavigatePush }),
+}));
+
+vi.mock("@multica/core/api", () => ({
+ api: { redeemWecomBindingToken: mockRedeemToken },
+}));
+
+import { WecomBindPage } from "./bind-page";
+
+function I18nWrapper({ children }: { children: ReactNode }) {
+ return (
+ <I18nProvider locale="en" resources={TEST_RESOURCES}>
+ {children}
+ </I18nProvider>
+ );
+}
+
+function renderPage(token: string | null) {
+ return render(<WecomBindPage token={token} />, { wrapper: I18nWrapper });
+}
+
+describe("WecomBindPage", () => {
+ beforeEach(() => {
+ mockAuthState.user = null;
+ mockAuthState.isLoading = false;
+ mockNavigatePush.mockReset();
+ mockRedeemToken.mockReset();
+ });
+
+ it("shows the linking text while auth is still loading (not needs-auth)", () => {
+ mockAuthState.isLoading = true;
+ renderPage("tok123");
+ expect(screen.getByText(/linking your account/i)).toBeInTheDocument();
+ expect(screen.queryByRole("button", { name: /sign in/i })).toBeNull();
+ });
+
+ it("shows needs-auth UI when auth finishes loading and user is null", () => {
+ renderPage("tok123");
+ expect(screen.getByRole("button", { name: /sign in/i })).toBeInTheDocument();
+ // Must NOT have attempted a redeem without a session.
+ expect(mockRedeemToken).not.toHaveBeenCalled();
+ });
+
+ it("redeems immediately when the user is already logged in, then shows success", async () => {
+ mockAuthState.user = { id: "u1", email: "[email protected]" };
+ mockRedeemToken.mockResolvedValue({ workspace_id: "ws1", installation_id: "inst1", wecom_user_id: "T_x" });
+ renderPage("tok123");
+ await waitFor(() => expect(mockRedeemToken).toHaveBeenCalledWith("tok123"));
+ await waitFor(() => expect(screen.getByText(/you're linked/i)).toBeInTheDocument());
+ });
+
+ it("sign-in navigates with ?next= carrying the token (not ?redirect=)", () => {
+ renderPage("mytoken");
+ fireEvent.click(screen.getByRole("button", { name: /sign in/i }));
+ expect(mockNavigatePush).toHaveBeenCalledTimes(1);
+ const url = mockNavigatePush.mock.calls[0]?.[0] as string;
+ expect(url).toContain("?next=");
+ expect(url).not.toContain("?redirect=");
+ expect(url).toContain(encodeURIComponent("mytoken"));
+ });
+
+ it("shows the missing-token error when token is null (and never calls redeem)", () => {
+ renderPage(null);
+ expect(screen.getByText(/missing its token/i)).toBeInTheDocument();
+ expect(mockRedeemToken).not.toHaveBeenCalled();
+ });
+
+ // Error-code → copy mapping: the page derives the reason from the thrown
+ // error's message (status code or phrase). Each must land on distinct copy.
+ it.each([
+ ["410", /invalid or expired/i],
+ ["expired", /invalid or expired/i],
+ ["409", /already linked to a different Multica user/i],
+ ["already bound", /already linked to a different Multica user/i],
+ ["403", /isn't a member of this workspace/i],
+ ["workspace member", /isn't a member of this workspace/i],
+ ["something exploded", /something went wrong/i],
+ ])("maps a %s failure to the right message", async (msg, expected) => {
+ mockAuthState.user = { id: "u1", email: "[email protected]" };
+ mockRedeemToken.mockRejectedValue(new Error(msg));
+ renderPage("tok123");
+ await waitFor(() => expect(screen.getByText(expected)).toBeInTheDocument());
+ });
+});
diff --git a/packages/views/wecom/bind-page.tsx b/packages/views/wecom/bind-page.tsx
new file mode 100644
index 0000000000..62cfc09ca0
--- /dev/null
+++ b/packages/views/wecom/bind-page.tsx
@@ -0,0 +1,140 @@
+"use client";
+
+import { useEffect, useState } from "react";
+import { Card, CardContent } from "@multica/ui/components/ui/card";
+import { Button } from "@multica/ui/components/ui/button";
+import { api } from "@multica/core/api";
+import { useAuthStore } from "@multica/core/auth";
+import { useNavigation } from "../navigation";
+import { useT } from "../i18n";
+
+type RedeemState =
+ | { kind: "idle" }
+ | { kind: "redeeming" }
+ | { kind: "done"; workspaceId: string; installationId: string }
+ | { kind: "needs-auth" }
+ | { kind: "error"; reason: string };
+
+// WecomBindPage is the destination the WeCom smart-bot's "link your Multica
+// account" prompt points at. Same shape as SlackBindPage — the user lands
+// here logged out OR logged in; we require auth before redeeming because
+// the redeemer's Multica identity is taken from the session (the token
+// alone never proves who is binding — see wecom.BindingTokenService.
+// RedeemAndBind).
+//
+// The token comes in via ?token=<raw>. We POST it to /api/wecom/binding/
+// redeem; the backend returns 410 (invalid/expired), 409 (already bound to
+// another user), 403 (not a workspace member) or 200 with the bound
+// installation. Each maps to distinct copy via wecom_bind in common.json.
+export function WecomBindPage({ token }: { token: string | null }) {
+ const { t } = useT("common");
+ const user = useAuthStore((s) => s.user);
+ const isAuthLoading = useAuthStore((s) => s.isLoading);
+ const navigation = useNavigation();
+ const [state, setState] = useState<RedeemState>({ kind: "idle" });
+
+ useEffect(() => {
+ if (!token) {
+ setState({ kind: "error", reason: "missing_token" });
+ return;
+ }
+ if (isAuthLoading) return;
+ if (!user) {
+ setState({ kind: "needs-auth" });
+ return;
+ }
+ if (state.kind !== "idle" && state.kind !== "needs-auth") return;
+ setState({ kind: "redeeming" });
+ (async () => {
+ try {
+ const resp = await api.redeemWecomBindingToken(token);
+ setState({
+ kind: "done",
+ workspaceId: resp.workspace_id,
+ installationId: resp.installation_id,
+ });
+ } catch (e) {
+ setState({
+ kind: "error",
+ reason: redemptionFailureReason(e),
+ });
+ }
+ })();
+ }, [token, user, isAuthLoading, state.kind]);
+
+ return (
+ <div className="mx-auto flex min-h-screen max-w-md flex-col items-center justify-center p-6">
+ <Card className="w-full">
+ <CardContent className="space-y-4">
+ <h1 className="text-title font-semibold">{t(($) => $.wecom_bind.page_title)}</h1>
+ {state.kind === "idle" || state.kind === "redeeming" ? (
+ <p className="text-body text-muted-foreground">{t(($) => $.wecom_bind.redeeming)}</p>
+ ) : state.kind === "needs-auth" ? (
+ <>
+ <p className="text-body text-muted-foreground">
+ {t(($) => $.wecom_bind.needs_auth_description)}
+ </p>
+ <Button
+ size="sm"
+ onClick={() =>
+ navigation.push(
+ `/login?next=${encodeURIComponent(
+ `/wecom/bind?token=${encodeURIComponent(token ?? "")}`,
+ )}`,
+ )
+ }
+ >
+ {t(($) => $.wecom_bind.sign_in)}
+ </Button>
+ </>
+ ) : state.kind === "done" ? (
+ <>
+ <p className="text-body font-medium">{t(($) => $.wecom_bind.done_title)}</p>
+ <p className="text-caption text-muted-foreground">
+ {t(($) => $.wecom_bind.done_description)}
+ </p>
+ </>
+ ) : (
+ <>
+ <p className="text-body font-medium">{t(($) => $.wecom_bind.error_title)}</p>
+ <p className="text-caption text-muted-foreground">
+ {(() => {
+ switch (state.reason) {
+ case "missing_token":
+ return t(($) => $.wecom_bind.error_missing_token);
+ case "expired":
+ return t(($) => $.wecom_bind.error_expired);
+ case "already_bound":
+ return t(($) => $.wecom_bind.error_already_bound);
+ case "not_member":
+ return t(($) => $.wecom_bind.error_not_member);
+ default:
+ return t(($) => $.wecom_bind.error_unknown);
+ }
+ })()}
+ </p>
+ <p className="text-micro text-muted-foreground">
+ {t(($) => $.wecom_bind.error_admin_hint)}
+ </p>
+ </>
+ )}
+ </CardContent>
+ </Card>
+ </div>
+ );
+}
+
+function redemptionFailureReason(err: unknown): string {
+ const msg = err instanceof Error ? err.message : "";
+ const lower = msg.toLowerCase();
+ if (lower.includes("invalid") || lower.includes("expired") || lower.includes("410")) {
+ return "expired";
+ }
+ if (lower.includes("already bound") || lower.includes("409")) {
+ return "already_bound";
+ }
+ if (lower.includes("workspace member") || lower.includes("403")) {
+ return "not_member";
+ }
+ return "unknown";
+}
diff --git a/packages/views/wecom/index.ts b/packages/views/wecom/index.ts
new file mode 100644
index 0000000000..1389fa20b0
--- /dev/null
+++ b/packages/views/wecom/index.ts
@@ -0,0 +1 @@
+export { WecomBindPage } from "./bind-page";
diff --git a/server/cmd/server/router.go b/server/cmd/server/router.go
index 9bd503a936..829cd0e63a 100644
--- a/server/cmd/server/router.go
+++ b/server/cmd/server/router.go
@@ -30,6 +30,7 @@ import (
"github.com/multica-ai/multica/server/internal/integrations/dingtalk"
"github.com/multica-ai/multica/server/internal/integrations/lark"
"github.com/multica-ai/multica/server/internal/integrations/slack"
+ "github.com/multica-ai/multica/server/internal/integrations/wecom"
obsmetrics "github.com/multica-ai/multica/server/internal/metrics"
"github.com/multica-ai/multica/server/internal/middleware"
"github.com/multica-ai/multica/server/internal/realtime"
@@ -634,6 +635,98 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus
slog.Info("dingtalk integration disabled (MULTICA_DINGTALK_SECRET_KEY not set)")
}
+ // WeCom smart-bot integration ("智能机器人" / aibot). Per-installation
+ // WebSocket long connection to wss://openws.work.weixin.qq.com; the
+ // Supervisor drives one connection per active wecom installation, gated
+ // by the shared ws_lease_token so multi-replica deployments still hold
+ // at most one active socket per bot (WeCom itself only permits one).
+ //
+ // Gated by MULTICA_WECOM_SECRET_KEY. Without it, the whole block is
+ // skipped and the wecom Web-UI endpoints return 503; existing deployments
+ // are unaffected. The smart-bot flow does NOT require any public HTTP
+ // callback, so nothing else needs to be exposed to the internet.
+ if wecomKey, err := secretbox.LoadKey("MULTICA_WECOM_SECRET_KEY"); err == nil {
+ box, err := secretbox.New(wecomKey)
+ if err != nil {
+ slog.Error("wecom: secretbox.New failed; wecom integration disabled", "error", err)
+ } else {
+ credsResolver, err := wecom.NewSecretboxCredentialsResolver(box)
+ if err != nil {
+ slog.Error("wecom: credentials resolver init failed; wecom integration disabled", "error", err)
+ } else {
+ wecomStore := wecom.NewStore(queries)
+ h.WecomStore = wecomStore
+ h.WecomCredentials = credsResolver
+
+ // Binding tokens back the per-user "link your Multica account"
+ // prompt sent to first-time WeCom senders. aibot userids are
+ // anonymized T-prefixed ids with no relation to real userids
+ // or emails, so an explicit binding table is the only correct
+ // answer — see wecom/binding.go for the rationale.
+ wecomBinding := wecom.NewBindingTokenService(queries, pool)
+ h.WecomBindingTokens = wecomBinding
+
+ // Senders registry: the wecom OutboundReplier is created here
+ // at boot, but the live wsSender it needs to push
+ // aibot_send_msg only exists inside a running wecomChannel.
+ // wecom.NewSendersRegistry mints a shared map; the
+ // ChannelDeps write side and the Replier read side both
+ // receive it, and each Channel.Connect self-registers on
+ // entry and clears on exit.
+ wecomSenders := wecom.NewSendersRegistry()
+
+ wecomReplier := wecom.NewOutboundReplier(wecom.OutboundReplierConfig{
+ Binding: wecomBinding,
+ Senders: wecomSenders,
+ AppURL: appURLFromEnv(),
+ Logger: slog.Default(),
+ })
+
+ // Wecom shares the engine.ChatSession (channel_type-keyed) so
+ // /issue, dedup, and run-triggering behave identically across
+ // platforms. Session titles use the wecom-flavored wording
+ // (Chinese product voice — wecom deployments are China-only).
+ wecomSession := engine.NewChatSession(queries, pool, wecom.TypeWecom, engine.SessionTitles{
+ Group: "企业微信群聊",
+ Direct: "企业微信单聊",
+ Fallback: "企业微信会话",
+ })
+
+ wecom.RegisterWecom(channelRegistry, wecom.ChannelDeps{
+ Credentials: credsResolver,
+ Senders: wecomSenders,
+ Logger: slog.Default(),
+ })
+ channelRouter.Register(wecom.TypeWecom, wecom.NewResolverSet(
+ wecomStore, wecomSession, wecomReplier,
+ ))
+
+ // EventChatDone subscriber: pushes the agent's chat reply
+ // back over the same aibot WebSocket the inbound loop owns.
+ // Mirrors slack.NewOutbound(...).Register(bus). Without it
+ // the agent's reply lands only in Multica's web UI — the
+ // user in WeCom sees no response.
+ wecom.NewOutbound(queries, wecomSenders, slog.Default()).Register(bus)
+
+ slog.Info("wecom integration enabled (smart bot, long connection)")
+ // SINGLE-REPLICA CONSTRAINT: WeCom outbound (agent replies +
+ // inbox pushes) is delivered only by the replica holding each
+ // bot's in-process WebSocket lease. On a multi-replica
+ // deployment, an EventChatDone/EventInboxNew published on another
+ // replica cannot reach the lease holder, so those replies are
+ // dropped. This is stated conditionally rather than gated on a
+ // replica-count signal: the server has no reliable count here,
+ // and REDIS_URL means "Redis configured" (it also gates rate
+ // limiting), not "more than one replica". See wecom/outbound.go
+ // and SELF_HOSTING.md. Remove once outbound routes to the lease
+ // holder.
+ slog.Warn("wecom integration: WeCom agent replies and inbox pushes are delivered only by the replica holding each bot's WebSocket lease. If you run more than one backend replica, responses produced on a replica that does not hold the lease will be dropped — run the WeCom-enabled backend as a single replica until cross-replica outbound routing is implemented.")
+ }
+ }
+ } else {
+ slog.Info("wecom integration disabled (MULTICA_WECOM_SECRET_KEY not set)")
+ }
+
// Composio integration (MUL-3720). Gated by COMPOSIO_API_KEY plus the
// composio_mcp_apps feature flag. The env var is the project-scoped key the
// standalone SDK authenticates Composio with (sent as x-api-key; the project
@@ -1074,11 +1167,14 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus
r.Group(func(r chi.Router) {
r.Use(middleware.RequireWorkspaceMemberFromURL(queries, "id"))
r.Get("/slack/installations", h.ListSlackInstallations)
+ r.Get("/wecom/installations", h.ListWecomInstallations)
})
r.Group(func(r chi.Router) {
r.Use(middleware.RequireWorkspaceRoleFromURL(queries, "id", "owner", "admin"))
r.Delete("/slack/installations/{installationId}", h.RevokeSlackInstallation)
r.Post("/slack/install/byo", h.RegisterSlackBYO)
+ r.Delete("/wecom/installations/{installationId}", h.RevokeWecomInstallation)
+ r.Post("/wecom/install/byo", h.RegisterWecomBYO)
})
r.Group(func(r chi.Router) {
@@ -1109,6 +1205,10 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus
// DingTalk binding redemption is user-scoped for the same reason as
// Slack: the token is redeemed before workspace context is selected.
r.Post("/api/dingtalk/binding/redeem", h.RedeemDingTalkBindingToken)
+ // WeCom smart-bot binding-token redemption. Same rationale as
+ // Lark/Slack: the session is the source of truth for the redeemer's
+ // Multica identity; the token only carries the WeCom userid to bind.
+ r.Post("/api/wecom/binding/redeem", h.RedeemWecomBindingToken)
// Composio integration (MUL-3720). User-scoped (no workspace context):
// a connection belongs to a user. These four require a logged-in
diff --git a/server/internal/handler/handler.go b/server/internal/handler/handler.go
index 761e212a27..aa78434245 100644
--- a/server/internal/handler/handler.go
+++ b/server/internal/handler/handler.go
@@ -29,6 +29,7 @@ import (
"github.com/multica-ai/multica/server/internal/integrations/ghsnapshot"
"github.com/multica-ai/multica/server/internal/integrations/lark"
"github.com/multica-ai/multica/server/internal/integrations/slack"
+ "github.com/multica-ai/multica/server/internal/integrations/wecom"
obsmetrics "github.com/multica-ai/multica/server/internal/metrics"
"github.com/multica-ai/multica/server/internal/middleware"
"github.com/multica-ai/multica/server/internal/realtime"
@@ -265,6 +266,20 @@ type Handler struct {
// unless Slack is configured; GetChatChannelHistory then reports "no channel
// integration". A future platform satisfies the same reader interface.
SlackHistory ChatChannelHistoryReader
+ // WecomStore is the read/write handle over channel_installation rows scoped
+ // to channel_type='wecom'. Nil disables the wecom Web-UI endpoints (they
+ // return 503) and prevents boot from wiring the smart-bot supervisor.
+ WecomStore *wecom.Store
+ // WecomCredentials unseals a wecom installation's smart-bot secret for the
+ // WebSocket subscribe frame. Nil disables the wecom integration.
+ WecomCredentials wecom.CredentialsResolver
+ // WecomBindingTokens mints/redeems the user-binding tokens behind the
+ // "link your Multica account" prompt sent to first-time WeCom users
+ // (their aibot userid is a "T"-prefixed anonymized id with no relation
+ // to their real userid or email, so an explicit binding is required —
+ // see wecom/binding.go). Nil disables the redeem endpoint (returns 503)
+ // and the OutboundReplier's binding-prompt path.
+ WecomBindingTokens *wecom.BindingTokenService
// LLM is the basic LLM API layer (MUL-4238): a thin wrapper over the
// OpenAI Go SDK backing server-internal one-shot LLM helpers such as chat
// title generation. The generic passthrough endpoints were removed in
diff --git a/server/internal/handler/wecom_web.go b/server/internal/handler/wecom_web.go
new file mode 100644
index 0000000000..f11e8541e3
--- /dev/null
+++ b/server/internal/handler/wecom_web.go
@@ -0,0 +1,313 @@
+package handler
+
+// wecom_web.go — the Web-UI-facing management endpoints for the WeCom
+// smart-bot ("智能机器人" / aibot) integration. Parallel of slack.go: it
+// exposes list / install / revoke over JSON so the Settings page and per-
+// agent Integrations tab can drive wecom.InstallationService.Upsert /
+// Revoke. There is no callback surface — the smart-bot is a client-initiated
+// WebSocket long connection, so a public callback URL is not required.
+
+import (
+ "encoding/json"
+ "errors"
+ "log/slog"
+ "net/http"
+ "strings"
+
+ "github.com/go-chi/chi/v5"
+
+ "github.com/multica-ai/multica/server/internal/integrations/wecom"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+ "github.com/multica-ai/multica/server/pkg/protocol"
+)
+
+// WecomInstallationResponse is the wire shape for a wecom installation
+// row. The secret is NEVER included — it remains sealed on the row. BotID
+// is surfaced because operators need to see which bot is bound.
+type WecomInstallationResponse struct {
+ ID string `json:"id"`
+ WorkspaceID string `json:"workspace_id"`
+ AgentID string `json:"agent_id"`
+ BotID string `json:"bot_id"`
+ InstallerUserID string `json:"installer_user_id"`
+ Status string `json:"status"`
+}
+
+func wecomInstallationToResponse(inst wecom.Installation) WecomInstallationResponse {
+ return WecomInstallationResponse{
+ ID: uuidToString(inst.ID),
+ WorkspaceID: uuidToString(inst.WorkspaceID),
+ AgentID: uuidToString(inst.AgentID),
+ BotID: inst.BotID,
+ InstallerUserID: uuidToString(inst.InstallerUserID),
+ Status: string(inst.Status),
+ }
+}
+
+// wecomIntegrationConfigured reports whether the wecom integration is
+// wired on this deployment. Both surfaces (list + register) short-circuit
+// on it: list degrades to an empty response, register returns 503.
+func (h *Handler) wecomIntegrationConfigured() bool {
+ return h.WecomStore != nil && h.WecomCredentials != nil && h.ChannelRouter != nil
+}
+
+// ListWecomInstallations (GET /api/workspaces/{id}/wecom/installations) is
+// member-visible so the Integrations tab renders for non-admins. Same
+// response envelope Slack / Lark use.
+func (h *Handler) ListWecomInstallations(w http.ResponseWriter, r *http.Request) {
+ if !h.wecomIntegrationConfigured() {
+ writeJSON(w, http.StatusOK, map[string]any{
+ "installations": []WecomInstallationResponse{},
+ "configured": false,
+ "install_supported": false,
+ })
+ return
+ }
+ wsUUID, ok := parseUUIDOrBadRequest(w, chi.URLParam(r, "id"), "workspace id")
+ if !ok {
+ return
+ }
+ svc := h.wecomInstallService()
+ if svc == nil {
+ writeError(w, http.StatusServiceUnavailable, "wecom integration not enabled")
+ return
+ }
+ rows, err := svc.ListByWorkspace(r.Context(), wsUUID)
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to list wecom installations")
+ return
+ }
+ out := make([]WecomInstallationResponse, 0, len(rows))
+ for _, row := range rows {
+ out = append(out, wecomInstallationToResponse(row))
+ }
+ writeJSON(w, http.StatusOK, map[string]any{
+ "installations": out,
+ "configured": true,
+ "install_supported": true,
+ })
+}
+
+// RegisterWecomBYORequest is the body an admin submits from the Web UI's
+// BYO dialog. Two fields: the bot's stable identifier (BotID) and its
+// long-connection secret. The secret is written straight through the
+// secretbox so plaintext never lives on this file's stack past the
+// wecom.InstallationService.Upsert call.
+type RegisterWecomBYORequest struct {
+ BotID string `json:"bot_id"`
+ Secret string `json:"secret"`
+}
+
+// RegisterWecomBYO (POST /api/workspaces/{id}/wecom/install/byo?agent_id=…)
+// installs a user-supplied ("bring your own") wecom smart-bot for an agent.
+// Admin-only at the router.
+func (h *Handler) RegisterWecomBYO(w http.ResponseWriter, r *http.Request) {
+ if !h.wecomIntegrationConfigured() {
+ writeError(w, http.StatusServiceUnavailable, "wecom integration not enabled")
+ return
+ }
+ svc := h.wecomInstallService()
+ if svc == nil {
+ writeError(w, http.StatusServiceUnavailable, "wecom integration not enabled")
+ return
+ }
+ userID, ok := requireUserID(w, r)
+ if !ok {
+ return
+ }
+ wsUUID, ok := parseUUIDOrBadRequest(w, chi.URLParam(r, "id"), "workspace id")
+ if !ok {
+ return
+ }
+ agentIDStr := strings.TrimSpace(r.URL.Query().Get("agent_id"))
+ if agentIDStr == "" {
+ writeError(w, http.StatusBadRequest, "agent_id is required")
+ return
+ }
+ agentUUID, ok := parseUUIDOrBadRequest(w, agentIDStr, "agent_id")
+ if !ok {
+ return
+ }
+ if _, err := h.Queries.GetAgentInWorkspace(r.Context(), db.GetAgentInWorkspaceParams{
+ ID: agentUUID,
+ WorkspaceID: wsUUID,
+ }); err != nil {
+ writeError(w, http.StatusNotFound, "agent not found in this workspace")
+ return
+ }
+ initiatorUUID, ok := parseUUIDOrBadRequest(w, userID, "user id")
+ if !ok {
+ return
+ }
+ var body RegisterWecomBYORequest
+ if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
+ writeError(w, http.StatusBadRequest, "invalid request body")
+ return
+ }
+ inst, err := svc.Upsert(r.Context(), wecom.InstallationParams{
+ WorkspaceID: wsUUID,
+ AgentID: agentUUID,
+ InstallerUserID: initiatorUUID,
+ BotID: strings.TrimSpace(body.BotID),
+ Secret: strings.TrimSpace(body.Secret),
+ })
+ if err != nil {
+ // One bot is one live long connection, so the (wecom, bot_id) slot has
+ // exactly one owner. Upsert conflicts on
+ // (workspace_id, agent_id, channel_type), which means connecting an
+ // already-connected bot to a SECOND agent misses ON CONFLICT and trips
+ // idx_channel_installation_type_appid instead. Each sentinel gets the
+ // sentence that tells the admin where the bot actually is; returning
+ // err.Error() here used to toast them the raw "duplicate key value
+ // violates unique constraint" text — and forwarded every other database
+ // error verbatim to the API caller besides.
+ switch {
+ case errors.Is(err, wecom.ErrBotOwnedBySameWorkspace):
+ writeError(w, http.StatusConflict, "this bot is already connected to another agent in this workspace — disconnect it there first, then connect it here")
+ case errors.Is(err, wecom.ErrBotOwnedByArchivedAgent):
+ writeError(w, http.StatusConflict, "this bot is connected to an archived agent in this workspace — restore that agent, or disconnect its bot, before connecting it here")
+ case errors.Is(err, wecom.ErrBotOwnedByAnotherWorkspace):
+ writeError(w, http.StatusConflict, "this bot is already connected to a different Multica workspace — disconnect it there before connecting it here")
+ default:
+ slog.Warn("wecom install failed",
+ "error", err, "workspace_id", uuidToString(wsUUID), "agent_id", uuidToString(agentUUID))
+ writeError(w, http.StatusBadRequest, "could not connect the WeCom bot — check the Bot ID and secret from the WeCom admin console, and that the bot is a smart bot with the long connection enabled")
+ }
+ return
+ }
+ h.publish(protocol.EventWecomInstallationCreated, uuidToString(inst.WorkspaceID), "user", userID, map[string]any{
+ "id": uuidToString(inst.ID),
+ })
+ writeJSON(w, http.StatusOK, wecomInstallationToResponse(inst))
+}
+
+// RevokeWecomInstallation (DELETE /api/workspaces/{id}/wecom/installations/{installationId})
+// flips status to 'revoked'. Admin-only at the router. Row-preserving so a
+// re-install through Upsert flips it back to 'active' atomically.
+func (h *Handler) RevokeWecomInstallation(w http.ResponseWriter, r *http.Request) {
+ if !h.wecomIntegrationConfigured() {
+ writeError(w, http.StatusServiceUnavailable, "wecom integration not enabled")
+ return
+ }
+ svc := h.wecomInstallService()
+ if svc == nil {
+ writeError(w, http.StatusServiceUnavailable, "wecom integration not enabled")
+ return
+ }
+ userID, ok := requireUserID(w, r)
+ if !ok {
+ return
+ }
+ wsUUID, ok := parseUUIDOrBadRequest(w, chi.URLParam(r, "id"), "workspace id")
+ if !ok {
+ return
+ }
+ instUUID, ok := parseUUIDOrBadRequest(w, chi.URLParam(r, "installationId"), "installation id")
+ if !ok {
+ return
+ }
+ if _, err := svc.GetInWorkspace(r.Context(), instUUID, wsUUID); err != nil {
+ if errors.Is(err, wecom.ErrInstallationNotFound) {
+ writeError(w, http.StatusNotFound, "wecom installation not found")
+ return
+ }
+ writeError(w, http.StatusInternalServerError, "failed to load installation")
+ return
+ }
+ if err := svc.Revoke(r.Context(), instUUID); err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to revoke installation")
+ return
+ }
+ h.publish(protocol.EventWecomInstallationRevoked, uuidToString(wsUUID), "user", userID, map[string]any{
+ "id": uuidToString(instUUID),
+ })
+ w.WriteHeader(http.StatusNoContent)
+}
+
+// wecomInstallService builds an InstallationService on demand from the
+// pieces the handler was wired with. It is cheap (a struct wrap over
+// *db.Queries + the shared secretbox.Box behind the CredentialsResolver),
+// and this lazy pattern avoids adding a fourth wecom field on the Handler
+// struct just for the Web-UI path.
+//
+// SecretboxCredentialsResolver is the only production implementation of
+// wecom.CredentialsResolver, so a type-assert is safe. If a test supplies
+// a fake resolver, the assert falls through and both endpoints report 503,
+// which is exactly the "no encryption key wired" behaviour we want.
+func (h *Handler) wecomInstallService() *wecom.InstallationService {
+ res, ok := h.WecomCredentials.(*wecom.SecretboxCredentialsResolver)
+ if !ok || res == nil || res.Box == nil {
+ return nil
+ }
+ svc, err := wecom.NewInstallationService(h.Queries, h.TxStarter, res.Box)
+ if err != nil {
+ return nil
+ }
+ return svc
+}
+
+// RedeemWecomBindingTokenRequest carries the raw token the user clicked
+// through from the bot's "link your Multica account" prompt.
+type RedeemWecomBindingTokenRequest struct {
+ Token string `json:"token"`
+}
+
+// RedeemWecomBindingTokenResponse echoes the bound workspace / installation
+// / wecom user so the frontend can confirm without a second fetch.
+type RedeemWecomBindingTokenResponse struct {
+ WorkspaceID string `json:"workspace_id"`
+ InstallationID string `json:"installation_id"`
+ WecomUserID string `json:"wecom_user_id"`
+}
+
+// RedeemWecomBindingToken (POST /api/wecom/binding/redeem) binds the WeCom
+// aibot userid carried by the token to the logged-in Multica user. The
+// redeemer's identity comes from the session, not the token, so a stolen
+// token cannot bind a WeCom id to an attacker's account. Failure modes map
+// to distinct status codes:
+//
+// - 410 Gone: token unknown / consumed / expired
+// - 409 Conflict: this WeCom id is already bound to a different user
+// - 403 Forbidden: redeemer is not a workspace member
+func (h *Handler) RedeemWecomBindingToken(w http.ResponseWriter, r *http.Request) {
+ if h.WecomBindingTokens == nil {
+ writeError(w, http.StatusServiceUnavailable, "wecom integration not configured")
+ return
+ }
+ userID, ok := requireUserID(w, r)
+ if !ok {
+ return
+ }
+ var req RedeemWecomBindingTokenRequest
+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
+ writeError(w, http.StatusBadRequest, "invalid request body")
+ return
+ }
+ if req.Token == "" {
+ writeError(w, http.StatusBadRequest, "token is required")
+ return
+ }
+ userUUID, ok := parseUUIDOrBadRequest(w, userID, "user id")
+ if !ok {
+ return
+ }
+ redeemed, err := h.WecomBindingTokens.RedeemAndBind(r.Context(), req.Token, userUUID)
+ if err != nil {
+ switch {
+ case errors.Is(err, wecom.ErrBindingTokenInvalid):
+ writeError(w, http.StatusGone, "binding token invalid or expired")
+ case errors.Is(err, wecom.ErrBindingAlreadyAssigned):
+ writeError(w, http.StatusConflict, "this WeCom user is already bound to a different Multica user")
+ case errors.Is(err, wecom.ErrBindingNotWorkspaceMember):
+ writeError(w, http.StatusForbidden, "binding refused (are you a workspace member?)")
+ default:
+ writeError(w, http.StatusInternalServerError, "failed to redeem token")
+ }
+ return
+ }
+ writeJSON(w, http.StatusOK, RedeemWecomBindingTokenResponse{
+ WorkspaceID: uuidToString(redeemed.WorkspaceID),
+ InstallationID: uuidToString(redeemed.InstallationID),
+ WecomUserID: redeemed.WecomUserID,
+ })
+}
diff --git a/server/internal/integrations/channel/channel.go b/server/internal/integrations/channel/channel.go
index 8fcc62dc24..70c3d0f8bd 100644
--- a/server/internal/integrations/channel/channel.go
+++ b/server/internal/integrations/channel/channel.go
@@ -3,6 +3,8 @@ package channel
import (
"context"
"encoding/json"
+
+ "github.com/jackc/pgx/v5/pgtype"
)
// Type identifies an inbound channel platform — the discriminator the
@@ -84,6 +86,14 @@ type Config struct {
Type Type
Raw json.RawMessage
+ // ID is the channel_installation.id row this Channel is being built
+ // from. Zero when a build path doesn't have an installation (nothing
+ // in-tree does today, but Factory implementations should tolerate it
+ // rather than assume Valid). WeCom uses it to key its per-connection
+ // wsSender into a shared registry the OutboundReplier looks up by;
+ // Feishu and Slack don't currently read it.
+ ID pgtype.UUID
+
// Handler is the shared inbound entry point the engine injects so the
// built Channel can deliver normalized InboundMessage values into the
// core (see InboundHandler). A Factory captures it and invokes it from
diff --git a/server/internal/integrations/channel/engine/router.go b/server/internal/integrations/channel/engine/router.go
index 2093642f07..0e2f1fdbc9 100644
--- a/server/internal/integrations/channel/engine/router.go
+++ b/server/internal/integrations/channel/engine/router.go
@@ -458,8 +458,18 @@ func (r *Router) processClaimed(ctx context.Context, set ResolverSet, msg channe
// THIS message's sender (the task initiator), deliberately not the
// session creator (group sessions are creator=installer). Latest sender
// in a window wins (MUL-2645).
- r.scheduleRun(set, inst, msg, sessionID, identity.UserID)
- res.runScheduled = true
+ //
+ // SkipAgentRun lets an adapter opt this message out of the agent turn —
+ // used by wecom for standalone /issue commands where the engine has
+ // already done the meaningful work (created the issue, sent the
+ // "✅ Created #N" reply via OutboundReplier) and an agent reply would
+ // just quote the slash command back. The chat_message is still durable
+ // and the OutboundReplier still fires — only the debounced run trigger
+ // (and therefore the typing indicator) is suppressed.
+ if !msg.SkipAgentRun {
+ r.scheduleRun(set, inst, msg, sessionID, identity.UserID)
+ res.runScheduled = true
+ }
if resolveMedia {
r.enqueueMedia(set, inst, identity, appendRes.MessageID, msg, sessionID, mediaIssue, deferredIssueTaskID, localMediaDeadline)
}
diff --git a/server/internal/integrations/channel/engine/supervisor.go b/server/internal/integrations/channel/engine/supervisor.go
index d9e04be4ed..e5fe9092b3 100644
--- a/server/internal/integrations/channel/engine/supervisor.go
+++ b/server/internal/integrations/channel/engine/supervisor.go
@@ -481,6 +481,7 @@ func (s *Supervisor) supervise(ctx context.Context, inst Installation, id string
// run it under a child context, and renew the lease in parallel.
ch, err := s.registry.Build(channel.Config{
Type: inst.ChannelType,
+ ID: inst.ID,
Raw: inst.Config,
Handler: s.handler,
})
diff --git a/server/internal/integrations/channel/message.go b/server/internal/integrations/channel/message.go
index 17c1efb2b4..98cddfd16b 100644
--- a/server/internal/integrations/channel/message.go
+++ b/server/internal/integrations/channel/message.go
@@ -162,6 +162,17 @@ type InboundMessage struct {
// command; adapters may also set this flag for a native platform affordance.
ForceFresh bool
+ // SkipAgentRun asks the core to persist this message + create any
+ // engine-side artefacts (issue from /issue command, session binding
+ // row) but NOT to trigger an agent run afterwards. Set by an adapter
+ // when the message is a pure control command whose only meaningful
+ // effect is the artefact (wecom uses it for standalone /issue
+ // invocations, where an agent reply would just quote the command back
+ // as "I don't know this slash command"). Left unset by adapters where
+ // the current cross-platform behaviour — /issue triggers the agent as
+ // a normal chat turn — should be preserved (Feishu, Slack today).
+ SkipAgentRun bool
+
// Raw is the untouched platform payload. Adapters stash platform-
// specific fields here (Lark raw msg_type / parent_id / root_id /
// mention arrays, …) and read them back only inside the adapter. The
diff --git a/server/internal/integrations/wecom/binding.go b/server/internal/integrations/wecom/binding.go
new file mode 100644
index 0000000000..e7ed948085
--- /dev/null
+++ b/server/internal/integrations/wecom/binding.go
@@ -0,0 +1,183 @@
+package wecom
+
+// binding.go — the WeCom smart-bot user-binding token flow. An unbound WeCom
+// user who messages the bot gets a "link your account" prompt (minted here,
+// delivered by the OutboundReplier), clicks through to the in-product redeem
+// page, and their WeCom userid is bound to their Multica account. Mirrors
+// slack.BindingTokenService — runs on the generic channel_binding_token /
+// channel_user_binding tables with channel_type='wecom'.
+//
+// Why we need this: aibot smart-bot events carry an anonymized userid
+// ("T"-prefixed) that is stable per (bot, user) but bears no relationship
+// to the enterprise's real userid or email. Any implicit identity heuristic
+// (email-prefix match, corp userid lookup) is impossible. An explicit
+// binding table is the ONLY correct answer.
+
+import (
+ "context"
+ "crypto/rand"
+ "crypto/sha256"
+ "encoding/base64"
+ "encoding/hex"
+ "errors"
+ "fmt"
+ "time"
+
+ "github.com/jackc/pgx/v5"
+ "github.com/jackc/pgx/v5/pgtype"
+
+ "github.com/multica-ai/multica/server/internal/integrations/channel/engine"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+)
+
+// BindingTokenTTL bounds a token's life. The channel_binding_token CHECK
+// enforces the same 15-minute cap so a misconfigured caller cannot mint
+// longer.
+const BindingTokenTTL = 15 * time.Minute
+
+var (
+ // ErrBindingTokenInvalid: token unknown / already consumed / expired.
+ // One opaque error for all three avoids a replay timing oracle.
+ ErrBindingTokenInvalid = errors.New("wecom: binding token invalid or expired")
+ // ErrBindingAlreadyAssigned: this WeCom userid is already bound to a
+ // different Multica user (account transfer must go through explicit
+ // unbind, not implemented in iter 1 — an admin can DELETE the row).
+ ErrBindingAlreadyAssigned = errors.New("wecom: user id is already bound to a different user")
+ // ErrBindingNotWorkspaceMember: the redeemer is not a member of the
+ // token's workspace. Translated to 403 at the HTTP boundary.
+ ErrBindingNotWorkspaceMember = errors.New("wecom: redeemer is not a workspace member")
+)
+
+// BindingToken is a freshly minted token. The raw value is returned exactly
+// once (embedded in the binding URL); only its hash is persisted.
+type BindingToken struct {
+ Raw string
+ ExpiresAt time.Time
+}
+
+// RedeemedBindingToken is returned after a successful redemption.
+type RedeemedBindingToken struct {
+ WorkspaceID pgtype.UUID
+ InstallationID pgtype.UUID
+ WecomUserID string
+}
+
+// BindingTokenService mints and redeems WeCom binding tokens. Redemption is
+// transactional: consuming the token and inserting the channel_user_binding
+// row commit together, so a failed bind never burns a token.
+type BindingTokenService struct {
+ q *db.Queries
+ tx engine.TxStarter
+ now func() time.Time
+}
+
+// NewBindingTokenService constructs the service. tx (a *pgxpool.Pool) is
+// needed for the transactional redeem path.
+func NewBindingTokenService(q *db.Queries, tx engine.TxStarter) *BindingTokenService {
+ return &BindingTokenService{q: q, tx: tx, now: time.Now}
+}
+
+// Mint creates a single-use binding token for (installation, wecomUserID)
+// and returns the raw secret + expiry. The raw value must be delivered over
+// the aibot WebSocket (encrypted in transit by the platform) and never
+// logged.
+func (s *BindingTokenService) Mint(ctx context.Context, workspaceID, installationID pgtype.UUID, wecomUserID string) (BindingToken, error) {
+ raw, err := randomBindingToken(32)
+ if err != nil {
+ return BindingToken{}, fmt.Errorf("wecom: generate token: %w", err)
+ }
+ expiresAt := s.now().Add(BindingTokenTTL)
+ if _, err := s.q.CreateChannelBindingToken(ctx, db.CreateChannelBindingTokenParams{
+ TokenHash: hashBindingToken(raw),
+ WorkspaceID: workspaceID,
+ InstallationID: installationID,
+ ChannelType: channelTypeWecom,
+ ChannelUserID: wecomUserID,
+ ExpiresAt: pgtype.Timestamptz{Time: expiresAt, Valid: true},
+ }); err != nil {
+ return BindingToken{}, fmt.Errorf("wecom: persist token: %w", err)
+ }
+ return BindingToken{Raw: raw, ExpiresAt: expiresAt}, nil
+}
+
+// RedeemAndBind atomically consumes a raw token and binds the WeCom userid
+// to multicaUserID (taken from the session, never from the token). Returns
+// ErrBindingTokenInvalid / ErrBindingAlreadyAssigned /
+// ErrBindingNotWorkspaceMember.
+func (s *BindingTokenService) RedeemAndBind(ctx context.Context, raw string, multicaUserID pgtype.UUID) (RedeemedBindingToken, error) {
+ if s.tx == nil {
+ return RedeemedBindingToken{}, errors.New("wecom: BindingTokenService missing TxStarter")
+ }
+ tx, err := s.tx.Begin(ctx)
+ if err != nil {
+ return RedeemedBindingToken{}, fmt.Errorf("wecom: begin tx: %w", err)
+ }
+ defer func() { _ = tx.Rollback(ctx) }()
+ qtx := s.q.WithTx(tx)
+
+ row, err := qtx.ConsumeChannelBindingToken(ctx, hashBindingToken(raw))
+ if err != nil {
+ if errors.Is(err, pgx.ErrNoRows) {
+ return RedeemedBindingToken{}, ErrBindingTokenInvalid
+ }
+ return RedeemedBindingToken{}, fmt.Errorf("wecom: consume token: %w", err)
+ }
+ // Guard: the token row's channel_type must be 'wecom' — the redeem
+ // endpoint is wecom-scoped but the underlying table is shared across
+ // platforms. A caller who steals a slack token and posts it here would
+ // otherwise silently bind a slack userid via the wecom endpoint.
+ if row.ChannelType != channelTypeWecom {
+ return RedeemedBindingToken{}, ErrBindingTokenInvalid
+ }
+
+ // Explicit membership gate (no member FK): returning before Commit rolls
+ // the consume back, so a non-member's attempt does not burn the token.
+ if _, err := qtx.GetMemberByUserAndWorkspace(ctx, db.GetMemberByUserAndWorkspaceParams{
+ UserID: multicaUserID,
+ WorkspaceID: row.WorkspaceID,
+ }); err != nil {
+ if errors.Is(err, pgx.ErrNoRows) {
+ return RedeemedBindingToken{}, ErrBindingNotWorkspaceMember
+ }
+ return RedeemedBindingToken{}, fmt.Errorf("wecom: check membership: %w", err)
+ }
+
+ if _, err := qtx.CreateChannelUserBinding(ctx, db.CreateChannelUserBindingParams{
+ WorkspaceID: row.WorkspaceID,
+ MulticaUserID: multicaUserID,
+ InstallationID: row.InstallationID,
+ ChannelType: channelTypeWecom,
+ ChannelUserID: row.ChannelUserID,
+ Config: []byte(`{}`),
+ }); err != nil {
+ // pgx.ErrNoRows means the existing binding points at a different
+ // user — the ON CONFLICT DO UPDATE WHERE multica_user_id=… gating
+ // rejected it.
+ if errors.Is(err, pgx.ErrNoRows) {
+ return RedeemedBindingToken{}, ErrBindingAlreadyAssigned
+ }
+ return RedeemedBindingToken{}, fmt.Errorf("wecom: create binding: %w", err)
+ }
+
+ if err := tx.Commit(ctx); err != nil {
+ return RedeemedBindingToken{}, fmt.Errorf("wecom: commit: %w", err)
+ }
+ return RedeemedBindingToken{
+ WorkspaceID: row.WorkspaceID,
+ InstallationID: row.InstallationID,
+ WecomUserID: row.ChannelUserID,
+ }, nil
+}
+
+func randomBindingToken(n int) (string, error) {
+ buf := make([]byte, n)
+ if _, err := rand.Read(buf); err != nil {
+ return "", err
+ }
+ return base64.RawURLEncoding.EncodeToString(buf), nil
+}
+
+func hashBindingToken(raw string) string {
+ sum := sha256.Sum256([]byte(raw))
+ return hex.EncodeToString(sum[:])
+}
diff --git a/server/internal/integrations/wecom/credentials.go b/server/internal/integrations/wecom/credentials.go
new file mode 100644
index 0000000000..df21a36a1f
--- /dev/null
+++ b/server/internal/integrations/wecom/credentials.go
@@ -0,0 +1,55 @@
+package wecom
+
+// credentials.go — the CredentialsResolver default implementation that
+// unseals an Installation's encrypted secret for the WebSocket subscribe
+// frame. The wecom package owns encryption via a secretbox.Box supplied at
+// boot; the Installation itself never holds plaintext, so every caller that
+// needs a real secret comes through here.
+
+import (
+ "errors"
+ "fmt"
+
+ "github.com/multica-ai/multica/server/internal/util/secretbox"
+)
+
+// CredentialsResolver mints per-call InstallationCredentials with plaintext
+// secrets by unsealing what the Installation carries. The wecom package
+// injects a concrete implementation at boot; unit tests supply a fake.
+type CredentialsResolver interface {
+ Credentials(inst Installation) (InstallationCredentials, error)
+}
+
+// SecretboxCredentialsResolver decrypts the smart-bot secret using a single
+// secretbox.Box shared across every wecom installation. Rotation is the same
+// story as Feishu / Slack: change MULTICA_WECOM_SECRET_KEY, and every
+// existing row needs a re-encrypt migration.
+type SecretboxCredentialsResolver struct {
+ Box *secretbox.Box
+}
+
+// NewSecretboxCredentialsResolver validates the box is non-nil so the wire-
+// up cannot fall back to plaintext.
+func NewSecretboxCredentialsResolver(box *secretbox.Box) (*SecretboxCredentialsResolver, error) {
+ if box == nil {
+ return nil, errors.New("wecom: SecretboxCredentialsResolver requires a non-nil secretbox.Box")
+ }
+ return &SecretboxCredentialsResolver{Box: box}, nil
+}
+
+// Credentials returns the plaintext-bearing InstallationCredentials for a
+// given Installation. The returned value is a value type, safe to hand
+// around without aliasing the encrypted blob.
+func (r *SecretboxCredentialsResolver) Credentials(inst Installation) (InstallationCredentials, error) {
+ if r.Box == nil {
+ return InstallationCredentials{}, errors.New("wecom: credentials resolver has no secretbox")
+ }
+ secret, err := r.Box.Open(inst.SecretEncrypted)
+ if err != nil {
+ return InstallationCredentials{}, fmt.Errorf("wecom: decrypt secret: %w", err)
+ }
+ return InstallationCredentials{
+ BotID: inst.BotID,
+ Secret: string(secret),
+ }, nil
+}
diff --git a/server/internal/integrations/wecom/dispatch_test.go b/server/internal/integrations/wecom/dispatch_test.go
new file mode 100644
index 0000000000..d4090d4d91
--- /dev/null
+++ b/server/internal/integrations/wecom/dispatch_test.go
@@ -0,0 +1,146 @@
+package wecom
+
+// dispatch_test.go — dispatchFrame routing, driven with a recording wsConn and
+// a capturing handler (no network). Covers the text-only receipt for non-text
+// messages, the text path reaching the handler, the superseded-disconnect
+// escalation, and the server-ping / pong frames.
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "log/slog"
+ "testing"
+
+ "github.com/multica-ai/multica/server/internal/integrations/channel"
+)
+
+func testChannel(handler channel.InboundHandler) *wecomChannel {
+ return &wecomChannel{botID: "bot-1", handler: handler}
+}
+
+func msgCallbackFrame(t *testing.T, msgType, content string) frameEnvelope {
+ t.Helper()
+ mc := aibotMsgCallback{MsgID: "m1", ChatID: "CHAT_1", ChatType: "single", MsgType: msgType}
+ mc.From.UserID = "USER_A"
+ mc.Text.Content = content
+ body, err := json.Marshal(mc)
+ if err != nil {
+ t.Fatalf("marshal callback: %v", err)
+ }
+ return frameEnvelope{Cmd: cmdMsgCallback, Body: body}
+}
+
+func TestDispatchFrame_TextReachesHandler(t *testing.T) {
+ t.Parallel()
+ var got channel.InboundMessage
+ called := false
+ c := testChannel(func(_ context.Context, m channel.InboundMessage) error {
+ called, got = true, m
+ return nil
+ })
+ conn := &recordingConn{}
+ err := c.dispatchFrame(context.Background(), msgCallbackFrame(t, "text", "hello"), newWSSender(conn, nil), slog.Default())
+ if err != nil {
+ t.Fatalf("dispatchFrame: %v", err)
+ }
+ if !called {
+ t.Fatal("handler was not called for a text message")
+ }
+ if got.Text != "hello" {
+ t.Errorf("handler got text %q, want hello", got.Text)
+ }
+ if len(conn.frames) != 0 {
+ t.Errorf("text message should not send a receipt, got %d frames", len(conn.frames))
+ }
+}
+
+func TestDispatchFrame_NonTextGetsReceiptAndSkipsHandler(t *testing.T) {
+ t.Parallel()
+ called := false
+ c := testChannel(func(context.Context, channel.InboundMessage) error {
+ called = true
+ return nil
+ })
+ conn := &recordingConn{}
+ err := c.dispatchFrame(context.Background(), msgCallbackFrame(t, "image", ""), newWSSender(conn, nil), slog.Default())
+ if err != nil {
+ t.Fatalf("dispatchFrame: %v", err)
+ }
+ if called {
+ t.Error("handler must NOT be called for a non-text message")
+ }
+ if len(conn.frames) != 1 {
+ t.Fatalf("expected one text-only receipt, got %d frames", len(conn.frames))
+ }
+ body := conn.sendBody(t, 0)
+ if body["chatid"] != "CHAT_1" {
+ t.Errorf("receipt chatid = %v, want the same chat CHAT_1", body["chatid"])
+ }
+}
+
+func TestDispatchFrame_DisconnectedEventEscalates(t *testing.T) {
+ t.Parallel()
+ c := testChannel(func(context.Context, channel.InboundMessage) error { return nil })
+ ec := aibotEventCallback{}
+ ec.Event.EventType = eventDisconnected
+ body, _ := json.Marshal(ec)
+ err := c.dispatchFrame(context.Background(), frameEnvelope{Cmd: cmdEventCallback, Body: body}, newWSSender(&recordingConn{}, nil), slog.Default())
+ if err == nil {
+ t.Fatal("a disconnected_event must return an error so the Supervisor reconnects")
+ }
+}
+
+func TestDispatchFrame_ServerPingIsPonged(t *testing.T) {
+ t.Parallel()
+ c := testChannel(func(context.Context, channel.InboundMessage) error { return nil })
+ conn := &recordingConn{}
+ err := c.dispatchFrame(context.Background(), frameEnvelope{Cmd: cmdServerPing, Headers: frameHeaders{ReqID: "r1"}}, newWSSender(conn, nil), slog.Default())
+ if err != nil {
+ t.Fatalf("dispatchFrame: %v", err)
+ }
+ if len(conn.frames) != 1 || conn.frames[0].Cmd != cmdPong {
+ t.Errorf("server ping should be answered with a pong, got %+v", conn.frames)
+ }
+}
+
+func TestDispatchFrame_HandlerErrorPropagates(t *testing.T) {
+ t.Parallel()
+ c := testChannel(func(context.Context, channel.InboundMessage) error { return errors.New("boom") })
+ err := c.dispatchFrame(context.Background(), msgCallbackFrame(t, "text", "hi"), newWSSender(&recordingConn{}, nil), slog.Default())
+ if err == nil {
+ t.Fatal("a handler error must propagate so the read loop can escalate")
+ }
+}
+
+func TestChannelGetters(t *testing.T) {
+ t.Parallel()
+ c := testChannel(nil)
+ if c.Type() != TypeWecom {
+ t.Errorf("Type() = %v, want %v", c.Type(), TypeWecom)
+ }
+ if c.Capabilities()&channel.CapText == 0 {
+ t.Error("Capabilities() should include CapText")
+ }
+ if err := c.Disconnect(context.Background()); err != nil {
+ t.Errorf("Disconnect() = %v, want nil", err)
+ }
+ if _, err := c.Send(context.Background(), channel.OutboundMessage{}); !errors.Is(err, ErrSendNotSupported) {
+ t.Errorf("Send() = %v, want ErrSendNotSupported", err)
+ }
+}
+
+// TestSend_NeverGuessesChatType pins the fix for the removed len(ChatID)>32
+// heuristic: Send must reject regardless of ChatID length — a long id must not
+// route as a group send, a short one must not route as a private send. If a
+// length heuristic ever comes back, one of these stops returning the sentinel.
+func TestSend_NeverGuessesChatType(t *testing.T) {
+ t.Parallel()
+ c := testChannel(func(context.Context, channel.InboundMessage) error { return nil })
+ for _, chatID := range []string{"short", "a-very-long-chat-id-well-over-thirty-two-characters-long"} {
+ _, err := c.Send(context.Background(), channel.OutboundMessage{ChatID: chatID, Text: "hi"})
+ if !errors.Is(err, ErrSendNotSupported) {
+ t.Errorf("Send(ChatID=%q) = %v, want ErrSendNotSupported (no length heuristic)", chatID, err)
+ }
+ }
+}
diff --git a/server/internal/integrations/wecom/helpers_test.go b/server/internal/integrations/wecom/helpers_test.go
new file mode 100644
index 0000000000..d7d0b6a610
--- /dev/null
+++ b/server/internal/integrations/wecom/helpers_test.go
@@ -0,0 +1,119 @@
+package wecom
+
+// helpers_test.go — pure, no-network guards for the small building blocks:
+// the install-config JSON round trip, the binding-token hash, and the
+// issue-created confirmation text.
+
+import (
+ "strings"
+ "testing"
+
+ "github.com/jackc/pgx/v5/pgtype"
+
+ "github.com/multica-ai/multica/server/internal/integrations/channel/engine"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+)
+
+func TestEncodeInstallConfigRoundTrip(t *testing.T) {
+ t.Parallel()
+ in := Installation{BotID: "bot-xyz", SecretEncrypted: []byte("sealed")}
+ cfg, err := encodeInstallConfig(in)
+ if err != nil {
+ t.Fatalf("encode: %v", err)
+ }
+ out, err := installationFromRow(db.ChannelInstallation{Config: cfg, Status: "active"})
+ if err != nil {
+ t.Fatalf("decode: %v", err)
+ }
+ if out.BotID != "bot-xyz" {
+ t.Errorf("BotID round trip = %q, want bot-xyz", out.BotID)
+ }
+ if string(out.SecretEncrypted) != "sealed" {
+ t.Errorf("SecretEncrypted round trip = %q, want sealed", out.SecretEncrypted)
+ }
+ if out.Status != InstallationActive {
+ t.Errorf("Status = %q, want active", out.Status)
+ }
+}
+
+func TestEncodeInstallConfigRequiresBotID(t *testing.T) {
+ t.Parallel()
+ if _, err := encodeInstallConfig(Installation{}); err == nil {
+ t.Error("encodeInstallConfig with no bot_id should error")
+ }
+}
+
+func TestHashBindingTokenStableAndDistinct(t *testing.T) {
+ t.Parallel()
+ h1 := hashBindingToken("token-a")
+ if h1 != hashBindingToken("token-a") {
+ t.Error("hash is not stable for the same input")
+ }
+ if h1 == hashBindingToken("token-b") {
+ t.Error("different tokens hashed to the same value")
+ }
+ if len(h1) != 64 { // sha256 hex
+ t.Errorf("hash length = %d, want 64 hex chars", len(h1))
+ }
+ // The raw token must not be recoverable from / equal to its hash.
+ if strings.Contains(h1, "token-a") {
+ t.Error("hash leaks the raw token")
+ }
+}
+
+func TestRandomBindingTokenIsUnique(t *testing.T) {
+ t.Parallel()
+ a, err := randomBindingToken(24)
+ if err != nil {
+ t.Fatalf("randomBindingToken: %v", err)
+ }
+ b, _ := randomBindingToken(24)
+ if a == "" || a == b {
+ t.Errorf("expected two distinct non-empty tokens, got %q and %q", a, b)
+ }
+}
+
+func TestValidateInstallationParams(t *testing.T) {
+ t.Parallel()
+ valid := InstallationParams{
+ WorkspaceID: mustTestUUID(t),
+ AgentID: mustTestUUID(t),
+ InstallerUserID: mustTestUUID(t),
+ BotID: "bot-1",
+ Secret: "s3cr3t",
+ }
+ if err := validateInstallationParams(valid); err != nil {
+ t.Fatalf("valid params rejected: %v", err)
+ }
+ // Each required field, cleared in turn, must be rejected.
+ clearers := map[string]func(p *InstallationParams){
+ "workspace_id": func(p *InstallationParams) { p.WorkspaceID = pgtype.UUID{} },
+ "agent_id": func(p *InstallationParams) { p.AgentID = pgtype.UUID{} },
+ "installer": func(p *InstallationParams) { p.InstallerUserID = pgtype.UUID{} },
+ "bot_id": func(p *InstallationParams) { p.BotID = "" },
+ "secret": func(p *InstallationParams) { p.Secret = "" },
+ }
+ for name, clear := range clearers {
+ p := valid
+ clear(&p)
+ if err := validateInstallationParams(p); err == nil {
+ t.Errorf("missing %s should be rejected", name)
+ }
+ }
+}
+
+func TestIssueCreatedText(t *testing.T) {
+ t.Parallel()
+ withTitle := issueCreatedText(engine.Result{IssueIdentifier: "MUL-42", IssueTitle: "Fix the thing"})
+ if !strings.Contains(withTitle, "MUL-42") || !strings.Contains(withTitle, "Fix the thing") {
+ t.Errorf("issueCreatedText = %q, want identifier + title", withTitle)
+ }
+ noTitle := issueCreatedText(engine.Result{IssueIdentifier: "MUL-43"})
+ if !strings.Contains(noTitle, "MUL-43") || strings.Contains(noTitle, "—") {
+ t.Errorf("issueCreatedText without title = %q, want just the identifier", noTitle)
+ }
+ noID := issueCreatedText(engine.Result{IssueNumber: 7})
+ if !strings.Contains(noID, "#7") {
+ t.Errorf("issueCreatedText with no identifier = %q, want #7 fallback", noID)
+ }
+}
diff --git a/server/internal/integrations/wecom/inbox_message.go b/server/internal/integrations/wecom/inbox_message.go
new file mode 100644
index 0000000000..0c60d67f66
--- /dev/null
+++ b/server/internal/integrations/wecom/inbox_message.go
@@ -0,0 +1,184 @@
+package wecom
+
+// inbox_message.go — the markdown body wecom smart-bot pushes on inbox:new.
+// Uses markdown so it renders cleanly through aibot_send_msg (which does not
+// accept msgtype=text). Kept in a separate file so the outbound handler stays
+// focused on delivery and this module owns the wording + link building.
+
+import (
+ "net/url"
+ "os"
+ "strings"
+ "unicode/utf8"
+)
+
+// aibot markdown size cap. WeCom rejects the whole frame if we
+// push more than ~4096 chars, so we truncate the body on that budget. We
+// use 4000 to leave headroom for the prefix + link suffix.
+const inboxMarkdownMaxLen = 4000
+
+// inboxTypeLabels are the Chinese display names used in the notification
+// preamble. Kept locally so wecom does not reach into cmd/server for it;
+// the two lists agree by convention.
+var inboxTypeLabels = map[string]string{
+ "issue_assigned": "任务指派",
+ "mentioned": "提及你",
+ "status_changed": "状态变更",
+ "comment_added": "新评论",
+ "new_comment": "新评论",
+ "reaction_added": "表情反应",
+ "task_failed": "任务失败",
+ "unassigned": "取消指派",
+ "assignee_changed": "指派人变更",
+ "priority_changed": "优先级变更",
+ "due_date_changed": "截止日期变更",
+ "start_date_changed": "开始日期变更",
+}
+
+func inboxTypeLabel(t string) string {
+ if label, ok := inboxTypeLabels[t]; ok {
+ return label
+ }
+ return "新消息"
+}
+
+// inboxAppURL resolves the frontend URL for building the "view detail" link.
+// Priority: WECOM_APP_URL → MULTICA_APP_URL → FRONTEND_ORIGIN. Only HTTPS
+// values are accepted; a non-HTTPS override is silently dropped so a
+// misconfigured env cannot leak an http:// URL into a user chat.
+func inboxAppURL() string {
+ for _, name := range []string{"WECOM_APP_URL", "MULTICA_APP_URL", "FRONTEND_ORIGIN"} {
+ v := strings.TrimSpace(os.Getenv(name))
+ if v == "" {
+ continue
+ }
+ if !strings.HasPrefix(v, "https://") {
+ continue
+ }
+ return strings.TrimRight(v, "/")
+ }
+ return ""
+}
+
+// buildInboxMarkdown builds the aibot-friendly markdown body from an
+// inbox_item map. Format:
+//
+// **[{type}] {title}**
+// {body}
+// [查看详情]({appURL}/{slug|workspaceID}/inbox?issue={issueID})
+//
+// The link segment is omitted entirely when no appURL is configured — we
+// would rather send a title-only card than a broken link.
+func buildInboxMarkdown(item map[string]any, workspaceID, slug string) string {
+ title, _ := item["title"].(string)
+ typeStr, _ := item["type"].(string)
+ if title == "" && typeStr == "" {
+ return ""
+ }
+ body := inboxItemBody(item)
+ link := inboxItemLink(item, workspaceID, slug)
+
+ var b strings.Builder
+ b.WriteString("**[")
+ b.WriteString(inboxTypeLabel(typeStr))
+ b.WriteString("] ")
+ b.WriteString(title)
+ b.WriteString("**")
+ if body != "" {
+ b.WriteString("\n")
+ b.WriteString(body)
+ }
+ if link != "" {
+ b.WriteString("\n[查看详情](")
+ b.WriteString(link)
+ b.WriteString(")")
+ }
+ result := b.String()
+ if utf8.RuneCountInString(result) <= inboxMarkdownMaxLen {
+ return result
+ }
+ // Truncate the body only. Prefix + link must survive intact so the
+ // user still gets the "view detail" affordance.
+ prefix := "**[" + inboxTypeLabel(typeStr) + "] " + title + "**"
+ suffix := ""
+ if link != "" {
+ suffix = "\n[查看详情](" + link + ")"
+ }
+ room := inboxMarkdownMaxLen - utf8.RuneCountInString(prefix) - utf8.RuneCountInString(suffix) - 4 // "\n...\n"
+ if room <= 0 {
+ return prefix + suffix
+ }
+ return prefix + "\n" + truncateRunes(body, room) + "..." + suffix
+}
+
+// inboxItemBody extracts the body/description string from an inbox_item map.
+// Body may arrive as *string (nil-able JSON field), string, or missing.
+func inboxItemBody(item map[string]any) string {
+ switch v := item["body"].(type) {
+ case *string:
+ if v != nil {
+ return *v
+ }
+ case string:
+ return v
+ }
+ return ""
+}
+
+// inboxItemLink builds the {appURL}/{slug|wsUUID}/inbox?issue={issueID}
+// deep link. Returns "" when no appURL is configured — the caller uses that
+// as a signal to drop the entire link segment.
+func inboxItemLink(item map[string]any, workspaceID, slug string) string {
+ appURL := inboxAppURL()
+ if appURL == "" {
+ return ""
+ }
+ seg := slug
+ if seg == "" {
+ seg = workspaceID
+ }
+ var b strings.Builder
+ b.WriteString(appURL)
+ b.WriteString("/")
+ b.WriteString(url.PathEscape(seg))
+ b.WriteString("/inbox")
+ // Optional ?issue=... — chat-only inbox items have no issue.
+ if issueID := inboxItemIssueID(item); issueID != "" {
+ b.WriteString("?issue=")
+ b.WriteString(url.QueryEscape(issueID))
+ }
+ return b.String()
+}
+
+// inboxItemIssueID extracts issue_id when present. Chat-type notifications
+// have no issue_id and we return "" — the link then omits the query param.
+func inboxItemIssueID(item map[string]any) string {
+ switch v := item["issue_id"].(type) {
+ case *string:
+ if v != nil {
+ return *v
+ }
+ case string:
+ return v
+ }
+ return ""
+}
+
+// truncateRunes trims s to at most maxRunes runes. Rune-based rather than
+// byte-based so the truncation never splits a Chinese character.
+func truncateRunes(s string, maxRunes int) string {
+ if maxRunes <= 0 {
+ return ""
+ }
+ if utf8.RuneCountInString(s) <= maxRunes {
+ return s
+ }
+ i := 0
+ for pos := range s {
+ if i == maxRunes {
+ return s[:pos]
+ }
+ i++
+ }
+ return s
+}
diff --git a/server/internal/integrations/wecom/inbox_message_test.go b/server/internal/integrations/wecom/inbox_message_test.go
new file mode 100644
index 0000000000..2891d11803
--- /dev/null
+++ b/server/internal/integrations/wecom/inbox_message_test.go
@@ -0,0 +1,134 @@
+package wecom
+
+import (
+ "os"
+ "strings"
+ "testing"
+)
+
+func TestBuildInboxMarkdown_TitleBodyLink(t *testing.T) {
+ t.Setenv("WECOM_APP_URL", "https://example.com")
+ item := map[string]any{
+ "type": "status_changed",
+ "title": "登录页 500 错误",
+ "body": "from: todo\nto: in_review",
+ "issue_id": "9194c058-e8a4-4c15-9c65-86d1784ba715",
+ }
+ got := buildInboxMarkdown(item, "ws-uuid", "acme")
+ if !strings.Contains(got, "**[状态变更] 登录页 500 错误**") {
+ t.Fatalf("missing typed title header: %q", got)
+ }
+ if !strings.Contains(got, "from: todo\nto: in_review") {
+ t.Fatalf("missing body: %q", got)
+ }
+ if !strings.Contains(got, "[查看详情](https://example.com/acme/inbox?issue=9194c058-e8a4-4c15-9c65-86d1784ba715)") {
+ t.Fatalf("missing detail link: %q", got)
+ }
+}
+
+func TestBuildInboxMarkdown_UnknownTypeFallsBackToDefault(t *testing.T) {
+ t.Setenv("WECOM_APP_URL", "https://example.com")
+ item := map[string]any{"type": "some_new_type", "title": "hi"}
+ got := buildInboxMarkdown(item, "ws-uuid", "acme")
+ if !strings.Contains(got, "**[新消息] hi**") {
+ t.Fatalf("expected fallback type label 新消息, got %q", got)
+ }
+}
+
+func TestBuildInboxMarkdown_FallsBackToWorkspaceUUIDWhenSlugMissing(t *testing.T) {
+ t.Setenv("WECOM_APP_URL", "https://example.com")
+ item := map[string]any{"type": "new_comment", "title": "t", "issue_id": "iid"}
+ got := buildInboxMarkdown(item, "ws-uuid", "")
+ if !strings.Contains(got, "https://example.com/ws-uuid/inbox?issue=iid") {
+ t.Fatalf("expected workspace uuid path segment, got %q", got)
+ }
+}
+
+func TestBuildInboxMarkdown_NoAppURLDropsLink(t *testing.T) {
+ // Unset every var buildInboxMarkdown looks at.
+ for _, k := range []string{"WECOM_APP_URL", "MULTICA_APP_URL", "FRONTEND_ORIGIN"} {
+ if v, ok := os.LookupEnv(k); ok {
+ t.Cleanup(func() { os.Setenv(k, v) })
+ }
+ os.Unsetenv(k)
+ }
+ item := map[string]any{"type": "new_comment", "title": "t"}
+ got := buildInboxMarkdown(item, "ws-uuid", "acme")
+ if strings.Contains(got, "查看详情") {
+ t.Fatalf("link section must be omitted when no app url is configured: %q", got)
+ }
+}
+
+func TestBuildInboxMarkdown_NonHTTPSAppURLIsRejected(t *testing.T) {
+ for _, k := range []string{"WECOM_APP_URL", "MULTICA_APP_URL", "FRONTEND_ORIGIN"} {
+ if v, ok := os.LookupEnv(k); ok {
+ t.Cleanup(func() { os.Setenv(k, v) })
+ }
+ os.Unsetenv(k)
+ }
+ t.Setenv("WECOM_APP_URL", "http://insecure.example.com")
+ item := map[string]any{"type": "new_comment", "title": "t"}
+ got := buildInboxMarkdown(item, "ws-uuid", "acme")
+ if strings.Contains(got, "insecure.example.com") {
+ t.Fatalf("http:// override must be dropped, got %q", got)
+ }
+}
+
+func TestBuildInboxMarkdown_TruncatesLongBody(t *testing.T) {
+ t.Setenv("WECOM_APP_URL", "https://example.com")
+ body := strings.Repeat("我", 5000) // 5000 runes, exceeds 4000 cap
+ item := map[string]any{"type": "new_comment", "title": "hi", "body": body, "issue_id": "iid"}
+ got := buildInboxMarkdown(item, "ws-uuid", "acme")
+ if !strings.Contains(got, "...") {
+ t.Fatalf("expected truncation marker, got tail %q", got[len(got)-50:])
+ }
+ if !strings.HasSuffix(got, "acme/inbox?issue=iid)") {
+ t.Fatalf("link must survive truncation, got tail %q", got[len(got)-80:])
+ }
+}
+
+func TestBuildInboxMarkdown_HandlesPointerBodyAndIssueID(t *testing.T) {
+ t.Setenv("WECOM_APP_URL", "https://example.com")
+ bodyStr := "详情"
+ issueIDStr := "iid"
+ item := map[string]any{
+ "type": "new_comment",
+ "title": "hi",
+ "body": &bodyStr,
+ "issue_id": &issueIDStr,
+ }
+ got := buildInboxMarkdown(item, "ws-uuid", "acme")
+ if !strings.Contains(got, "详情") {
+ t.Fatalf("expected pointer body to be dereferenced, got %q", got)
+ }
+ if !strings.Contains(got, "issue=iid") {
+ t.Fatalf("expected pointer issue_id to be dereferenced, got %q", got)
+ }
+}
+
+func TestBuildInboxMarkdown_EmptyItemReturnsEmpty(t *testing.T) {
+ got := buildInboxMarkdown(map[string]any{}, "ws", "slug")
+ if got != "" {
+ t.Fatalf("expected empty output for empty item, got %q", got)
+ }
+}
+
+func TestTruncateRunes(t *testing.T) {
+ cases := []struct {
+ in string
+ max int
+ expect string
+ }{
+ {"abc", 0, ""},
+ {"abc", 3, "abc"},
+ {"abc", 2, "ab"},
+ {"你好世界", 2, "你好"},
+ {"你好世界", 4, "你好世界"},
+ {"你好世界", 5, "你好世界"},
+ }
+ for _, tc := range cases {
+ if got := truncateRunes(tc.in, tc.max); got != tc.expect {
+ t.Errorf("truncateRunes(%q,%d)=%q; want %q", tc.in, tc.max, got, tc.expect)
+ }
+ }
+}
diff --git a/server/internal/integrations/wecom/installation.go b/server/internal/integrations/wecom/installation.go
new file mode 100644
index 0000000000..8de634ec68
--- /dev/null
+++ b/server/internal/integrations/wecom/installation.go
@@ -0,0 +1,269 @@
+package wecom
+
+// installation.go — the write surface for wecom channel_installation rows.
+// It centralises secretbox encryption of the smart-bot secret so no caller
+// ever handles plaintext beyond this file's boundary, and it is the ONLY
+// path to a wecom row in channel_installation — an admin CLI or an HTTP
+// install endpoint both go through Upsert.
+
+import (
+ "context"
+ "errors"
+ "fmt"
+
+ "github.com/jackc/pgx/v5"
+ "github.com/jackc/pgx/v5/pgconn"
+ "github.com/jackc/pgx/v5/pgtype"
+
+ "github.com/multica-ai/multica/server/internal/integrations/channel/engine"
+ "github.com/multica-ai/multica/server/internal/util/secretbox"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+)
+
+// InstallationParams is the plaintext-bearing input to InstallationService.
+// The caller supplies the raw (BotID, Secret) pair from the WeCom
+// admin console; the service seals Secret before it touches the DB.
+type InstallationParams struct {
+ WorkspaceID pgtype.UUID
+ AgentID pgtype.UUID
+ InstallerUserID pgtype.UUID
+
+ // BotID is the smart-bot identifier shown on the WeCom admin
+ // console. Stable per-bot; used as both auth identity in the subscribe
+ // frame and the routing key persisted at config->>'app_id'.
+ BotID string
+
+ // Secret is the plaintext long-connection secret shown once at bot
+ // creation on the admin console. Sealed at the service boundary.
+ Secret string
+}
+
+// InstallationService creates, refreshes and revokes wecom smart-bot
+// installations through the shared channel_installation table. It requires
+// a non-nil *secretbox.Box so a caller cannot accidentally fall back to
+// plaintext storage — the same invariant lark.InstallationService enforces.
+type InstallationService struct {
+ store *Store
+ tx engine.TxStarter
+ box *secretbox.Box
+}
+
+// NewInstallationService binds the service to a queries handle, a transaction
+// starter (so the reclaim-then-upsert runs atomically), and a secretbox keyed
+// for at-rest encryption. Returns an error when the box is nil; callers should
+// surface it (do not fall back to plaintext).
+func NewInstallationService(queries *db.Queries, tx engine.TxStarter, box *secretbox.Box) (*InstallationService, error) {
+ if box == nil {
+ return nil, errors.New("wecom: InstallationService requires a non-nil secretbox.Box")
+ }
+ return &InstallationService{store: NewStore(queries), tx: tx, box: box}, nil
+}
+
+// Upsert creates or refreshes an installation row. The conflict key on
+// channel_installation is (workspace_id, agent_id, channel_type), so
+// re-running Upsert against an existing (workspace, agent, wecom) triple
+// rotates every field on the row and flips status back to 'active'. The
+// returned Installation reflects the post-write DB state.
+func (s *InstallationService) Upsert(ctx context.Context, p InstallationParams) (Installation, error) {
+ if err := validateInstallationParams(p); err != nil {
+ return Installation{}, err
+ }
+ sealed, err := s.box.Seal([]byte(p.Secret))
+ if err != nil {
+ return Installation{}, fmt.Errorf("wecom: encrypt secret: %w", err)
+ }
+ cfg, err := encodeInstallConfig(Installation{
+ BotID: p.BotID,
+ SecretEncrypted: sealed,
+ })
+ if err != nil {
+ return Installation{}, err
+ }
+
+ // Reclaim-then-upsert, atomically. UpsertChannelInstallation conflicts on
+ // (workspace_id, agent_id, channel_type), but the (channel_type, app_id)
+ // slot is guarded by idx_channel_installation_type_appid. Disconnect only
+ // flips status to 'revoked' — it does not free the row — so without a
+ // reclaim step a bot revoked from agent A can never be connected to agent
+ // B: the upsert misses its ON CONFLICT and trips the unique index, and the
+ // admin is told to "disconnect it there first" for a bot that is already
+ // disconnected and has no UI control to free it. ReclaimDeadChannelInstalla-
+ // tionByAppID deletes any DEAD owner of this bot's slot (a revoked row held
+ // by a DIFFERENT (workspace, agent), or an orphan whose workspace/agent was
+ // deleted) and clears its dependent rows in the same statement, while
+ // leaving a LIVE owner (active or archived agent) in place to trip the
+ // index below — which botOwnerConflictErr turns into an accurate 409.
+ // Mirrors slack/install.go's persistInstall.
+ if s.tx == nil {
+ return Installation{}, errors.New("wecom: InstallationService requires a transaction starter")
+ }
+ tx, err := s.tx.Begin(ctx)
+ if err != nil {
+ return Installation{}, fmt.Errorf("wecom: begin install tx: %w", err)
+ }
+ defer func() { _ = tx.Rollback(ctx) }()
+ qtx := s.store.WithTx(tx)
+
+ if _, err := qtx.Queries.ReclaimDeadChannelInstallationByAppID(ctx, db.ReclaimDeadChannelInstallationByAppIDParams{
+ ChannelType: channelTypeWecom,
+ AppID: p.BotID,
+ WorkspaceID: p.WorkspaceID,
+ AgentID: p.AgentID,
+ }); err != nil && !errors.Is(err, pgx.ErrNoRows) {
+ // pgx.ErrNoRows just means nothing was dead — a no-op, not a failure.
+ return Installation{}, fmt.Errorf("wecom: reclaim dead installation: %w", err)
+ }
+
+ row, err := qtx.Queries.UpsertChannelInstallation(ctx, db.UpsertChannelInstallationParams{
+ WorkspaceID: p.WorkspaceID,
+ AgentID: p.AgentID,
+ ChannelType: channelTypeWecom,
+ Config: cfg,
+ InstallerUserID: p.InstallerUserID,
+ })
+ if err != nil {
+ var pgErr *pgconn.PgError
+ if errors.As(err, &pgErr) && pgErr.Code == pgUniqueViolation {
+ // A LIVE owner still holds the slot. Read the owner on the
+ // non-tx connection (this tx is now in aborted state) to name it.
+ return Installation{}, s.botOwnerConflictErr(ctx, p.WorkspaceID, p.BotID)
+ }
+ return Installation{}, fmt.Errorf("wecom: upsert installation: %w", err)
+ }
+ if err := tx.Commit(ctx); err != nil {
+ return Installation{}, fmt.Errorf("wecom: commit install tx: %w", err)
+ }
+ return installationFromRow(row)
+}
+
+// Sentinels for the one conflict Upsert cannot resolve: the bot is already
+// connected somewhere else. UpsertChannelInstallation conflicts on
+// (workspace_id, agent_id, channel_type), but idx_channel_installation_type_appid
+// is UNIQUE on (channel_type, config->>'app_id') — so connecting the SAME bot to
+// a second agent misses the ON CONFLICT clause entirely and trips the index
+// instead. Without these the admin reads the raw Postgres text
+// ("duplicate key value violates unique constraint …") in a toast.
+//
+// One bot is one connection: the WeCom long connection allows a single
+// live subscriber per bot, so two agents cannot share one. The way out is
+// always to free the bot first, which is what each message says.
+var (
+ // ErrBotOwnedBySameWorkspace — another agent in the admin's own workspace
+ // holds the bot. Reversible from the same settings screen.
+ ErrBotOwnedBySameWorkspace = errors.New("wecom: this bot is already connected to another agent in this workspace")
+
+ // ErrBotOwnedByArchivedAgent — the holder is archived, so it does not show
+ // up in the agent list and the bot looks free while it is not.
+ ErrBotOwnedByArchivedAgent = errors.New("wecom: this bot is connected to an archived agent in this workspace")
+
+ // ErrBotOwnedByAnotherWorkspace — the holder is out of sight entirely and
+ // only someone with access there can release it.
+ ErrBotOwnedByAnotherWorkspace = errors.New("wecom: this bot is already connected to a different Multica workspace")
+)
+
+// pgUniqueViolation is Postgres' unique_violation SQLSTATE.
+const pgUniqueViolation = "23505"
+
+// botOwnerConflictErr names who holds the (wecom, bot_id) routing slot so the
+// handler can tell the admin where to go, mirroring slack's owner-conflict
+// classification. Read after the upsert failed, so a slot that has since been
+// freed — or a lookup that fails — falls back to the cross-workspace message:
+// it is the only one that is never wrong about where to look, and a retry
+// succeeds anyway.
+func (s *InstallationService) botOwnerConflictErr(ctx context.Context, requestingWorkspaceID pgtype.UUID, botID string) error {
+ owner, err := s.store.Queries.GetChannelInstallationOwnerByAppID(ctx, db.GetChannelInstallationOwnerByAppIDParams{
+ ChannelType: channelTypeWecom,
+ AppID: botID,
+ })
+ if err != nil {
+ return ErrBotOwnedByAnotherWorkspace
+ }
+ switch {
+ case owner.WorkspaceID != requestingWorkspaceID:
+ return ErrBotOwnedByAnotherWorkspace
+ case owner.AgentArchivedAt.Valid:
+ return ErrBotOwnedByArchivedAgent
+ default:
+ return ErrBotOwnedBySameWorkspace
+ }
+}
+
+// Revoke flips status to 'revoked' — the row is preserved so audit trails
+// remain queryable, and a subsequent Upsert flips it back to 'active'
+// atomically. A revoked row is skipped by the router's installation resolver
+// (Active=false → invalid_event drop with audit).
+func (s *InstallationService) Revoke(ctx context.Context, id pgtype.UUID) error {
+ return s.store.Queries.SetChannelInstallationStatus(ctx, db.SetChannelInstallationStatusParams{
+ ID: id,
+ Status: string(InstallationRevoked),
+ })
+}
+
+// ErrInstallationNotFound is returned by GetInWorkspace when either no row
+// exists at the given (id, workspace) or the row belongs to a different
+// channel_type. It is distinct from a plain pgx.ErrNoRows so HTTP handlers
+// can map it to 404 without importing pgx.
+var ErrInstallationNotFound = errors.New("wecom: installation not found")
+
+// ListByWorkspace returns every wecom installation for the given workspace
+// in creation order. Used by the Settings and Agent-Integrations tabs to
+// render "connected bots" lists; revoked rows are included so operators can
+// see history (the UI filters on Status).
+func (s *InstallationService) ListByWorkspace(ctx context.Context, workspaceID pgtype.UUID) ([]Installation, error) {
+ rows, err := s.store.Queries.ListChannelInstallationsByWorkspace(ctx, db.ListChannelInstallationsByWorkspaceParams{
+ WorkspaceID: workspaceID,
+ ChannelType: channelTypeWecom,
+ })
+ if err != nil {
+ return nil, err
+ }
+ out := make([]Installation, 0, len(rows))
+ for _, row := range rows {
+ inst, err := installationFromRow(row)
+ if err != nil {
+ return nil, fmt.Errorf("wecom: decode installation %s: %w", row.ID.String(), err)
+ }
+ out = append(out, inst)
+ }
+ return out, nil
+}
+
+// GetInWorkspace loads one installation scoped to (id, workspace_id) so a
+// forged UUID from another workspace returns not-found instead of leaking
+// existence. Returns ErrInstallationNotFound on either missing row or a
+// row that exists but belongs to another channel_type.
+func (s *InstallationService) GetInWorkspace(ctx context.Context, id, workspaceID pgtype.UUID) (Installation, error) {
+ row, err := s.store.Queries.GetChannelInstallationInWorkspace(ctx, db.GetChannelInstallationInWorkspaceParams{
+ ID: id,
+ WorkspaceID: workspaceID,
+ ChannelType: channelTypeWecom,
+ })
+ if err != nil {
+ if errors.Is(err, pgx.ErrNoRows) {
+ return Installation{}, ErrInstallationNotFound
+ }
+ return Installation{}, err
+ }
+ return installationFromRow(row)
+}
+
+// validateInstallationParams is a lightweight pre-write check for
+// required fields. It does NOT verify anything against WeCom.
+func validateInstallationParams(p InstallationParams) error {
+ if !p.WorkspaceID.Valid {
+ return errors.New("wecom: workspace_id is required")
+ }
+ if !p.AgentID.Valid {
+ return errors.New("wecom: agent_id is required")
+ }
+ if !p.InstallerUserID.Valid {
+ return errors.New("wecom: installer_user_id is required")
+ }
+ if p.BotID == "" {
+ return errors.New("wecom: bot_id is required")
+ }
+ if p.Secret == "" {
+ return errors.New("wecom: secret is required")
+ }
+ return nil
+}
diff --git a/server/internal/integrations/wecom/installation_reclaim_test.go b/server/internal/integrations/wecom/installation_reclaim_test.go
new file mode 100644
index 0000000000..42eefcb77e
--- /dev/null
+++ b/server/internal/integrations/wecom/installation_reclaim_test.go
@@ -0,0 +1,209 @@
+package wecom
+
+// installation_reclaim_test.go — DB-backed guards for the reclaim-then-upsert
+// slot recovery (the fix for the "a disconnected bot can never be moved to
+// another agent" review item). These need Postgres: they exercise the real
+// ReclaimDeadChannelInstallationByAppID DELETE against channel_installation +
+// workspace + agent rows, so they skip when no migrated database is reachable
+// (they run in CI, which has one). Mirrors lark/channel_store_rebind_test.go.
+
+import (
+ "context"
+ "errors"
+ "os"
+ "testing"
+
+ "github.com/jackc/pgx/v5/pgtype"
+ "github.com/jackc/pgx/v5/pgxpool"
+
+ "github.com/multica-ai/multica/server/internal/util"
+ "github.com/multica-ai/multica/server/internal/util/secretbox"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+)
+
+const (
+ wcRclWS = "5c09e200-0000-4000-8000-000000000001"
+ wcRclRuntime = "5c09e200-0000-4000-8000-000000000003"
+ wcRclAgentA = "5c09e200-0000-4000-8000-00000000000a"
+ wcRclAgentB = "5c09e200-0000-4000-8000-00000000000b"
+ wcRclAgentArc = "5c09e200-0000-4000-8000-00000000000c"
+ wcRclInstall = "5c09e200-0000-4000-8000-000000000005"
+
+ wcRclBotRevoked = "bot_rcl_revoked"
+ wcRclBotLive = "bot_rcl_live"
+ wcRclBotArchived = "bot_rcl_archived"
+ wcRclBotSame = "bot_rcl_same"
+)
+
+func reclaimTestDB(t *testing.T) *pgxpool.Pool {
+ t.Helper()
+ dsn := os.Getenv("DATABASE_URL")
+ if dsn == "" {
+ dsn = "postgres://multica:multica@localhost:5432/multica?sslmode=disable"
+ }
+ ctx := context.Background()
+ pool, err := pgxpool.New(ctx, dsn)
+ if err != nil {
+ t.Skipf("no database: %v", err)
+ }
+ if err := pool.Ping(ctx); err != nil {
+ pool.Close()
+ t.Skipf("database not reachable: %v", err)
+ }
+ var present bool
+ if err := pool.QueryRow(ctx, "SELECT to_regclass('public.channel_installation') IS NOT NULL").Scan(&present); err != nil || !present {
+ pool.Close()
+ t.Skip("channel_installation not present (database not migrated)")
+ }
+ t.Cleanup(pool.Close)
+ return pool
+}
+
+func newReclaimSvc(t *testing.T, pool *pgxpool.Pool) *InstallationService {
+ t.Helper()
+ box, err := secretbox.New(make([]byte, secretbox.KeySize))
+ if err != nil {
+ t.Fatalf("secretbox.New: %v", err)
+ }
+ svc, err := NewInstallationService(db.New(pool), pool, box)
+ if err != nil {
+ t.Fatalf("NewInstallationService: %v", err)
+ }
+ return svc
+}
+
+func seedReclaimOwners(t *testing.T, ctx context.Context, pool *pgxpool.Pool) {
+ t.Helper()
+ exec := func(q string, args ...any) {
+ if _, err := pool.Exec(ctx, q, args...); err != nil {
+ t.Fatalf("seed reclaim owner: %v", err)
+ }
+ }
+ exec(`INSERT INTO workspace (id, name, slug, description) VALUES ($1, 'wecom reclaim', 'wecom-reclaim', '') ON CONFLICT (id) DO NOTHING`, wcRclWS)
+ exec(`INSERT INTO agent_runtime (id, workspace_id, name, runtime_mode, provider)
+VALUES ($1, $2, 'wecom reclaim runtime', 'local', 'multica_daemon') ON CONFLICT (id) DO NOTHING`, wcRclRuntime, wcRclWS)
+ for _, a := range []string{wcRclAgentA, wcRclAgentB} {
+ exec(`INSERT INTO agent (id, workspace_id, name, runtime_mode, runtime_id)
+VALUES ($1, $2, $3, 'local', $4) ON CONFLICT (id) DO NOTHING`, a, wcRclWS, "wecom reclaim "+a, wcRclRuntime)
+ }
+ exec(`INSERT INTO agent (id, workspace_id, name, runtime_mode, runtime_id, archived_at)
+VALUES ($1, $2, $3, 'local', $4, now()) ON CONFLICT (id) DO NOTHING`, wcRclAgentArc, wcRclWS, "wecom reclaim archived", wcRclRuntime)
+}
+
+func cleanReclaim(ctx context.Context, pool *pgxpool.Pool) {
+ apps := []string{wcRclBotRevoked, wcRclBotLive, wcRclBotArchived, wcRclBotSame}
+ _, _ = pool.Exec(ctx, `DELETE FROM channel_installation WHERE config->>'app_id' = ANY($1)`, apps)
+ _, _ = pool.Exec(ctx, `DELETE FROM workspace WHERE id = $1`, wcRclWS)
+}
+
+func uuid(t *testing.T, s string) pgtype.UUID {
+ t.Helper()
+ u, err := util.ParseUUID(s)
+ if err != nil {
+ t.Fatalf("parse uuid %s: %v", s, err)
+ }
+ return u
+}
+
+func insertWecomInstall(t *testing.T, ctx context.Context, pool *pgxpool.Pool, app, agent, status string) {
+ t.Helper()
+ if _, err := pool.Exec(ctx, `
+INSERT INTO channel_installation (workspace_id, agent_id, channel_type, config, installer_user_id, status)
+VALUES ($1, $2, 'wecom', jsonb_build_object('app_id', $3::text, 'bot_id', $3::text, 'app_secret_encrypted', ''), $4, $5)`,
+ wcRclWS, agent, app, wcRclInstall, status); err != nil {
+ t.Fatalf("insert install app=%s status=%s: %v", app, status, err)
+ }
+}
+
+func params(app, agent string) InstallationParams {
+ return InstallationParams{
+ WorkspaceID: mustUUID(wcRclWS),
+ AgentID: mustUUID(agent),
+ InstallerUserID: mustUUID(wcRclInstall),
+ BotID: app,
+ Secret: "s3cr3t",
+ }
+}
+
+func mustUUID(s string) pgtype.UUID {
+ u, _ := util.ParseUUID(s)
+ return u
+}
+
+func setupReclaim(t *testing.T) (context.Context, *pgxpool.Pool, *InstallationService) {
+ t.Helper()
+ pool := reclaimTestDB(t)
+ ctx := context.Background()
+ cleanReclaim(ctx, pool)
+ seedReclaimOwners(t, ctx, pool)
+ t.Cleanup(func() { cleanReclaim(ctx, pool) })
+ return ctx, pool, newReclaimSvc(t, pool)
+}
+
+// A revoked owner on a DIFFERENT agent must be reclaimed so the bot can move.
+func TestUpsert_TakesOverRevokedOwnerOnDifferentAgent(t *testing.T) {
+ ctx, pool, svc := setupReclaim(t)
+ insertWecomInstall(t, ctx, pool, wcRclBotRevoked, wcRclAgentA, "revoked")
+
+ got, err := svc.Upsert(ctx, params(wcRclBotRevoked, wcRclAgentB))
+ if err != nil {
+ t.Fatalf("takeover of a revoked owner should succeed, got: %v", err)
+ }
+ if got.AgentID != uuid(t, wcRclAgentB) {
+ t.Errorf("new owner agent = %v, want agent B", got.AgentID)
+ }
+ // The dead row for agent A must be gone (slot freed, not double-owned).
+ var n int
+ if err := pool.QueryRow(ctx, `SELECT count(*) FROM channel_installation WHERE config->>'app_id' = $1`, wcRclBotRevoked).Scan(&n); err != nil {
+ t.Fatalf("count: %v", err)
+ }
+ if n != 1 {
+ t.Errorf("expected exactly one row for the bot after takeover, got %d", n)
+ }
+}
+
+// A LIVE (active) owner on another agent must still be refused with an accurate
+// same-workspace conflict — reclaim must not steal a live slot.
+func TestUpsert_RefusesLiveOwnerOnDifferentAgent(t *testing.T) {
+ ctx, pool, svc := setupReclaim(t)
+ insertWecomInstall(t, ctx, pool, wcRclBotLive, wcRclAgentA, "active")
+
+ _, err := svc.Upsert(ctx, params(wcRclBotLive, wcRclAgentB))
+ if !errors.Is(err, ErrBotOwnedBySameWorkspace) {
+ t.Fatalf("live owner should be refused with ErrBotOwnedBySameWorkspace, got: %v", err)
+ }
+}
+
+// An ARCHIVED agent is still a live owner (not dead) — reclaim leaves it, and
+// the conflict is reported as the archived-agent case.
+func TestUpsert_RefusesArchivedOwner(t *testing.T) {
+ ctx, pool, svc := setupReclaim(t)
+ insertWecomInstall(t, ctx, pool, wcRclBotArchived, wcRclAgentArc, "active")
+
+ _, err := svc.Upsert(ctx, params(wcRclBotArchived, wcRclAgentB))
+ if !errors.Is(err, ErrBotOwnedByArchivedAgent) {
+ t.Fatalf("archived owner should be refused with ErrBotOwnedByArchivedAgent, got: %v", err)
+ }
+}
+
+// Reconnecting the same bot to the SAME agent is an in-place refresh, never a
+// conflict (it hits the (workspace, agent, channel_type) ON CONFLICT).
+func TestUpsert_SameAgentReconnectInPlace(t *testing.T) {
+ ctx, pool, svc := setupReclaim(t)
+ insertWecomInstall(t, ctx, pool, wcRclBotSame, wcRclAgentA, "revoked")
+
+ got, err := svc.Upsert(ctx, params(wcRclBotSame, wcRclAgentA))
+ if err != nil {
+ t.Fatalf("same-agent reconnect should succeed, got: %v", err)
+ }
+ if got.Status != InstallationActive {
+ t.Errorf("status after reconnect = %q, want active", got.Status)
+ }
+ var n int
+ if err := pool.QueryRow(ctx, `SELECT count(*) FROM channel_installation WHERE config->>'app_id' = $1`, wcRclBotSame).Scan(&n); err != nil {
+ t.Fatalf("count: %v", err)
+ }
+ if n != 1 {
+ t.Errorf("expected one row after in-place reconnect, got %d", n)
+ }
+}
diff --git a/server/internal/integrations/wecom/outbound.go b/server/internal/integrations/wecom/outbound.go
new file mode 100644
index 0000000000..36026ca774
--- /dev/null
+++ b/server/internal/integrations/wecom/outbound.go
@@ -0,0 +1,248 @@
+package wecom
+
+// outbound.go — the WeCom EventChatDone subscriber. After an agent finishes
+// producing a chat reply on the bus, this subscriber looks up the wecom
+// chat_session binding, resolves the live wsSender through the shared
+// registry, and pushes the reply back as aibot_send_msg. Mirrors
+// slack.Outbound; sessions with no wecom binding are ignored so it
+// coexists with Slack / Lark subscribers on the shared bus.
+//
+// Kept lean: aibot has no threading, no per-bot outbound REST, and no
+// mrkdwn conversion — the reply text goes through sendMsgTextBody the
+// same way OutboundReplier's messages do (markdown msgtype, which
+// renders plaintext without escaping).
+//
+// SINGLE-REPLICA CONSTRAINT: WeCom's only outbound path is the in-process
+// WebSocket held in the sendersRegistry, but EventChatDone / EventInboxNew are
+// dispatched on the in-process events.Bus. On a multi-replica deployment the
+// replica that publishes the event is not necessarily the one holding the
+// bot's WS lease, so senders.get() returns nil and the reply cannot be
+// delivered from here (Slack/Lark are immune — their outbound is stateless
+// HTTP any replica can perform). Until outbound is routed to the lease holder,
+// a WeCom-enabled backend must run as a single replica; boot emits a warning
+// when a multi-replica setup (REDIS_URL) is detected. See router.go.
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "log/slog"
+ "time"
+
+ "github.com/jackc/pgx/v5"
+ "github.com/jackc/pgx/v5/pgtype"
+
+ "github.com/multica-ai/multica/server/internal/events"
+ "github.com/multica-ai/multica/server/internal/integrations/channel"
+ "github.com/multica-ai/multica/server/internal/util"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+ "github.com/multica-ai/multica/server/pkg/protocol"
+)
+
+// outboundQueries is the slice of generated queries the WeCom outbound
+// subscriber needs. *db.Queries satisfies it.
+type outboundQueries interface {
+ GetChannelChatSessionBindingBySession(ctx context.Context, arg db.GetChannelChatSessionBindingBySessionParams) (db.ChannelChatSessionBinding, error)
+ GetChannelInstallation(ctx context.Context, arg db.GetChannelInstallationParams) (db.ChannelInstallation, error)
+ FindChannelBindingForMember(ctx context.Context, arg db.FindChannelBindingForMemberParams) (db.ChannelUserBinding, error)
+ GetWorkspace(ctx context.Context, id pgtype.UUID) (db.Workspace, error)
+}
+
+// Outbound delivers an agent's chat reply back to WeCom over the same
+// aibot WebSocket the inbound loop owns. Registered against the shared
+// event bus; sessions with no wecom binding are silently ignored.
+type Outbound struct {
+ q outboundQueries
+ senders *sendersRegistry
+ logger *slog.Logger
+}
+
+// NewOutbound builds the WeCom outbound subscriber. senders is the same
+// process-wide registry the wecom.ChannelDeps and OutboundReplier were
+// built with — reply delivery goes through the live wsSender for the
+// binding's installation, so a session whose Supervisor lost the lease
+// mid-flight silently drops rather than opening a second connection.
+func NewOutbound(q outboundQueries, senders *sendersRegistry, logger *slog.Logger) *Outbound {
+ if logger == nil {
+ logger = slog.Default()
+ }
+ return &Outbound{q: q, senders: senders, logger: logger}
+}
+
+// Register subscribes to the chat-done event on the bus.
+func (o *Outbound) Register(bus *events.Bus) {
+ bus.Subscribe(protocol.EventChatDone, o.handleEvent)
+ // Inbox notifications delivered through the smart bot: when the
+ // recipient member has a WeCom binding with a live connection, their
+ // inbox:new items are pushed to the aibot as a markdown card.
+ bus.Subscribe(protocol.EventInboxNew, o.handleInboxNew)
+}
+
+func (o *Outbound) handleEvent(e events.Event) {
+ // Bus delivery is synchronous — a stuck WS write must not wedge the
+ // publish call site. Fresh ctx with a tight timeout, same as Slack.
+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
+ defer cancel()
+ if err := o.processEvent(ctx, e); err != nil {
+ o.logger.WarnContext(ctx, "wecom outbound: reply delivery failed",
+ "error", err, "chat_session_id", e.ChatSessionID)
+ }
+}
+
+func (o *Outbound) processEvent(ctx context.Context, e events.Event) error {
+ sessionID, err := util.ParseUUID(e.ChatSessionID)
+ if err != nil || !sessionID.Valid {
+ // Issue / autopilot tasks carry no chat_session.
+ return nil
+ }
+ binding, err := o.q.GetChannelChatSessionBindingBySession(ctx, db.GetChannelChatSessionBindingBySessionParams{
+ ChatSessionID: sessionID,
+ ChannelType: channelTypeWecom,
+ })
+ if err != nil {
+ if errors.Is(err, pgx.ErrNoRows) {
+ return nil // not a wecom session (Slack / Lark / web-only)
+ }
+ return fmt.Errorf("wecom: lookup chat binding: %w", err)
+ }
+ content := chatDoneContent(e.Payload)
+ if content == "" {
+ return nil // nothing to say (empty completion)
+ }
+ inst, err := o.q.GetChannelInstallation(ctx, db.GetChannelInstallationParams{
+ ID: binding.InstallationID,
+ ChannelType: channelTypeWecom,
+ })
+ if err != nil {
+ return fmt.Errorf("wecom: load installation: %w", err)
+ }
+ if inst.Status != string(InstallationActive) {
+ return nil // revoked between trigger and reply
+ }
+ if o.senders == nil {
+ return errors.New("wecom: sender registry not configured")
+ }
+ sender := o.senders.get(inst.ID)
+ if sender == nil {
+ // No live WS for this installation on this replica. Two causes:
+ // (1) the Supervisor lost the lease or is mid-reconnect — transient,
+ // and the user's next inbound message reaches the reconnected loop;
+ // (2) on a multi-replica deployment the lease is held by a DIFFERENT
+ // replica than the one that published this event, so it can never be
+ // delivered from here (see the single-replica constraint in this
+ // file's header). Either way, buffering is wrong — the reply is stale
+ // by the time a socket returns — so we surface it to the caller's WARN
+ // rather than drop it silently.
+ return errors.New("wecom: connection not ready on this replica")
+ }
+ chatType := aibotChatTypeFromChannel(channel.ChatType(binding.ChatType))
+ return sender.sendText(binding.ChannelChatID, chatType, content)
+}
+
+// chatDoneContent extracts the reply text from an EventChatDone payload
+// (the typed payload, or its map form after a serialization round trip).
+func chatDoneContent(payload any) string {
+ switch p := payload.(type) {
+ case protocol.ChatDonePayload:
+ return p.Content
+ case map[string]any:
+ if s, ok := p["content"].(string); ok {
+ return s
+ }
+ }
+ return ""
+}
+
+// handleInboxNew is the inbox:new subscriber that delivers a member
+// notification via the smart bot. When the recipient member has a WeCom
+// binding with a live connection, the notification is pushed to the aibot.
+// On any miss — non-member recipient, no wecom binding, no live sender,
+// send failure — the handler is a no-op and the member simply receives the
+// notification through the in-app inbox as usual.
+func (o *Outbound) handleInboxNew(e events.Event) {
+ payload, ok := e.Payload.(map[string]any)
+ if !ok {
+ return
+ }
+ item, ok := payload["item"].(map[string]any)
+ if !ok {
+ return
+ }
+ // Only member recipients — agents receive nothing via chat channels.
+ if rt, _ := item["recipient_type"].(string); rt != "member" {
+ return
+ }
+ recipientIDStr, _ := item["recipient_id"].(string)
+ workspaceIDStr, _ := item["workspace_id"].(string)
+ if recipientIDStr == "" || workspaceIDStr == "" {
+ return
+ }
+
+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
+ defer cancel()
+
+ o.tryDeliverInbox(ctx, item, recipientIDStr, workspaceIDStr)
+}
+
+// tryDeliverInbox is the delivery core. Returns true iff the bot pushed
+// the notification.
+func (o *Outbound) tryDeliverInbox(ctx context.Context, item map[string]any, recipientIDStr, workspaceIDStr string) bool {
+ recipientID, err := util.ParseUUID(recipientIDStr)
+ if err != nil || !recipientID.Valid {
+ return false
+ }
+ workspaceID, err := util.ParseUUID(workspaceIDStr)
+ if err != nil || !workspaceID.Valid {
+ return false
+ }
+ binding, err := o.q.FindChannelBindingForMember(ctx, db.FindChannelBindingForMemberParams{
+ WorkspaceID: workspaceID,
+ MulticaUserID: recipientID,
+ ChannelType: channelTypeWecom,
+ })
+ if err != nil {
+ if !errors.Is(err, pgx.ErrNoRows) {
+ o.logger.WarnContext(ctx, "wecom outbound: lookup member binding failed",
+ "error", err, "workspace_id", workspaceIDStr, "recipient_id", recipientIDStr)
+ }
+ return false // no binding → nothing to deliver via bot
+ }
+ if o.senders == nil {
+ return false
+ }
+ sender := o.senders.get(binding.InstallationID)
+ if sender == nil {
+ return false // supervisor down or reconnecting — no live connection
+ }
+
+ // Resolve slug for the link. Best-effort — a missing slug just falls
+ // back to the workspace UUID in the URL.
+ slug := ""
+ if ws, err := o.q.GetWorkspace(ctx, workspaceID); err == nil {
+ slug = ws.Slug
+ }
+ content := buildInboxMarkdown(item, workspaceIDStr, slug)
+ if content == "" {
+ return false
+ }
+ // Smart-bot inbox notifications are 1:1 pushes to the bound user. The
+ // binding row's channel_user_id is the bot-scoped T-* userid — WeCom
+ // treats that as the chatid for a single (chat_type=1) send.
+ if err := sender.sendText(binding.ChannelUserID, chatTypeSingleInt, content); err != nil {
+ o.logger.WarnContext(ctx, "wecom outbound: inbox push failed",
+ "error", err, "installation_id", uuidStringPub(binding.InstallationID),
+ "recipient_id", recipientIDStr)
+ return false // send failed → no bot delivery
+ }
+ o.logger.DebugContext(ctx, "wecom outbound: inbox delivered via bot",
+ "installation_id", uuidStringPub(binding.InstallationID),
+ "recipient_id", recipientIDStr,
+ "inbox_type", item["type"])
+ return true
+}
+
+// uuidStringPub renders a pgtype.UUID for a log line without depending on
+// engine.uuidString (a different package).
+func uuidStringPub(u pgtype.UUID) string {
+ return util.UUIDToString(u)
+}
diff --git a/server/internal/integrations/wecom/outbound_test.go b/server/internal/integrations/wecom/outbound_test.go
new file mode 100644
index 0000000000..7794d6678b
--- /dev/null
+++ b/server/internal/integrations/wecom/outbound_test.go
@@ -0,0 +1,205 @@
+package wecom
+
+// outbound_test.go — the EventChatDone reply path and the inbox:new delivery
+// path, both driven through a fake outboundQueries (the interface Outbound
+// depends on) and a recording wsConn, so no database is required. These are
+// the paths that put an agent's words back in front of the WeCom user, and
+// the "deliver via bot only when bound" contract the inbox notification rests
+// on.
+//
+// Original inbox-delivery design and review: seacen (PR #5833).
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "log/slog"
+ "testing"
+
+ "github.com/jackc/pgx/v5"
+ "github.com/jackc/pgx/v5/pgtype"
+
+ "github.com/multica-ai/multica/server/internal/events"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+ "github.com/multica-ai/multica/server/pkg/protocol"
+)
+
+// fakeOutboundQueries is an in-memory stand-in for the four queries Outbound
+// uses. A nil error field returns the row; a non-nil one is returned as-is
+// (use pgx.ErrNoRows to exercise the "not a wecom session" / "no binding"
+// branches).
+type fakeOutboundQueries struct {
+ sessionBinding db.ChannelChatSessionBinding
+ sessionErr error
+ installation db.ChannelInstallation
+ installErr error
+ memberBinding db.ChannelUserBinding
+ memberErr error
+ workspace db.Workspace
+ workspaceErr error
+}
+
+func (f *fakeOutboundQueries) GetChannelChatSessionBindingBySession(context.Context, db.GetChannelChatSessionBindingBySessionParams) (db.ChannelChatSessionBinding, error) {
+ return f.sessionBinding, f.sessionErr
+}
+func (f *fakeOutboundQueries) GetChannelInstallation(context.Context, db.GetChannelInstallationParams) (db.ChannelInstallation, error) {
+ return f.installation, f.installErr
+}
+func (f *fakeOutboundQueries) FindChannelBindingForMember(context.Context, db.FindChannelBindingForMemberParams) (db.ChannelUserBinding, error) {
+ return f.memberBinding, f.memberErr
+}
+func (f *fakeOutboundQueries) GetWorkspace(context.Context, pgtype.UUID) (db.Workspace, error) {
+ return f.workspace, f.workspaceErr
+}
+
+func newOutboundWithConn(t *testing.T, q outboundQueries) (*Outbound, pgtype.UUID, *recordingConn) {
+ t.Helper()
+ reg := newSendersRegistry()
+ instID := mustTestUUID(t)
+ conn := &recordingConn{}
+ reg.set(instID, newWSSender(conn, nil))
+ return NewOutbound(q, reg, slog.Default()), instID, conn
+}
+
+func TestProcessEvent_DeliversChatReplyToBoundChat(t *testing.T) {
+ t.Parallel()
+ q := &fakeOutboundQueries{
+ sessionBinding: db.ChannelChatSessionBinding{ChannelChatID: "CHAT_1", ChatType: "group"},
+ installation: db.ChannelInstallation{Status: string(InstallationActive)},
+ }
+ o, instID, conn := newOutboundWithConn(t, q)
+ q.sessionBinding.InstallationID = instID
+ q.installation.ID = instID
+
+ err := o.processEvent(context.Background(), events.Event{
+ ChatSessionID: "22222222-2222-2222-2222-222222222222",
+ Payload: protocol.ChatDonePayload{Content: "the agent reply"},
+ })
+ if err != nil {
+ t.Fatalf("processEvent: %v", err)
+ }
+ body := conn.sendBody(t, 0)
+ if body["chatid"] != "CHAT_1" {
+ t.Errorf("reply chatid = %v, want CHAT_1", body["chatid"])
+ }
+ if body["chat_type"] != float64(chatTypeGroupInt) {
+ t.Errorf("reply chat_type = %v, want group", body["chat_type"])
+ }
+ md, _ := body["markdown"].(map[string]any)
+ if md == nil || md["content"] != "the agent reply" {
+ t.Errorf("reply content = %v, want the agent reply", body["markdown"])
+ }
+}
+
+func TestProcessEvent_NonWecomSessionIsNoop(t *testing.T) {
+ t.Parallel()
+ q := &fakeOutboundQueries{sessionErr: pgx.ErrNoRows}
+ o, _, conn := newOutboundWithConn(t, q)
+ if err := o.processEvent(context.Background(), events.Event{ChatSessionID: "22222222-2222-2222-2222-222222222222", Payload: protocol.ChatDonePayload{Content: "x"}}); err != nil {
+ t.Fatalf("processEvent: %v", err)
+ }
+ if len(conn.frames) != 0 {
+ t.Errorf("expected no send for a non-wecom session, got %d frames", len(conn.frames))
+ }
+}
+
+func TestProcessEvent_EmptyContentIsNoop(t *testing.T) {
+ t.Parallel()
+ q := &fakeOutboundQueries{sessionBinding: db.ChannelChatSessionBinding{ChannelChatID: "CHAT_1"}}
+ o, instID, conn := newOutboundWithConn(t, q)
+ q.sessionBinding.InstallationID = instID
+ if err := o.processEvent(context.Background(), events.Event{ChatSessionID: "22222222-2222-2222-2222-222222222222", Payload: protocol.ChatDonePayload{Content: ""}}); err != nil {
+ t.Fatalf("processEvent: %v", err)
+ }
+ if len(conn.frames) != 0 {
+ t.Errorf("empty completion should send nothing, got %d frames", len(conn.frames))
+ }
+}
+
+func TestProcessEvent_RevokedInstallationIsNoop(t *testing.T) {
+ t.Parallel()
+ q := &fakeOutboundQueries{
+ sessionBinding: db.ChannelChatSessionBinding{ChannelChatID: "CHAT_1"},
+ installation: db.ChannelInstallation{Status: "revoked"},
+ }
+ o, instID, conn := newOutboundWithConn(t, q)
+ q.sessionBinding.InstallationID = instID
+ q.installation.ID = instID
+ if err := o.processEvent(context.Background(), events.Event{ChatSessionID: "22222222-2222-2222-2222-222222222222", Payload: protocol.ChatDonePayload{Content: "hi"}}); err != nil {
+ t.Fatalf("processEvent: %v", err)
+ }
+ if len(conn.frames) != 0 {
+ t.Errorf("revoked installation should send nothing, got %d frames", len(conn.frames))
+ }
+}
+
+func TestTryDeliverInbox_PushesToBoundMemberPrivately(t *testing.T) {
+ t.Parallel()
+ q := &fakeOutboundQueries{
+ memberBinding: db.ChannelUserBinding{ChannelUserID: "T_USER_1"},
+ workspace: db.Workspace{Slug: "acme"},
+ }
+ o, instID, conn := newOutboundWithConn(t, q)
+ q.memberBinding.InstallationID = instID
+
+ item := map[string]any{
+ "recipient_type": "member",
+ "recipient_id": "33333333-3333-3333-3333-333333333333",
+ "workspace_id": "44444444-4444-4444-4444-444444444444",
+ "type": "issue_assigned",
+ "title": "New issue",
+ }
+ if !o.tryDeliverInbox(context.Background(), item, "33333333-3333-3333-3333-333333333333", "44444444-4444-4444-4444-444444444444") {
+ t.Fatal("tryDeliverInbox returned false; expected delivery to a bound member")
+ }
+ body := conn.sendBody(t, 0)
+ if body["chatid"] != "T_USER_1" {
+ t.Errorf("inbox push chatid = %v, want the member's bound userid", body["chatid"])
+ }
+ if body["chat_type"] != float64(chatTypeSingleInt) {
+ t.Errorf("inbox push chat_type = %v, want single (1)", body["chat_type"])
+ }
+}
+
+func TestTryDeliverInbox_NoBindingIsNoop(t *testing.T) {
+ t.Parallel()
+ q := &fakeOutboundQueries{memberErr: pgx.ErrNoRows}
+ o, _, conn := newOutboundWithConn(t, q)
+ if o.tryDeliverInbox(context.Background(), map[string]any{}, "33333333-3333-3333-3333-333333333333", "44444444-4444-4444-4444-444444444444") {
+ t.Error("expected false when the member has no wecom binding")
+ }
+ if len(conn.frames) != 0 {
+ t.Errorf("no binding should push nothing, got %d frames", len(conn.frames))
+ }
+}
+
+func TestHandleInboxNew_IgnoresNonMemberRecipient(t *testing.T) {
+ t.Parallel()
+ // memberErr set so that if it somehow reached the query it would no-op;
+ // the recipient_type guard should return before any query.
+ q := &fakeOutboundQueries{memberErr: errors.New("must not be called")}
+ o, _, conn := newOutboundWithConn(t, q)
+ o.handleInboxNew(events.Event{Payload: map[string]any{
+ "item": map[string]any{"recipient_type": "agent", "recipient_id": "x", "workspace_id": "y"},
+ }})
+ if len(conn.frames) != 0 {
+ t.Errorf("agent recipient should not be pushed to, got %d frames", len(conn.frames))
+ }
+}
+
+func TestChatDoneContent(t *testing.T) {
+ t.Parallel()
+ if got := chatDoneContent(protocol.ChatDonePayload{Content: "typed"}); got != "typed" {
+ t.Errorf("typed payload = %q, want typed", got)
+ }
+ roundTripped := map[string]any{"content": "mapped"}
+ if got := chatDoneContent(roundTripped); got != "mapped" {
+ t.Errorf("map payload = %q, want mapped", got)
+ }
+ if got := chatDoneContent(map[string]any{"other": 1}); got != "" {
+ t.Errorf("payload without content = %q, want empty", got)
+ }
+ if got := chatDoneContent(json.RawMessage(`{}`)); got != "" {
+ t.Errorf("unknown payload type = %q, want empty", got)
+ }
+}
diff --git a/server/internal/integrations/wecom/replier.go b/server/internal/integrations/wecom/replier.go
new file mode 100644
index 0000000000..2fd3687289
--- /dev/null
+++ b/server/internal/integrations/wecom/replier.go
@@ -0,0 +1,226 @@
+package wecom
+
+// replier.go — the WeCom OutboundReplier. Handles the engine's needs_binding
+// / agent_offline / agent_archived / issue_created outcomes by sending a
+// text message back over the same aibot WebSocket the inbound loop owns
+// (aibot has no REST outbound; every write is on the socket, looked up via
+// the sendersRegistry).
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "log/slog"
+ "net/url"
+ "strings"
+
+ "github.com/jackc/pgx/v5/pgtype"
+
+ "github.com/multica-ai/multica/server/internal/integrations/channel"
+ "github.com/multica-ai/multica/server/internal/integrations/channel/engine"
+ "github.com/multica-ai/multica/server/internal/util"
+)
+
+const (
+ agentOfflineText = "⚠️ 智能体当前不在线,你的消息已收到,等它上线后会处理。"
+ agentArchivedText = "⚠️ 该智能体已归档,无法回复。请联系工作区管理员。"
+)
+
+// OutboundReplier implements engine.OutboundReplier for WeCom.
+type OutboundReplier struct {
+ binding binder
+ senders *sendersRegistry
+ appURL string
+ bindingPath string
+ logger *slog.Logger
+}
+
+// binder is the slice of BindingTokenService sendBindingPrompt needs, declared
+// as an interface so the group-vs-private routing can be exercised with a fake
+// (no DB-backed token mint). *BindingTokenService is the production value.
+type binder interface {
+ Mint(ctx context.Context, workspaceID, installationID pgtype.UUID, wecomUserID string) (BindingToken, error)
+}
+
+// OutboundReplierConfig configures the replier. Binding + AppURL are
+// required for the needs_binding prompt to work; without them the prompt
+// is skipped (the offline/archived/issue notices still fire).
+type OutboundReplierConfig struct {
+ Binding *BindingTokenService
+
+ // Senders is the same sendersRegistry the wecom ChannelDeps was built
+ // with. The replier looks up the live wsSender by installation id.
+ Senders *sendersRegistry
+
+ // AppURL is the Multica web app host the user clicks into to redeem
+ // the binding token (e.g. https://multica.example). It comes from
+ // MULTICA_APP_URL (falling back to FRONTEND_ORIGIN) and is
+ // intentionally separate from MULTICA_PUBLIC_URL, which is the
+ // backend/API URL — the bind page (/wecom/bind) is served by the web
+ // app, so the link must point at the app host.
+ AppURL string
+ BindingPath string // default "/wecom/bind"
+ Logger *slog.Logger
+}
+
+var _ engine.OutboundReplier = (*OutboundReplier)(nil)
+
+// NewOutboundReplier builds the replier.
+func NewOutboundReplier(cfg OutboundReplierConfig) *OutboundReplier {
+ logger := cfg.Logger
+ if logger == nil {
+ logger = slog.Default()
+ }
+ bindingPath := cfg.BindingPath
+ if bindingPath == "" {
+ bindingPath = "/wecom/bind"
+ }
+ if !strings.HasPrefix(bindingPath, "/") {
+ bindingPath = "/" + bindingPath
+ }
+ r := &OutboundReplier{
+ senders: cfg.Senders,
+ appURL: strings.TrimRight(cfg.AppURL, "/"),
+ bindingPath: bindingPath,
+ logger: logger,
+ }
+ // Assign through the interface only when non-nil: a nil *BindingTokenService
+ // stored in the binder interface would be a non-nil interface value holding
+ // a typed nil, defeating the `r.binding == nil` guard in sendBindingPrompt
+ // and panicking on Mint.
+ if cfg.Binding != nil {
+ r.binding = cfg.Binding
+ }
+ return r
+}
+
+// Reply routes each outcome to its user-visible message. Errors are
+// logged, not propagated: the replier runs detached from the inbound ACK
+// path (the engine.Router owns that goroutine).
+func (r *OutboundReplier) Reply(ctx context.Context, inst engine.ResolvedInstallation, msg channel.InboundMessage, res engine.Result) {
+ switch res.Outcome {
+ case engine.OutcomeNeedsBinding:
+ if err := r.sendBindingPrompt(ctx, inst, msg, res); err != nil {
+ r.logger.WarnContext(ctx, "wecom replier: binding prompt failed",
+ "installation_id", util.UUIDToString(inst.ID), "error", err)
+ }
+ case engine.OutcomeAgentOffline:
+ if err := r.post(ctx, inst, msg, agentOfflineText); err != nil {
+ r.logger.WarnContext(ctx, "wecom replier: offline notice failed",
+ "installation_id", util.UUIDToString(inst.ID), "error", err)
+ }
+ case engine.OutcomeAgentArchived:
+ if err := r.post(ctx, inst, msg, agentArchivedText); err != nil {
+ r.logger.WarnContext(ctx, "wecom replier: archived notice failed",
+ "installation_id", util.UUIDToString(inst.ID), "error", err)
+ }
+ case engine.OutcomeIngested:
+ // Only a /issue-created message warrants a confirmation; a plain
+ // chat message stays silent (the agent's own reply lands via
+ // EventChatDone / Channel.Send).
+ if res.IssueID.Valid {
+ if err := r.post(ctx, inst, msg, issueCreatedText(res)); err != nil {
+ r.logger.WarnContext(ctx, "wecom replier: issue-created confirmation failed",
+ "installation_id", util.UUIDToString(inst.ID), "error", err)
+ }
+ }
+ }
+}
+
+func (r *OutboundReplier) sendBindingPrompt(ctx context.Context, inst engine.ResolvedInstallation, msg channel.InboundMessage, res engine.Result) error {
+ sender := res.Sender
+ if sender == "" {
+ sender = msg.Source.SenderID
+ }
+ if sender == "" {
+ return errors.New("wecom: missing sender id")
+ }
+ if r.binding == nil {
+ return errors.New("wecom: binding service not configured")
+ }
+ if r.appURL == "" {
+ return errors.New("wecom: app url not configured")
+ }
+ token, err := r.binding.Mint(ctx, inst.WorkspaceID, inst.ID, sender)
+ if err != nil {
+ return fmt.Errorf("wecom: mint binding token: %w", err)
+ }
+ bindURL := r.appURL + r.bindingPath + "?token=" + url.QueryEscape(token.Raw)
+ text := "👋 请先绑定你的 Multica 账号,才能与我对话:\n" + bindURL + "\n(链接 15 分钟内有效)"
+ // A binding token is a bearer credential: binding.Redeem only checks that
+ // the redeemer belongs to the token's workspace, and the bind page redeems
+ // on load as whoever is signed in. Sending it to msg.Source.ChatID — which
+ // in a group IS the group — would let any member click first and bind the
+ // sender's WeCom userid to their own Multica account, after which the
+ // sender's messages (/issue included) resolve to the hijacker. So deliver
+ // the link privately to the sender's own userid with chat_type=1 (the same
+ // address outbound.go uses for inbox pushes), never to the room. Lark's
+ // SendBindingPromptCard targets the sender's OpenID for the same reason.
+ if err := r.postPrivate(inst, sender, text); err != nil {
+ return err
+ }
+ // A group trigger still needs an answer — silence reads as a broken bot —
+ // but a token-less one that names nobody. Posted only after the private
+ // send is accepted, so the room is never pointed at a message the wire
+ // refused. A 1:1 trigger already received the prompt in its only room.
+ if aibotChatTypeFromChannel(msg.Source.ChatType) == chatTypeGroupInt {
+ return r.post(ctx, inst, msg, "👋 已把绑定链接私发给你,请在与我的单聊里点击完成绑定。")
+ }
+ return nil
+}
+
+// postPrivate delivers text to a single user's 1:1 chat (chat_type=1),
+// regardless of which room triggered the message. Used for bearer-credential
+// content (the binding link) that must never land in a group.
+func (r *OutboundReplier) postPrivate(inst engine.ResolvedInstallation, userID, text string) error {
+ if r.senders == nil {
+ return errors.New("wecom: sender registry not configured")
+ }
+ if !inst.ID.Valid {
+ return errors.New("wecom: installation id is zero")
+ }
+ if userID == "" {
+ return errors.New("wecom: missing user id")
+ }
+ sender := r.senders.get(inst.ID)
+ if sender == nil {
+ return errors.New("wecom: connection not ready")
+ }
+ return sender.sendText(userID, chatTypeSingleInt, text)
+}
+
+// post looks up the installation's live wsSender in the registry and
+// pushes aibot_send_msg with the given text. Returns "connection not
+// ready" when the Supervisor has no active connection (mid-reconnect
+// after lease flip, or right after Revoke).
+func (r *OutboundReplier) post(ctx context.Context, inst engine.ResolvedInstallation, msg channel.InboundMessage, text string) error {
+ _ = ctx
+ if r.senders == nil {
+ return errors.New("wecom: sender registry not configured")
+ }
+ if !inst.ID.Valid {
+ return errors.New("wecom: installation id is zero")
+ }
+ sender := r.senders.get(inst.ID)
+ if sender == nil {
+ return errors.New("wecom: connection not ready")
+ }
+ chatID := msg.Source.ChatID
+ if chatID == "" {
+ return errors.New("wecom: missing chat_id")
+ }
+ chatType := aibotChatTypeFromChannel(msg.Source.ChatType)
+ return sender.sendText(chatID, chatType, text)
+}
+
+func issueCreatedText(res engine.Result) string {
+ id := res.IssueIdentifier
+ if id == "" {
+ id = fmt.Sprintf("#%d", res.IssueNumber)
+ }
+ title := strings.TrimSpace(res.IssueTitle)
+ if title == "" {
+ return "✅ 已创建 " + id
+ }
+ return "✅ 已创建 " + id + " — " + title
+}
diff --git a/server/internal/integrations/wecom/replier_test.go b/server/internal/integrations/wecom/replier_test.go
new file mode 100644
index 0000000000..f55e5a188a
--- /dev/null
+++ b/server/internal/integrations/wecom/replier_test.go
@@ -0,0 +1,230 @@
+package wecom
+
+// replier_test.go — the security fix for the group-chat binding-token leak. A
+// binding token is a bearer credential, so it must go to the sender privately
+// (chat_type=1), never to the group room in Source.ChatID. The key test drives
+// the real sendBindingPrompt group branch (via a fake binder, so no DB-backed
+// token mint) and asserts the token reaches only the sender and no
+// group-addressed frame carries it. The postPrivate / post primitives are
+// checked separately below.
+//
+// Original defect report and analysis: seacen (PR #5833 review).
+
+import (
+ "context"
+ "encoding/json"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/jackc/pgx/v5/pgtype"
+
+ "github.com/multica-ai/multica/server/internal/integrations/channel"
+ "github.com/multica-ai/multica/server/internal/integrations/channel/engine"
+)
+
+// fakeBinder mints a fixed, recognizable raw token without touching a DB.
+type fakeBinder struct{ raw string }
+
+func (f fakeBinder) Mint(context.Context, pgtype.UUID, pgtype.UUID, string) (BindingToken, error) {
+ return BindingToken{Raw: f.raw, ExpiresAt: time.Now().Add(15 * time.Minute)}, nil
+}
+
+// recordingConn captures every frame written to it so a test can inspect the
+// aibot_send_msg body (chatid + chat_type) without a real socket.
+type recordingConn struct {
+ mu sync.Mutex
+ frames []frameEnvelope
+}
+
+func (c *recordingConn) WriteMessage(_ int, data []byte) error {
+ var env frameEnvelope
+ if err := json.Unmarshal(data, &env); err != nil {
+ return err
+ }
+ c.mu.Lock()
+ c.frames = append(c.frames, env)
+ c.mu.Unlock()
+ return nil
+}
+func (c *recordingConn) ReadMessage() (int, []byte, error) { return 0, nil, nil }
+func (c *recordingConn) SetReadDeadline(time.Time) error { return nil }
+func (c *recordingConn) SetWriteDeadline(time.Time) error { return nil }
+func (c *recordingConn) Close() error { return nil }
+
+// sendBody decodes the body of the i-th recorded aibot_send_msg frame.
+func (c *recordingConn) sendBody(t *testing.T, i int) map[string]any {
+ t.Helper()
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ if i >= len(c.frames) {
+ t.Fatalf("frame %d not recorded (have %d)", i, len(c.frames))
+ }
+ var body map[string]any
+ if err := json.Unmarshal(c.frames[i].Body, &body); err != nil {
+ t.Fatalf("decode body: %v", err)
+ }
+ return body
+}
+
+func newReplierWithConn(t *testing.T) (*OutboundReplier, engine.ResolvedInstallation, *recordingConn) {
+ t.Helper()
+ reg := newSendersRegistry()
+ inst := engine.ResolvedInstallation{ID: mustTestUUID(t)}
+ conn := &recordingConn{}
+ reg.set(inst.ID, newWSSender(conn, nil))
+ r := NewOutboundReplier(OutboundReplierConfig{Senders: reg, AppURL: "https://multica.example"})
+ return r, inst, conn
+}
+
+func TestPostPrivate_AddressesUserWithSingleChatType(t *testing.T) {
+ t.Parallel()
+ r, inst, conn := newReplierWithConn(t)
+
+ const senderUserID = "SENDER_USERID"
+ const secretURL = "https://multica.example/wecom/bind?token=SECRET_TOKEN"
+ if err := r.postPrivate(inst, senderUserID, secretURL); err != nil {
+ t.Fatalf("postPrivate: %v", err)
+ }
+
+ body := conn.sendBody(t, 0)
+ if body["chatid"] != senderUserID {
+ t.Errorf("private send chatid = %v, want the sender's own userid %q", body["chatid"], senderUserID)
+ }
+ // chat_type round-trips through JSON as float64.
+ if body["chat_type"] != float64(chatTypeSingleInt) {
+ t.Errorf("private send chat_type = %v, want %d (single)", body["chat_type"], chatTypeSingleInt)
+ }
+}
+
+// TestPost_AddressesRoom is the contrast: the ordinary reply path targets the
+// message's Source.ChatID (the group in a group chat). This is exactly why the
+// binding token must NOT go through here — it would land in the room.
+func TestPost_AddressesRoomChatID(t *testing.T) {
+ t.Parallel()
+ r, inst, conn := newReplierWithConn(t)
+
+ msg := channel.InboundMessage{Source: channel.Source{
+ ChatID: "GROUP_CHAT_ID",
+ ChatType: channel.ChatTypeGroup,
+ SenderID: "SENDER_USERID",
+ }}
+ if err := r.post(nil, inst, msg, "a token-less line"); err != nil {
+ t.Fatalf("post: %v", err)
+ }
+
+ body := conn.sendBody(t, 0)
+ if body["chatid"] != "GROUP_CHAT_ID" {
+ t.Errorf("group reply chatid = %v, want the group chatid", body["chatid"])
+ }
+ if body["chat_type"] != float64(chatTypeGroupInt) {
+ t.Errorf("group reply chat_type = %v, want %d (group)", body["chat_type"], chatTypeGroupInt)
+ }
+}
+
+// TestSendBindingPrompt_GroupNeverLeaksToken drives the REAL sendBindingPrompt
+// group branch — the single line the whole #1 fix rests on. It asserts the
+// token-bearing frame goes only to the sender at chat_type=1, the group gets a
+// token-less acknowledgement, and NO group-addressed frame carries the raw
+// token. Re-pointing sendBindingPrompt at post() (the pre-fix bug) fails this.
+func TestSendBindingPrompt_GroupNeverLeaksToken(t *testing.T) {
+ t.Parallel()
+ const rawToken = "SECRET_BEARER_TOKEN_do_not_leak"
+ const senderID = "SENDER_USERID"
+ const groupID = "GROUP_CHAT_ID"
+
+ reg := newSendersRegistry()
+ inst := engine.ResolvedInstallation{ID: mustTestUUID(t)}
+ conn := &recordingConn{}
+ reg.set(inst.ID, newWSSender(conn, nil))
+ r := NewOutboundReplier(OutboundReplierConfig{
+ Binding: nil, // set the interface field directly with the fake below
+ Senders: reg,
+ AppURL: "https://multica.example",
+ })
+ r.binding = fakeBinder{raw: rawToken}
+
+ msg := channel.InboundMessage{Source: channel.Source{
+ ChatID: groupID,
+ ChatType: channel.ChatTypeGroup,
+ SenderID: senderID,
+ }}
+ if err := r.sendBindingPrompt(context.Background(), inst, msg, engine.Result{Sender: senderID}); err != nil {
+ t.Fatalf("sendBindingPrompt: %v", err)
+ }
+
+ conn.mu.Lock()
+ frames := append([]frameEnvelope(nil), conn.frames...)
+ conn.mu.Unlock()
+ if len(frames) != 2 {
+ t.Fatalf("expected 2 frames (private token + group ack), got %d", len(frames))
+ }
+
+ tokenFrames, groupFrames := 0, 0
+ for i := range frames {
+ var body map[string]any
+ if err := json.Unmarshal(frames[i].Body, &body); err != nil {
+ t.Fatalf("decode frame %d: %v", i, err)
+ }
+ content := ""
+ if md, ok := body["markdown"].(map[string]any); ok {
+ content, _ = md["content"].(string)
+ }
+ carriesToken := strings.Contains(content, rawToken)
+ chatID, _ := body["chatid"].(string)
+
+ if chatID == groupID {
+ groupFrames++
+ if carriesToken {
+ t.Errorf("SECURITY: a group-addressed frame carries the raw token: %q", content)
+ }
+ if body["chat_type"] != float64(chatTypeGroupInt) {
+ t.Errorf("group frame chat_type = %v, want group", body["chat_type"])
+ }
+ }
+ if carriesToken {
+ tokenFrames++
+ if chatID != senderID {
+ t.Errorf("SECURITY: token frame addressed to %q, want the sender %q", chatID, senderID)
+ }
+ if body["chat_type"] != float64(chatTypeSingleInt) {
+ t.Errorf("token frame chat_type = %v, want single (1)", body["chat_type"])
+ }
+ }
+ }
+ if tokenFrames != 1 {
+ t.Errorf("expected exactly one token-bearing frame (the private send), got %d", tokenFrames)
+ }
+ if groupFrames != 1 {
+ t.Errorf("expected exactly one group acknowledgement frame, got %d", groupFrames)
+ }
+}
+
+// TestSendBindingPrompt_P2PSendsOnlyPrivately: a 1:1 trigger already IS the
+// private chat, so exactly one frame (the token) goes out, no group ack.
+func TestSendBindingPrompt_P2PSendsOnlyPrivately(t *testing.T) {
+ t.Parallel()
+ const rawToken = "P2P_TOKEN"
+ reg := newSendersRegistry()
+ inst := engine.ResolvedInstallation{ID: mustTestUUID(t)}
+ conn := &recordingConn{}
+ reg.set(inst.ID, newWSSender(conn, nil))
+ r := NewOutboundReplier(OutboundReplierConfig{Senders: reg, AppURL: "https://multica.example"})
+ r.binding = fakeBinder{raw: rawToken}
+
+ msg := channel.InboundMessage{Source: channel.Source{ChatID: "USER_A", ChatType: channel.ChatTypeP2P, SenderID: "USER_A"}}
+ if err := r.sendBindingPrompt(context.Background(), inst, msg, engine.Result{Sender: "USER_A"}); err != nil {
+ t.Fatalf("sendBindingPrompt: %v", err)
+ }
+ conn.mu.Lock()
+ n := len(conn.frames)
+ conn.mu.Unlock()
+ if n != 1 {
+ t.Fatalf("p2p trigger should send exactly one (private) frame, got %d", n)
+ }
+ body := conn.sendBody(t, 0)
+ if body["chatid"] != "USER_A" || body["chat_type"] != float64(chatTypeSingleInt) {
+ t.Errorf("p2p token frame = %v, want USER_A at chat_type 1", body)
+ }
+}
diff --git a/server/internal/integrations/wecom/resolvers_test.go b/server/internal/integrations/wecom/resolvers_test.go
new file mode 100644
index 0000000000..a678de5338
--- /dev/null
+++ b/server/internal/integrations/wecom/resolvers_test.go
@@ -0,0 +1,183 @@
+package wecom
+
+// resolvers_test.go — the platform-specific resolver mappings and outbound
+// wiring that need no database: the session-binder param mapping (driven with
+// a fake engineSessionBinder), BindMedia's no-op, NewResolverSet's wiring,
+// wecomMsgFromRaw / textOrNull, the Reply outcome branches that post to a
+// live sender, and Outbound.Register / handleEvent over a real bus.
+
+import (
+ "context"
+ "encoding/json"
+ "log/slog"
+ "strings"
+ "testing"
+
+ "github.com/jackc/pgx/v5"
+ "github.com/jackc/pgx/v5/pgtype"
+
+ "github.com/multica-ai/multica/server/internal/events"
+ "github.com/multica-ai/multica/server/internal/integrations/channel"
+ "github.com/multica-ai/multica/server/internal/integrations/channel/engine"
+ "github.com/multica-ai/multica/server/pkg/protocol"
+)
+
+// fakeSessionBinder records the engine.*Input it was handed so the wecom
+// param mapping can be asserted without a database.
+type fakeSessionBinder struct {
+ ensureIn engine.EnsureSessionInput
+ appendIn engine.AppendInput
+ sessID pgtype.UUID
+}
+
+func (f *fakeSessionBinder) EnsureSession(_ context.Context, in engine.EnsureSessionInput) (pgtype.UUID, error) {
+ f.ensureIn = in
+ return f.sessID, nil
+}
+func (f *fakeSessionBinder) AppendUserMessage(_ context.Context, in engine.AppendInput) (engine.AppendResult, error) {
+ f.appendIn = in
+ return engine.AppendResult{}, nil
+}
+
+func TestSessionBinder_EnsureSessionMapsGroupKey(t *testing.T) {
+ t.Parallel()
+ fb := &fakeSessionBinder{sessID: mustTestUUID(t)}
+ b := &sessionBinder{session: fb}
+ inst := engine.ResolvedInstallation{ID: mustTestUUID(t), WorkspaceID: mustTestUUID(t), AgentID: mustTestUUID(t)}
+ _, err := b.EnsureSession(context.Background(), engine.EnsureSessionParams{
+ Installation: inst,
+ Sender: mustTestUUID(t),
+ Message: channel.InboundMessage{Source: channel.Source{ChatID: "GROUP_1", ChatType: channel.ChatTypeGroup}},
+ })
+ if err != nil {
+ t.Fatalf("EnsureSession: %v", err)
+ }
+ // wecom keys the session on the chat id (no thread concept).
+ if fb.ensureIn.BindingKey != "GROUP_1" {
+ t.Errorf("BindingKey = %q, want the group chat id GROUP_1", fb.ensureIn.BindingKey)
+ }
+ if fb.ensureIn.ChatType != channel.ChatTypeGroup {
+ t.Errorf("ChatType = %v, want group", fb.ensureIn.ChatType)
+ }
+}
+
+func TestSessionBinder_AppendUsesTextAsCommand(t *testing.T) {
+ t.Parallel()
+ fb := &fakeSessionBinder{}
+ b := &sessionBinder{session: fb}
+ _, err := b.AppendMessage(context.Background(), engine.AppendParams{
+ SessionID: mustTestUUID(t),
+ Message: channel.InboundMessage{Text: "/issue do a thing", MessageID: "m9"},
+ })
+ if err != nil {
+ t.Fatalf("AppendMessage: %v", err)
+ }
+ if fb.appendIn.Body != "/issue do a thing" || fb.appendIn.CommandText != "/issue do a thing" {
+ t.Errorf("append body/command = %q/%q, want both to equal the text (wecom has no enrichment)", fb.appendIn.Body, fb.appendIn.CommandText)
+ }
+}
+
+func TestSessionBinder_BindMediaIsNoop(t *testing.T) {
+ t.Parallel()
+ b := &sessionBinder{session: &fakeSessionBinder{}}
+ if err := b.BindMedia(context.Background(), engine.BindMediaParams{}); err != nil {
+ t.Errorf("BindMedia = %v, want nil (wecom resolves no media)", err)
+ }
+}
+
+func TestNewResolverSet_WiresAllResolvers(t *testing.T) {
+ t.Parallel()
+ set := NewResolverSet(&Store{}, &fakeSessionBinder{}, nil)
+ if set.Installation == nil || set.Identity == nil || set.Dedup == nil || set.Session == nil || set.Audit == nil {
+ t.Error("NewResolverSet left a required resolver nil")
+ }
+ if set.OriginType != originWecomChat {
+ t.Errorf("OriginType = %q, want %q", set.OriginType, originWecomChat)
+ }
+}
+
+func TestWecomMsgFromRaw(t *testing.T) {
+ t.Parallel()
+ raw, _ := json.Marshal(InboundMessage{BotID: "bot-1", MsgType: "text", ChatID: "c1"})
+ wm, err := wecomMsgFromRaw(channel.InboundMessage{Raw: raw})
+ if err != nil {
+ t.Fatalf("wecomMsgFromRaw: %v", err)
+ }
+ if wm.BotID != "bot-1" || wm.MsgType != "text" {
+ t.Errorf("decoded = %+v, want bot-1/text", wm)
+ }
+ if _, err := wecomMsgFromRaw(channel.InboundMessage{}); err == nil {
+ t.Error("empty Raw should error")
+ }
+ if _, err := wecomMsgFromRaw(channel.InboundMessage{Raw: []byte("{not json")}); err == nil {
+ t.Error("bad JSON should error")
+ }
+}
+
+func TestTextOrNull(t *testing.T) {
+ t.Parallel()
+ if got := textOrNull(""); got.Valid {
+ t.Error(`textOrNull("") should be NULL (Valid=false)`)
+ }
+ got := textOrNull("x")
+ if !got.Valid || got.String != "x" {
+ t.Errorf("textOrNull(x) = %+v, want valid x", got)
+ }
+}
+
+func TestReply_PostsIssueCreatedConfirmation(t *testing.T) {
+ t.Parallel()
+ r, inst, conn := newReplierWithConn(t)
+ r.Reply(context.Background(), inst, channel.InboundMessage{Source: channel.Source{ChatID: "C1", ChatType: channel.ChatTypeP2P}}, engine.Result{
+ Outcome: engine.OutcomeIngested,
+ IssueID: mustTestUUID(t),
+ IssueIdentifier: "MUL-9",
+ IssueTitle: "Ship it",
+ })
+ if len(conn.frames) != 1 {
+ t.Fatalf("expected one confirmation frame, got %d", len(conn.frames))
+ }
+ body := conn.sendBody(t, 0)
+ md, _ := body["markdown"].(map[string]any)
+ if md == nil || md["content"] == nil {
+ t.Fatalf("no markdown content in confirmation: %v", body)
+ }
+ if content, _ := md["content"].(string); content == "" || !strings.Contains(content, "MUL-9") {
+ t.Errorf("confirmation = %q, want it to name MUL-9", md["content"])
+ }
+}
+
+func TestReply_PlainChatStaysSilent(t *testing.T) {
+ t.Parallel()
+ r, inst, conn := newReplierWithConn(t)
+ // Ingested but NOT an issue-created (no IssueID) → the agent's own reply
+ // arrives via EventChatDone, so Reply must not post anything here.
+ r.Reply(context.Background(), inst, channel.InboundMessage{Source: channel.Source{ChatID: "C1"}}, engine.Result{Outcome: engine.OutcomeIngested})
+ if len(conn.frames) != 0 {
+ t.Errorf("a plain chat message should not post a confirmation, got %d frames", len(conn.frames))
+ }
+}
+
+func TestReply_OfflineAndArchivedPostNotices(t *testing.T) {
+ t.Parallel()
+ for _, oc := range []engine.Outcome{engine.OutcomeAgentOffline, engine.OutcomeAgentArchived} {
+ r, inst, conn := newReplierWithConn(t)
+ r.Reply(context.Background(), inst, channel.InboundMessage{Source: channel.Source{ChatID: "C1", ChatType: channel.ChatTypeP2P}}, engine.Result{Outcome: oc})
+ if len(conn.frames) != 1 {
+ t.Errorf("outcome %s: expected one notice frame, got %d", oc, len(conn.frames))
+ }
+ }
+}
+
+func TestOutbound_RegisterAndHandleEventNoopOnNonWecom(t *testing.T) {
+ t.Parallel()
+ // Register must subscribe without panicking, and a chat-done for a session
+ // that isn't a wecom binding must be a silent no-op (handleEvent swallows
+ // the processEvent result). Uses pgx.ErrNoRows via the fake.
+ q := &fakeOutboundQueries{sessionErr: pgx.ErrNoRows}
+ o := NewOutbound(q, newSendersRegistry(), slog.Default())
+ bus := events.New()
+ o.Register(bus)
+ // Publishing must not panic; the handler runs synchronously on the bus.
+ bus.Publish(events.Event{Type: protocol.EventChatDone, ChatSessionID: "55555555-5555-5555-5555-555555555555", Payload: protocol.ChatDonePayload{Content: "x"}})
+}
diff --git a/server/internal/integrations/wecom/senders_registry.go b/server/internal/integrations/wecom/senders_registry.go
new file mode 100644
index 0000000000..28eda70f6a
--- /dev/null
+++ b/server/internal/integrations/wecom/senders_registry.go
@@ -0,0 +1,61 @@
+package wecom
+
+// senders_registry.go — a small process-wide map from installation_id to
+// live wsSender. wecomChannel.Connect adds an entry on entry and clears it
+// on exit; OutboundReplier and wecomChannel.Send look up by installation
+// id to push aibot_send_msg over the same socket the inbound loop owns
+// (aibot has no REST outbound path; every write goes over the WebSocket).
+//
+// Why a registry rather than storing the sender on wecomChannel:
+// OutboundReplier is created once at boot with the shared engine.Router
+// and does not have per-installation Channel handles. When the engine
+// invokes Replier.Reply, it passes engine.ResolvedInstallation carrying
+// the installation id, not the Channel. The registry is the seam that
+// lets the boot-time Replier reach the per-installation live connection
+// without threading the Channel through the engine.
+
+import (
+ "sync"
+
+ "github.com/jackc/pgx/v5/pgtype"
+
+ "github.com/multica-ai/multica/server/internal/util"
+)
+
+// sendersRegistry is a goroutine-safe installation_id → wsSender map.
+type sendersRegistry struct {
+ mu sync.RWMutex
+ byKey map[string]*wsSender
+}
+
+// newSendersRegistry constructs an empty registry.
+func newSendersRegistry() *sendersRegistry {
+ return &sendersRegistry{byKey: make(map[string]*wsSender)}
+}
+
+// NewSendersRegistry is the public constructor boot uses to inject the
+// same registry into both the wecom ChannelDeps (writer side) and the
+// OutboundReplier (reader side). Kept exported so router.go can wire it
+// without importing an unexported type.
+func NewSendersRegistry() *sendersRegistry { return newSendersRegistry() }
+
+func (r *sendersRegistry) set(id pgtype.UUID, s *wsSender) {
+ r.mu.Lock()
+ defer r.mu.Unlock()
+ r.byKey[util.UUIDToString(id)] = s
+}
+
+func (r *sendersRegistry) clear(id pgtype.UUID) {
+ r.mu.Lock()
+ defer r.mu.Unlock()
+ delete(r.byKey, util.UUIDToString(id))
+}
+
+// get returns the live wsSender for an installation, or nil when no
+// connection is currently held. Callers MUST treat nil as "connection not
+// ready" — Supervisor may be mid-reconnect after a lease flip.
+func (r *sendersRegistry) get(id pgtype.UUID) *wsSender {
+ r.mu.RLock()
+ defer r.mu.RUnlock()
+ return r.byKey[util.UUIDToString(id)]
+}
diff --git a/server/internal/integrations/wecom/store.go b/server/internal/integrations/wecom/store.go
new file mode 100644
index 0000000000..20104e290e
--- /dev/null
+++ b/server/internal/integrations/wecom/store.go
@@ -0,0 +1,79 @@
+package wecom
+
+// store.go — the data-layer adapter behind wecom's ResolverSet. It rides on
+// the generalized channel_* tables (migration 124) using the shared sqlc
+// queries; nothing in this file writes wecom-specific SQL.
+
+import (
+ "context"
+ "errors"
+
+ "github.com/jackc/pgx/v5"
+ "github.com/jackc/pgx/v5/pgtype"
+
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+)
+
+// Store is the read/write surface the wecom resolvers and outbound path use.
+// It embeds *db.Queries so callers who need generic queries (workspace,
+// member, agent) can reach them without another wrapper. All wecom-specific
+// helpers scope by channel_type = 'wecom' internally.
+type Store struct {
+ *db.Queries
+}
+
+// NewStore constructs a wecom Store bound to a *db.Queries.
+func NewStore(q *db.Queries) *Store {
+ return &Store{Queries: q}
+}
+
+// WithTx binds this Store to a pgx.Tx so callers running the ingest tx can
+// keep wecom lookups inside it.
+func (s *Store) WithTx(tx pgx.Tx) *Store {
+ return &Store{Queries: s.Queries.WithTx(tx)}
+}
+
+// GetInstallationByBotID looks up an installation by its smart-bot id. The
+// routing key column is config->>'app_id' stored as the BotID directly (see
+// encodeInstallConfig) so the shared idx_channel_installation_type_appid
+// index does the work.
+func (s *Store) GetInstallationByBotID(ctx context.Context, botID string) (Installation, error) {
+ row, err := s.Queries.GetChannelInstallationByAppID(ctx, db.GetChannelInstallationByAppIDParams{
+ ChannelType: channelTypeWecom,
+ AppID: botID,
+ })
+ if err != nil {
+ return Installation{}, err
+ }
+ return installationFromRow(row)
+}
+
+// GetInstallation loads an installation by primary key, scoped to
+// channel_type = 'wecom' so a Feishu id passed here is not silently reused.
+func (s *Store) GetInstallation(ctx context.Context, id pgtype.UUID) (Installation, error) {
+ row, err := s.Queries.GetChannelInstallation(ctx, db.GetChannelInstallationParams{
+ ID: id,
+ ChannelType: channelTypeWecom,
+ })
+ if err != nil {
+ return Installation{}, err
+ }
+ return installationFromRow(row)
+}
+
+// IsWorkspaceMember re-checks membership at inbound time. With channel_* FKs
+// removed (MUL-3515 §4) a stale binding could otherwise route a message to a
+// user who has since left the workspace.
+func (s *Store) IsWorkspaceMember(ctx context.Context, workspaceID, userID pgtype.UUID) (bool, error) {
+ _, err := s.Queries.GetMemberByUserAndWorkspace(ctx, db.GetMemberByUserAndWorkspaceParams{
+ UserID: userID,
+ WorkspaceID: workspaceID,
+ })
+ if err != nil {
+ if errors.Is(err, pgx.ErrNoRows) {
+ return false, nil
+ }
+ return false, err
+ }
+ return true, nil
+}
diff --git a/server/internal/integrations/wecom/types.go b/server/internal/integrations/wecom/types.go
new file mode 100644
index 0000000000..2a989a571d
--- /dev/null
+++ b/server/internal/integrations/wecom/types.go
@@ -0,0 +1,123 @@
+// Package wecom is the WeCom (企业微信) smart-bot ("智能机器人" / aibot)
+// adapter for the channel-agnostic inbound engine (MUL-3620). It plugs into the
+// same engine.Router / ResolverSet as Feishu and Slack.
+//
+// Unlike the internal customer-service ("内部客服号") flow which is HTTP-callback
+// based, the smart-bot flow is a client-initiated WebSocket long connection
+// against wss://openws.work.weixin.qq.com. Each installation carries a
+// (bot_id, secret) pair; after the WS handshake the client subscribes with
+// aibot_subscribe and thereafter receives aibot_msg_callback events and sends
+// aibot_send_msg / aibot_respond_msg / aibot_upload_media_* over the same
+// socket. No public callback URL is required.
+//
+// One installation = one bot = one WebSocket. WeCom allows only one active
+// connection per bot; a second connection kicks the first with a
+// disconnected_event. That single-active-connection guarantee lines up with
+// engine.Supervisor's WS lease, so the multi-replica invariant (at most one
+// active connection per installation across processes) already holds without
+// wecom-specific code.
+package wecom
+
+import (
+ "encoding/json"
+ "errors"
+ "fmt"
+
+ "github.com/jackc/pgx/v5/pgtype"
+
+ "github.com/multica-ai/multica/server/internal/integrations/channel"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+)
+
+// TypeWecom is the channel discriminator for the WeCom smart-bot adapter.
+// It is defined here alongside the wecom-specific types (rather than in
+// package channel) so a build that excludes wecom does not force a package
+// channel edit; slack follows the same pattern with TypeSlack.
+const TypeWecom channel.Type = "wecom"
+
+// channelTypeWecom is the string form persisted in channel_installation.
+const channelTypeWecom = string(TypeWecom)
+
+// InstallationStatus mirrors the channel_installation.status column values.
+type InstallationStatus string
+
+const (
+ InstallationActive InstallationStatus = "active"
+ InstallationRevoked InstallationStatus = "revoked"
+)
+
+// Installation is the decoded, in-memory view of a WeCom smart-bot
+// channel_installation row. SecretEncrypted is a secretbox-sealed blob and
+// never plaintext; callers who need the plaintext go through the Credentials
+// resolver.
+type Installation struct {
+ ID pgtype.UUID
+ WorkspaceID pgtype.UUID
+ AgentID pgtype.UUID
+ InstallerUserID pgtype.UUID
+ Status InstallationStatus
+
+ // BotID is the smart-bot identifier the WeCom admin console
+ // assigns at bot creation. It is BOTH the auth identity presented in
+ // the aibot_subscribe frame AND the routing key we persist as
+ // config->>'app_id' so GetChannelInstallationByAppID resolves an
+ // inbound event to its installation.
+ BotID string
+
+ // SecretEncrypted is the sealed long-connection secret. This is
+ // distinct from the token/EncodingAESKey used by callback-mode bots
+ // (which we do not use). Rotated via re-install.
+ SecretEncrypted []byte
+}
+
+// InstallationCredentials is the plaintext-bearing view the WebSocket
+// subscribe frame needs. It is minted per-connect by the credentials resolver
+// so a plaintext secret never lives on the durable Installation itself.
+type InstallationCredentials struct {
+ BotID string
+ Secret string
+}
+
+// installConfig is the on-disk (JSONB) shape of channel_installation.config
+// for wecom smart-bot rows. `app_id == bot_id` so the shared
+// idx_channel_installation_type_appid index and GetChannelInstallationByAppID
+// query stay generic.
+type installConfig struct {
+ AppID string `json:"app_id"`
+ BotID string `json:"bot_id"`
+ SecretEncrypted []byte `json:"secret_encrypted"`
+}
+
+// encodeInstallConfig marshals an Installation's config-bearing fields into
+// the JSONB blob stored in channel_installation.config.
+func encodeInstallConfig(inst Installation) ([]byte, error) {
+ if inst.BotID == "" {
+ return nil, errors.New("wecom: bot_id is required")
+ }
+ return json.Marshal(installConfig{
+ AppID: inst.BotID,
+ BotID: inst.BotID,
+ SecretEncrypted: inst.SecretEncrypted,
+ })
+}
+
+// installationFromRow hydrates an Installation from a channel_installation
+// row. The row's ChannelType is trusted (the callers already scope queries by
+// channel_type = 'wecom'), so we don't re-check it here.
+func installationFromRow(row db.ChannelInstallation) (Installation, error) {
+ var cfg installConfig
+ if len(row.Config) > 0 {
+ if err := json.Unmarshal(row.Config, &cfg); err != nil {
+ return Installation{}, fmt.Errorf("wecom: decode installation config: %w", err)
+ }
+ }
+ return Installation{
+ ID: row.ID,
+ WorkspaceID: row.WorkspaceID,
+ AgentID: row.AgentID,
+ InstallerUserID: row.InstallerUserID,
+ Status: InstallationStatus(row.Status),
+ BotID: cfg.BotID,
+ SecretEncrypted: cfg.SecretEncrypted,
+ }, nil
+}
diff --git a/server/internal/integrations/wecom/wecom_channel.go b/server/internal/integrations/wecom/wecom_channel.go
new file mode 100644
index 0000000000..4629315a5c
--- /dev/null
+++ b/server/internal/integrations/wecom/wecom_channel.go
@@ -0,0 +1,479 @@
+package wecom
+
+// wecom_channel.go — the Channel + Factory the engine.Supervisor drives, plus
+// the WebSocket run loop for one aibot smart-bot connection. WeCom allows
+// only one active connection per bot; the Supervisor's WS lease enforces
+// that same "at most one per replica" invariant at the process layer, so the
+// combination gives us a single global connection per installation without
+// wecom-specific coordination.
+//
+// The read loop lives on this file (rather than in a shared connector as
+// with lark/ws_connector.go) because the aibot protocol is small enough
+// that a per-installation loop is clearer than an EventConnector abstraction.
+// Slack takes the same shape in slack_channel.go — the per-installation
+// receive loop is inlined into Channel.Connect.
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "log/slog"
+ "net/url"
+ "time"
+
+ cryptorand "crypto/rand"
+ "encoding/hex"
+
+ "github.com/gorilla/websocket"
+ "github.com/jackc/pgx/v5/pgtype"
+
+ "github.com/multica-ai/multica/server/internal/integrations/channel"
+ "github.com/multica-ai/multica/server/internal/util"
+)
+
+// DefaultWSURL is the aibot long-connection endpoint. WeCom publishes a
+// single global endpoint for every bot; the (bot_id, secret) pair carried in
+// the aibot_subscribe frame after the WS handshake identifies which bot the
+// connection belongs to.
+const DefaultWSURL = "wss://openws.work.weixin.qq.com"
+
+// pingInterval is the client-driven heartbeat cadence. WeCom's docs
+// prescribe 30s; below that they may kill the socket, above that we spam.
+const pingInterval = 30 * time.Second
+
+// subscribeTimeout caps the wait between "sent aibot_subscribe" and
+// "received the errcode 0 ack". The server responds within a few hundred
+// milliseconds in practice; this bound protects against a silent socket.
+const subscribeTimeout = 10 * time.Second
+
+// readDeadline is refreshed on every successful read. If no bytes arrive
+// within this window we assume the socket is dead and force-close it — the
+// Supervisor then handles reconnect. It MUST exceed pingInterval by a
+// comfortable margin so a pong is not late enough to trigger a false trip.
+const readDeadline = 90 * time.Second
+
+// writeDeadline caps a single frame's write budget. Below this a genuinely
+// slow socket is preferable to an infinitely stuck goroutine.
+const writeDeadline = 10 * time.Second
+
+// handshakeTimeout bounds the initial TCP + WS handshake dial.
+const handshakeTimeout = 15 * time.Second
+
+// wecomChannel is one installation's aibot smart-bot WebSocket connection.
+// The engine.Supervisor builds one per active installation via the
+// registered Factory and drives lease / reconnect lifecycle; Connect blocks
+// on the receive loop until ctx is cancelled or the link drops.
+type wecomChannel struct {
+ installationID pgtype.UUID
+ botID string
+ secret string
+ handler channel.InboundHandler
+ dialer Dialer
+ wsURL string
+ logger *slog.Logger
+ // senders is the package-level installation→wsSender registry (see
+ // senders_registry.go). We hold a reference so Connect can register
+ // itself on entry and clear on exit. nil in tests that don't exercise
+ // the OutboundReplier path.
+ senders *sendersRegistry
+}
+
+var _ channel.Channel = (*wecomChannel)(nil)
+
+func (c *wecomChannel) Type() channel.Type { return TypeWecom }
+
+// Capabilities declares what the aibot adapter supports today. Text is the
+// only fully wired capability; attachments arrive as MsgTypeImage / File /
+// Audio / Video but we do not yet download the media (WeCom's aibot API
+// requires an additional aibot_upload_media_* dance to send back media).
+func (c *wecomChannel) Capabilities() channel.Capability {
+ return channel.CapText
+}
+
+// Disconnect is a no-op: the WS connection's whole lifetime is scoped to
+// Connect (it returns when the run context is cancelled), so there is no
+// long-lived resource to release here. Mirrors feishuChannel / slackChannel.
+func (c *wecomChannel) Disconnect(ctx context.Context) error { return nil }
+
+// Connect dials the aibot long-connection endpoint, sends the subscribe
+// frame, and runs the read loop until ctx is cancelled or the link drops.
+// Every exit path cancels the derived runCtx and waits for the read
+// goroutine to observe it, so a transient failure tears the live connection
+// down before the Supervisor reconnects — no leaked socket goroutine
+// consuming events into an unread channel.
+func (c *wecomChannel) Connect(ctx context.Context) error {
+ if c.handler == nil {
+ return errors.New("wecom: inbound handler not configured")
+ }
+ if c.botID == "" || c.secret == "" {
+ return errors.New("wecom: bot_id / secret not configured")
+ }
+
+ wsURL := c.wsURL
+ if wsURL == "" {
+ wsURL = DefaultWSURL
+ }
+ if _, err := url.Parse(wsURL); err != nil {
+ return fmt.Errorf("wecom: parse ws url: %w", err)
+ }
+
+ dialer := c.dialer
+ if dialer == nil {
+ dialer = defaultDialer
+ }
+
+ log := c.logger
+ if log == nil {
+ log = slog.Default()
+ }
+ log = log.With("installation_id", util.UUIDToString(c.installationID), "bot_id", c.botID)
+
+ conn, _, err := dialer.DialContext(ctx, wsURL, nil)
+ if err != nil {
+ return fmt.Errorf("wecom: dial %s: %w", wsURL, err)
+ }
+ defer conn.Close()
+
+ sender := newWSSender(conn, log)
+
+ // Watchdog: bridges ctx cancellation to the blocking ReadMessage() call.
+ // gorilla's ReadMessage does not observe ctx; cancelling our ctx flips
+ // ctx.Done but does not touch the read syscall. We close the socket on
+ // ctx.Done so the in-flight Read returns immediately with a
+ // "use of closed connection" error. The watchdog also runs on any other
+ // exit path (via `done`) so we never leak this goroutine, and close is
+ // idempotent so double-close on a normal exit is safe.
+ done := make(chan struct{})
+ go func() {
+ select {
+ case <-ctx.Done():
+ _ = conn.Close()
+ case <-done:
+ }
+ }()
+ defer close(done)
+
+ // Subscribe — auth the connection. Any error here yields the loop back
+ // to the Supervisor for backoff + retry.
+ if err := c.subscribe(ctx, conn, sender, log); err != nil {
+ return err
+ }
+ log.Info("wecom: subscribe ok")
+
+ // Install the sender on the package-level registry so the OutboundReplier
+ // (created at boot, not per-installation) can locate this connection by
+ // installation id and push aibot_send_msg over the same socket. Cleared
+ // on exit so a stale sender for a dead connection is never dispatched to.
+ if c.senders != nil && c.installationID.Valid {
+ c.senders.set(c.installationID, sender)
+ defer c.senders.clear(c.installationID)
+ }
+
+ // Heartbeat — WeCom kills silent sockets past ~90s. We ping every 30s
+ // via the shared writer mutex so it interleaves cleanly with other
+ // outbound frames.
+ pingCtx, pingCancel := context.WithCancel(ctx)
+ pingDone := make(chan struct{})
+ go func() {
+ defer close(pingDone)
+ c.pingLoop(pingCtx, sender, log)
+ }()
+ // Cancel and wait in ONE defer, in that order. Two separate defers would
+ // run LIFO — the wait first, the cancel second — and pingLoop only returns
+ // on pingCtx.Done. On any exit path where the parent ctx is still live
+ // (read error, dispatch error) nothing would ever cancel pingCtx, so the
+ // wait would block forever and Connect would never return to the
+ // Supervisor for reconnect.
+ defer func() {
+ pingCancel()
+ <-pingDone
+ }()
+
+ // Read loop. Every frame comes back through the same decode → dispatch
+ // → (maybe) reply path. A single bad frame does NOT tear the socket
+ // down — only transport / handler errors escalate.
+ _ = conn.SetReadDeadline(time.Now().Add(readDeadline))
+ for {
+ if ctx.Err() != nil {
+ return nil
+ }
+ typ, payload, err := conn.ReadMessage()
+ if err != nil {
+ if ctx.Err() != nil {
+ return nil
+ }
+ return fmt.Errorf("wecom: read: %w", err)
+ }
+ _ = conn.SetReadDeadline(time.Now().Add(readDeadline))
+ if typ != websocket.TextMessage && typ != websocket.BinaryMessage {
+ continue
+ }
+
+ var env frameEnvelope
+ if err := json.Unmarshal(payload, &env); err != nil {
+ log.Warn("wecom: bad frame envelope", "error", err, "size", len(payload))
+ continue
+ }
+ if err := c.dispatchFrame(ctx, env, sender, log); err != nil {
+ return err
+ }
+ }
+}
+
+// subscribe sends the aibot_subscribe frame and waits (up to
+// subscribeTimeout) for the server's ack. The ack shape is a frame with
+// echoed headers.req_id + errcode; errcode == 0 means good, anything else
+// is fatal (bad credentials / bot doesn't exist).
+func (c *wecomChannel) subscribe(ctx context.Context, conn wsConn, sender *wsSender, log *slog.Logger) error {
+ reqID := newReqID()
+ if err := sender.write(map[string]any{
+ "cmd": cmdSubscribe,
+ "headers": frameHeaders{ReqID: reqID},
+ "body": subscribeBody(c.botID, c.secret),
+ }); err != nil {
+ return fmt.Errorf("wecom: send subscribe: %w", err)
+ }
+
+ // Wait for the matching ack — the server writes it as a frame with
+ // cmd empty (or absent) and headers.req_id equal to ours. Any other
+ // frame that arrives first is dropped (subscribe is the very first
+ // exchange, so this is rare in practice).
+ deadline := time.Now().Add(subscribeTimeout)
+ _ = conn.SetReadDeadline(deadline)
+ for {
+ if ctx.Err() != nil {
+ return ctx.Err()
+ }
+ typ, payload, err := conn.ReadMessage()
+ if err != nil {
+ return fmt.Errorf("wecom: subscribe read: %w", err)
+ }
+ if typ != websocket.TextMessage && typ != websocket.BinaryMessage {
+ continue
+ }
+ var env frameEnvelope
+ if err := json.Unmarshal(payload, &env); err != nil {
+ continue
+ }
+ if env.Headers.ReqID != reqID {
+ continue
+ }
+ if env.ErrCode != 0 {
+ return fmt.Errorf("wecom: subscribe rejected errcode=%d errmsg=%s", env.ErrCode, env.ErrMsg)
+ }
+ return nil
+ }
+}
+
+// dispatchFrame routes one server frame. Only aibot_msg_callback ever
+// escalates back to the loop's caller (as a handler infra failure);
+// events are logged + acked and everything else is silently dropped.
+func (c *wecomChannel) dispatchFrame(ctx context.Context, env frameEnvelope, sender *wsSender, log *slog.Logger) error {
+ switch env.Cmd {
+ case cmdMsgCallback:
+ var mc aibotMsgCallback
+ if err := json.Unmarshal(env.Body, &mc); err != nil {
+ log.Warn("wecom: bad aibot_msg_callback body", "error", err)
+ return nil
+ }
+ msg := channelMessageFromCallback(c.botID, mc, env.Headers.ReqID)
+ if mc.MsgType != "text" {
+ // Iteration 1 routes only text. Rather than drop other types
+ // (voice / image / file) silently — which reads as a broken bot —
+ // answer the same chat with a one-line "text only" receipt, then
+ // stop. Media routing, and dedup'd receipts that never double-answer
+ // a WeCom delivery retry, are a follow-up. Best-effort: a send
+ // failure degrades to the prior silent drop.
+ log.Debug("wecom: non-text message, replying text-only", "msg_type", mc.MsgType, "msg_id", mc.MsgID)
+ if err := sender.sendText(msg.Source.ChatID, aibotChatTypeFromChannel(msg.Source.ChatType), "抱歉,我目前只能处理文字消息。"); err != nil {
+ log.Debug("wecom: text-only receipt send failed", "error", err, "msg_id", mc.MsgID)
+ }
+ return nil
+ }
+ if err := c.handler(ctx, msg); err != nil {
+ return err
+ }
+ return nil
+ case cmdEventCallback:
+ var ec aibotEventCallback
+ if err := json.Unmarshal(env.Body, &ec); err != nil {
+ log.Warn("wecom: bad aibot_event_callback body", "error", err)
+ return nil
+ }
+ switch ec.Event.EventType {
+ case eventDisconnected:
+ // Another connection displaced ours. Return so the Supervisor
+ // can backoff and reconnect (which will in turn displace THAT
+ // one — the last writer wins).
+ return errors.New("wecom: received disconnected_event (superseded)")
+ default:
+ log.Debug("wecom: event", "type", ec.Event.EventType)
+ return nil
+ }
+ case cmdServerPing:
+ // Server-initiated ping (rare per the docs, but handle defensively).
+ if err := sender.write(map[string]any{
+ "cmd": cmdPong,
+ "headers": frameHeaders{ReqID: env.Headers.ReqID},
+ }); err != nil {
+ return fmt.Errorf("wecom: pong: %w", err)
+ }
+ return nil
+ case cmdPong:
+ // Ack for our client-initiated ping — no-op.
+ return nil
+ default:
+ // Anonymous ack frames (empty cmd) for our writes. Most are
+ // errcode=0 no-ops, but aibot_send_msg / aibot_respond_msg /
+ // aibot_upload_media_* can reject with a non-zero errcode
+ // (e.g. wrong msgtype, rate limit, chat not writable). Log the
+ // error so a failed outbound is visible without having to
+ // packet-capture the socket.
+ if env.ErrCode != 0 {
+ log.Warn("wecom: server ack error",
+ "errcode", env.ErrCode,
+ "errmsg", env.ErrMsg,
+ "req_id", env.Headers.ReqID,
+ )
+ }
+ return nil
+ }
+}
+
+// pingLoop sends heartbeat frames every pingInterval until ctx is
+// cancelled. A write failure surfaces on the next ReadMessage error path;
+// we log it here but do not tear the loop down ourselves.
+func (c *wecomChannel) pingLoop(ctx context.Context, sender *wsSender, log *slog.Logger) {
+ t := time.NewTicker(pingInterval)
+ defer t.Stop()
+ for {
+ select {
+ case <-ctx.Done():
+ return
+ case <-t.C:
+ if err := sender.write(map[string]any{
+ "cmd": cmdPing,
+ "headers": frameHeaders{ReqID: newReqID()},
+ }); err != nil {
+ log.Warn("wecom: ping write failed", "error", err)
+ }
+ }
+ }
+}
+
+// Send is the outbound Channel entry the engine calls with a normalized
+// OutboundMessage. Iteration 1 always uses aibot_send_msg (WeCom's
+// "proactive push" cmd) rather than aibot_respond_msg — send_msg has no 5s
+// deadline and works regardless of whether the message ever ties back to a
+// specific inbound frame. The one caveat is chat_type: aibot_send_msg needs
+// to know whether the ChatID is a single-user id or a group id. We piggy-
+// back on the length heuristic used by internal-customer-service (chat ids
+// are ≥33 chars, userids are shorter), which is stable in practice.
+//
+// The Channel is not the primary outbound path in the multica engine — the
+// EventChatDone subscriber and the OutboundReplier handle most sends — but
+// Channel.Send is still the contract that lets the engine deliver ad-hoc
+// replies, so we implement it here for parity with feishuChannel /
+// slackChannel.
+func (c *wecomChannel) Send(ctx context.Context, out channel.OutboundMessage) (channel.SendResult, error) {
+ // Not used. Outbound for wecom goes through OutboundReplier / Outbound
+ // (EventChatDone + EventInboxNew), which know the message's real
+ // Source.ChatType and address the correct chat. The generic
+ // Channel.Send seam is never invoked by the engine for this channel; a
+ // stub here previously guessed single-vs-group from len(ChatID) > 32,
+ // the only chat-type inference in the package. Return not-supported
+ // rather than keep a second, heuristic outbound path alive.
+ _ = ctx
+ _ = out
+ return channel.SendResult{}, ErrSendNotSupported
+}
+
+// ErrSendNotSupported is returned by wecomChannel.Send. WeCom's generic
+// Channel.Send seam has no honest implementation — channel.OutboundMessage
+// carries no chat_type, and outbound already flows through OutboundReplier /
+// Outbound, which read the chat type off the inbound frame.
+var ErrSendNotSupported = errors.New("wecom: Channel.Send is not supported; outbound goes through OutboundReplier/Outbound")
+
+// ---- factory ----
+
+// ChannelDeps bundles the shared dependencies the wecom Factory closes
+// over. The engine inbound handler is supplied per-build via
+// channel.Config.Handler; the CredentialsResolver decrypts the stored
+// secret.
+type ChannelDeps struct {
+ Credentials CredentialsResolver
+ Logger *slog.Logger
+
+ // Senders is the package-level installation→wsSender registry. The
+ // OutboundReplier and the wecomChannel.Send path both look up the live
+ // wsSender through it. Boot passes ONE registry instance shared with
+ // the OutboundReplier constructor. Nil in tests that don't exercise
+ // outbound.
+ Senders *sendersRegistry
+
+ // Dialer overrides the default gorilla dialer. Tests point it at an
+ // httptest server; production leaves this nil.
+ Dialer Dialer
+
+ // WSURL overrides DefaultWSURL. Same test-only intent as Dialer.
+ WSURL string
+}
+
+// RegisterWecom registers the per-installation wecom smart-bot Factory so
+// the engine.Supervisor builds + supervises one wecomChannel per active
+// installation. "Adding wecom smart-bot inbound" is this call plus the
+// adapter — no engine edit (same contract as lark.RegisterFeishu /
+// slack.RegisterSlack).
+func RegisterWecom(reg *channel.Registry, deps ChannelDeps) {
+ reg.Register(TypeWecom, newWecomFactory(deps))
+}
+
+func newWecomFactory(deps ChannelDeps) channel.Factory {
+ logger := deps.Logger
+ if logger == nil {
+ logger = slog.Default()
+ }
+ return func(cfg channel.Config) (channel.Channel, error) {
+ if deps.Credentials == nil {
+ return nil, errors.New("wecom: credentials resolver missing")
+ }
+ var ic installConfig
+ if len(cfg.Raw) > 0 {
+ if err := json.Unmarshal(cfg.Raw, &ic); err != nil {
+ return nil, fmt.Errorf("wecom: decode installation config: %w", err)
+ }
+ }
+ if ic.BotID == "" {
+ return nil, errors.New("wecom: installation config missing bot_id")
+ }
+ inst := Installation{BotID: ic.BotID, SecretEncrypted: ic.SecretEncrypted}
+ creds, err := deps.Credentials.Credentials(inst)
+ if err != nil {
+ return nil, fmt.Errorf("wecom: decrypt secret: %w", err)
+ }
+ return &wecomChannel{
+ installationID: cfg.ID,
+ botID: creds.BotID,
+ secret: creds.Secret,
+ handler: cfg.Handler,
+ dialer: deps.Dialer,
+ wsURL: deps.WSURL,
+ logger: logger,
+ senders: deps.Senders,
+ }, nil
+ }
+}
+
+// ---- request id ----
+
+// newReqID returns a random correlation id for a WebSocket frame's
+// headers.req_id. The server echoes it back on each ack so the client can
+// pair replies with requests.
+func newReqID() string {
+ var buf [8]byte
+ if _, err := cryptorand.Read(buf[:]); err != nil {
+ return fmt.Sprintf("wecom-%d", time.Now().UnixNano())
+ }
+ return hex.EncodeToString(buf[:])
+}
diff --git a/server/internal/integrations/wecom/wecom_channel_test.go b/server/internal/integrations/wecom/wecom_channel_test.go
new file mode 100644
index 0000000000..ca7bfbcd96
--- /dev/null
+++ b/server/internal/integrations/wecom/wecom_channel_test.go
@@ -0,0 +1,193 @@
+package wecom
+
+// wecom_channel_test.go — Connect lifecycle guards. The one that matters most
+// is the deadlock regression: a read error while the parent ctx is still live
+// (exactly the transient drop the Supervisor exists to retry) must return to
+// the caller, not park forever. The bug was a LIFO defer ordering — the ping
+// goroutine's wait ran before its cancel — and it was invisible on the
+// shutdown path, so it needs a guard that drives the live-ctx error path.
+//
+// Co-authored analysis and the original defect report: seacen (PR #5833 review).
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "net/http"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/gorilla/websocket"
+ "github.com/jackc/pgx/v5/pgtype"
+
+ "github.com/multica-ai/multica/server/internal/integrations/channel"
+ "github.com/multica-ai/multica/server/internal/util"
+)
+
+// scriptedConn is a wsConn that acks the subscribe frame it is written (echoing
+// the caller's req_id, which is generated internally and not knowable ahead of
+// time) and then, on the next read, returns a transient error — standing in for
+// a dropped socket while the parent ctx is still live.
+type scriptedConn struct {
+ mu sync.Mutex
+ ackFrame []byte // queued subscribe ack, set when the subscribe write is seen
+ reads int
+ readErr error
+ writes int
+ closed bool
+ closeOnce sync.Once
+}
+
+func (c *scriptedConn) WriteMessage(_ int, data []byte) error {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ c.writes++
+ var env frameEnvelope
+ if err := json.Unmarshal(data, &env); err != nil {
+ return nil
+ }
+ if env.Cmd == cmdSubscribe {
+ ack, _ := json.Marshal(frameEnvelope{Headers: frameHeaders{ReqID: env.Headers.ReqID}, ErrCode: 0})
+ c.ackFrame = ack
+ }
+ return nil
+}
+
+func (c *scriptedConn) ReadMessage() (int, []byte, error) {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ c.reads++
+ if c.ackFrame != nil {
+ ack := c.ackFrame
+ c.ackFrame = nil
+ return websocket.TextMessage, ack, nil
+ }
+ // Subscribe already acked; the socket now "drops".
+ return 0, nil, errors.New("simulated transient read error")
+}
+
+func (c *scriptedConn) SetReadDeadline(time.Time) error { return nil }
+func (c *scriptedConn) SetWriteDeadline(time.Time) error { return nil }
+func (c *scriptedConn) Close() error {
+ c.closeOnce.Do(func() { c.closed = true })
+ return nil
+}
+
+type scriptedDialer struct{ conn wsConn }
+
+func (d scriptedDialer) DialContext(context.Context, string, http.Header) (wsConn, *http.Response, error) {
+ return d.conn, nil, nil
+}
+
+// TestConnectReturnsOnReadErrorWhileCtxLive drives the exact path the deadlock
+// hid on: subscribe succeeds, the ping goroutine is running, then a read fails
+// while ctx is NOT cancelled. Connect must return the error promptly. Against
+// the pre-fix defer ordering this blocks forever on <-pingDone and the test
+// times out.
+func TestConnectReturnsOnReadErrorWhileCtxLive(t *testing.T) {
+ t.Parallel()
+
+ c := &wecomChannel{
+ installationID: mustTestUUID(t),
+ botID: "bot-1",
+ secret: "secret-1",
+ handler: func(context.Context, channel.InboundMessage) error { return nil },
+ dialer: scriptedDialer{conn: &scriptedConn{}},
+ wsURL: "wss://example.test/ws",
+ senders: newSendersRegistry(),
+ }
+
+ errCh := make(chan error, 1)
+ go func() { errCh <- c.Connect(context.Background()) }()
+
+ select {
+ case err := <-errCh:
+ if err == nil {
+ t.Fatal("Connect returned nil; expected the transient read error")
+ }
+ case <-time.After(3 * time.Second):
+ t.Fatal("Connect did not return within 3s on a read error with a live ctx — the ping defer deadlock has regressed")
+ }
+}
+
+// TestConnectReturnsOnCtxCancel confirms the ordinary shutdown path still
+// returns (the path that always worked, kept so a fix to the above can't break
+// it).
+func TestConnectReturnsOnCtxCancel(t *testing.T) {
+ t.Parallel()
+
+ // A conn that acks subscribe then blocks on read until Close, so only ctx
+ // cancellation (which closes the socket via the watchdog) ends Connect.
+ bc := &blockingConn{unblock: make(chan struct{})}
+ c := &wecomChannel{
+ installationID: mustTestUUID(t),
+ botID: "bot-1",
+ secret: "secret-1",
+ handler: func(context.Context, channel.InboundMessage) error { return nil },
+ dialer: scriptedDialer{conn: bc},
+ wsURL: "wss://example.test/ws",
+ }
+
+ ctx, cancel := context.WithCancel(context.Background())
+ errCh := make(chan error, 1)
+ go func() { errCh <- c.Connect(ctx) }()
+
+ time.Sleep(50 * time.Millisecond) // let it reach the read loop
+ cancel()
+
+ select {
+ case <-errCh:
+ // returned (nil on ctx path) — success
+ case <-time.After(3 * time.Second):
+ t.Fatal("Connect did not return within 3s after ctx cancel")
+ }
+}
+
+// blockingConn acks subscribe, then blocks every subsequent read until Close.
+type blockingConn struct {
+ mu sync.Mutex
+ ack []byte
+ acked bool
+ unblock chan struct{}
+ closeOne sync.Once
+}
+
+func (c *blockingConn) WriteMessage(_ int, data []byte) error {
+ var env frameEnvelope
+ if err := json.Unmarshal(data, &env); err == nil && env.Cmd == cmdSubscribe {
+ c.mu.Lock()
+ c.ack, _ = json.Marshal(frameEnvelope{Headers: frameHeaders{ReqID: env.Headers.ReqID}})
+ c.mu.Unlock()
+ }
+ return nil
+}
+
+func (c *blockingConn) ReadMessage() (int, []byte, error) {
+ c.mu.Lock()
+ if !c.acked && c.ack != nil {
+ c.acked = true
+ ack := c.ack
+ c.mu.Unlock()
+ return websocket.TextMessage, ack, nil
+ }
+ c.mu.Unlock()
+ <-c.unblock // block until Close
+ return 0, nil, errors.New("closed")
+}
+
+func (c *blockingConn) SetReadDeadline(time.Time) error { return nil }
+func (c *blockingConn) SetWriteDeadline(time.Time) error { return nil }
+func (c *blockingConn) Close() error {
+ c.closeOne.Do(func() { close(c.unblock) })
+ return nil
+}
+
+func mustTestUUID(t *testing.T) pgtype.UUID {
+ t.Helper()
+ u, err := util.ParseUUID("11111111-1111-1111-1111-111111111111")
+ if err != nil {
+ t.Fatalf("parse uuid: %v", err)
+ }
+ return u
+}
diff --git a/server/internal/integrations/wecom/wecom_resolvers.go b/server/internal/integrations/wecom/wecom_resolvers.go
new file mode 100644
index 0000000000..a8fa730ca5
--- /dev/null
+++ b/server/internal/integrations/wecom/wecom_resolvers.go
@@ -0,0 +1,271 @@
+package wecom
+
+// wecom_resolvers.go — the ResolverSet the engine.Router routes through when
+// the inbound channel_type is "wecom". Each interface method translates
+// between the engine's normalized channel.InboundMessage and the wecom store
+// / services. Platform-specific fields the normalized envelope does not carry
+// (BotID, sender userid) come out of the wecom InboundMessage stashed in
+// channel.InboundMessage.Raw.
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "strings"
+
+ "github.com/jackc/pgx/v5"
+ "github.com/jackc/pgx/v5/pgtype"
+
+ "github.com/multica-ai/multica/server/internal/integrations/channel"
+ "github.com/multica-ai/multica/server/internal/integrations/channel/engine"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+)
+
+// originWecomChat is the issue.origin_type label written for issues created
+// via the wecom /issue command. Matches the "lark_chat" pattern (platform +
+// "_chat") so analytics keeps the origin family consistent.
+const originWecomChat = "wecom_chat"
+
+// wecomMsgFromRaw decodes the wecom-side InboundMessage from
+// channel.InboundMessage.Raw. Every resolver ends up doing this at least
+// once; we centralize the JSON tag so a Raw shape change is a single-file
+// edit.
+func wecomMsgFromRaw(msg channel.InboundMessage) (InboundMessage, error) {
+ if len(msg.Raw) == 0 {
+ return InboundMessage{}, errors.New("wecom: inbound message Raw is empty")
+ }
+ var wm InboundMessage
+ if err := json.Unmarshal(msg.Raw, &wm); err != nil {
+ return InboundMessage{}, fmt.Errorf("wecom: decode inbound raw: %w", err)
+ }
+ return wm, nil
+}
+
+// NewResolverSet assembles the wecom ResolverSet from the store, the shared
+// chat-session service, and an outbound replier. wecom has no typing-
+// indicator affordance, so Typing is left nil — the Router treats a nil
+// Typing as a no-op.
+//
+// The replier is optional: pass nil to disable outbound binding prompts.
+func NewResolverSet(
+ store *Store,
+ session engineSessionBinder,
+ replier engine.OutboundReplier,
+) engine.ResolverSet {
+ set := engine.ResolverSet{
+ Installation: &installationResolver{store: store},
+ Identity: &identityResolver{store: store},
+ Dedup: &deduper{store: store},
+ Session: &sessionBinder{session: session},
+ Audit: &auditor{store: store},
+ OriginType: originWecomChat,
+ }
+ if replier != nil {
+ set.Replier = replier
+ }
+ return set
+}
+
+// engineSessionBinder is the slice of engine.ChatSession the wecom binder
+// drives. Declared as an interface so the platform-specific param mapping
+// can be exercised with a fake in unit tests; *engine.ChatSession is the
+// production value.
+type engineSessionBinder interface {
+ EnsureSession(ctx context.Context, in engine.EnsureSessionInput) (pgtype.UUID, error)
+ AppendUserMessage(ctx context.Context, in engine.AppendInput) (engine.AppendResult, error)
+}
+
+// ---- installation routing ----
+
+type installationResolver struct{ store *Store }
+
+// ResolveInstallation looks up the wecom installation by the BotID carried
+// on the inbound event. Every aibot_msg_callback frame identifies the bot
+// via the WebSocket connection it arrived on (one bot per connection); the
+// connector stamps BotID into InboundMessage.Raw so this resolver stays a
+// pure DB lookup rather than needing socket-side plumbing.
+func (r *installationResolver) ResolveInstallation(ctx context.Context, msg channel.InboundMessage) (engine.ResolvedInstallation, error) {
+ wm, err := wecomMsgFromRaw(msg)
+ if err != nil {
+ return engine.ResolvedInstallation{}, err
+ }
+ if wm.BotID == "" {
+ return engine.ResolvedInstallation{}, engine.ErrInstallationNotFound
+ }
+ inst, err := r.store.GetInstallationByBotID(ctx, wm.BotID)
+ if err != nil {
+ if errors.Is(err, pgx.ErrNoRows) {
+ return engine.ResolvedInstallation{}, engine.ErrInstallationNotFound
+ }
+ return engine.ResolvedInstallation{}, err
+ }
+ return engine.ResolvedInstallation{
+ ID: inst.ID,
+ WorkspaceID: inst.WorkspaceID,
+ AgentID: inst.AgentID,
+ InstallerUserID: inst.InstallerUserID,
+ Active: inst.Status == InstallationActive,
+ Platform: inst,
+ }, nil
+}
+
+// ---- identity ----
+
+type identityResolver struct{ store *Store }
+
+// ResolveSender maps the WeCom smart-bot userid (the anonymized "T"-prefixed
+// id the aibot API assigns per bot, from Source.SenderID) to a Multica user
+// via the channel_user_binding table. First-time senders have no row and
+// return engine.ErrSenderUnbound, which the Router pairs with the outbound
+// binding prompt (see OutboundReplier.sendBindingPrompt).
+//
+// Why explicit binding rather than an implicit heuristic: aibot's userids
+// have no relationship to real enterprise userids or emails — they are
+// per-(bot, user) anonymized stable ids — so email-prefix matching (the
+// pattern the internal customer-service adapter used) cannot work. See
+// binding.go for the rationale.
+//
+// Membership re-check: the binding row's existence does NOT prove current
+// workspace membership — a removed member's binding survives until an admin
+// vacuums it. ErrSenderNotMember lets the Router drop silently rather than
+// re-prompt (the correct product outcome, avoids leaking that a user was
+// once a member).
+func (r *identityResolver) ResolveSender(ctx context.Context, inst engine.ResolvedInstallation, msg channel.InboundMessage) (engine.ResolvedIdentity, error) {
+ senderID := strings.TrimSpace(msg.Source.SenderID)
+ if senderID == "" {
+ return engine.ResolvedIdentity{}, engine.ErrSenderUnbound
+ }
+ binding, err := r.store.Queries.GetChannelUserBindingByUserID(ctx, db.GetChannelUserBindingByUserIDParams{
+ InstallationID: inst.ID,
+ ChannelUserID: senderID,
+ })
+ if err != nil {
+ if errors.Is(err, pgx.ErrNoRows) {
+ return engine.ResolvedIdentity{}, engine.ErrSenderUnbound
+ }
+ return engine.ResolvedIdentity{}, err
+ }
+ isMember, err := r.store.IsWorkspaceMember(ctx, inst.WorkspaceID, binding.MulticaUserID)
+ if err != nil {
+ return engine.ResolvedIdentity{}, err
+ }
+ if !isMember {
+ return engine.ResolvedIdentity{}, engine.ErrSenderNotMember
+ }
+ return engine.ResolvedIdentity{UserID: binding.MulticaUserID}, nil
+}
+
+// ---- dedup ----
+
+// deduper is the wecom Deduper. It uses the shared channel_inbound_message_dedup
+// sqlc queries — the same table Feishu / Slack use — so the two-phase
+// idempotency invariant is enforced uniformly across channels.
+type deduper struct{ store *Store }
+
+func (d *deduper) Claim(ctx context.Context, installationID pgtype.UUID, messageID string) (pgtype.UUID, error) {
+ row, err := d.store.Queries.ClaimChannelInboundDedup(ctx, db.ClaimChannelInboundDedupParams{
+ InstallationID: installationID,
+ MessageID: messageID,
+ })
+ if err != nil {
+ if errors.Is(err, pgx.ErrNoRows) {
+ return pgtype.UUID{}, engine.ErrDuplicate
+ }
+ return pgtype.UUID{}, err
+ }
+ return row.ClaimToken, nil
+}
+
+func (d *deduper) Mark(ctx context.Context, installationID pgtype.UUID, messageID string, claimToken pgtype.UUID) error {
+ _, err := d.store.Queries.MarkChannelInboundDedupProcessed(ctx, db.MarkChannelInboundDedupProcessedParams{
+ InstallationID: installationID,
+ MessageID: messageID,
+ ClaimToken: claimToken,
+ })
+ return err
+}
+
+func (d *deduper) Release(ctx context.Context, installationID pgtype.UUID, messageID string, claimToken pgtype.UUID) error {
+ _, err := d.store.Queries.ReleaseChannelInboundDedup(ctx, db.ReleaseChannelInboundDedupParams{
+ InstallationID: installationID,
+ MessageID: messageID,
+ ClaimToken: claimToken,
+ })
+ return err
+}
+
+// ---- session binding ----
+
+type sessionBinder struct{ session engineSessionBinder }
+
+// EnsureSession picks the wecom session-isolation key. For single (p2p)
+// chats the wecom ChatID already IS the userid, one session per user;
+// for group chats we key on the chatid so all group traffic lands in one
+// session — the aibot API does not have a first-class thread concept.
+func (r *sessionBinder) EnsureSession(ctx context.Context, p engine.EnsureSessionParams) (pgtype.UUID, error) {
+ return r.session.EnsureSession(ctx, engine.EnsureSessionInput{
+ WorkspaceID: p.Installation.WorkspaceID,
+ AgentID: p.Installation.AgentID,
+ InstallationID: p.Installation.ID,
+ Sender: p.Sender,
+ BindingKey: p.Message.Source.ChatID,
+ ChatType: p.Message.Source.ChatType,
+ })
+}
+
+func (r *sessionBinder) AppendMessage(ctx context.Context, p engine.AppendParams) (engine.AppendResult, error) {
+ return r.session.AppendUserMessage(ctx, engine.AppendInput{
+ SessionID: p.SessionID,
+ Sender: p.Sender,
+ InstallationID: p.InstallationID,
+ Body: p.Message.Text,
+ CommandText: p.Message.Text, // wecom has no enrichment; command == body
+ MessageID: p.Message.MessageID,
+ ClaimToken: p.ClaimToken,
+ })
+}
+
+// BindMedia is a no-op for wecom. The wecom ResolverSet registers no
+// MediaResolver, so the Router never resolves media for a wecom message
+// (resolveMedia stays false) and this method is never called at runtime; it
+// exists only to satisfy engine.SessionBinder. If wecom gains inbound media
+// support, wire this to a BindMediaRefs on the session store, mirroring the
+// lark binder.
+func (r *sessionBinder) BindMedia(ctx context.Context, p engine.BindMediaParams) error {
+ return nil
+}
+
+// ---- audit ----
+
+type auditor struct{ store *Store }
+
+func (a *auditor) RecordDrop(ctx context.Context, instID pgtype.UUID, msg channel.InboundMessage, reason engine.DropReason) error {
+ var eventType string
+ if wm, err := wecomMsgFromRaw(msg); err == nil {
+ eventType = wm.MsgType
+ }
+ var instIDArg pgtype.UUID
+ if instID.Valid {
+ instIDArg = instID
+ }
+ return a.store.Queries.RecordChannelInboundDrop(ctx, db.RecordChannelInboundDropParams{
+ InstallationID: instIDArg,
+ ChannelType: channelTypeWecom,
+ ChannelChatID: textOrNull(msg.Source.ChatID),
+ EventType: eventType,
+ ChannelEventID: textOrNull(msg.EventID),
+ ChannelMessageID: textOrNull(msg.MessageID),
+ DropReason: string(reason),
+ })
+}
+
+// textOrNull maps an empty string to a NULL pgtype.Text — the shared
+// RecordChannelInboundDrop query uses sqlc.narg on the id columns so we
+// need to pass NULL rather than "".
+func textOrNull(s string) pgtype.Text {
+ if s == "" {
+ return pgtype.Text{}
+ }
+ return pgtype.Text{String: s, Valid: true}
+}
diff --git a/server/internal/integrations/wecom/ws_frame.go b/server/internal/integrations/wecom/ws_frame.go
new file mode 100644
index 0000000000..35df1757e3
--- /dev/null
+++ b/server/internal/integrations/wecom/ws_frame.go
@@ -0,0 +1,280 @@
+package wecom
+
+// ws_frame.go — the aibot WebSocket wire format. Every frame is JSON with a
+// {cmd, headers.req_id, body} envelope. We only parse the frames we act on:
+//
+// inbound — aibot_msg_callback (user message), aibot_event_callback (event)
+// outbound — aibot_subscribe (auth), ping (heartbeat), aibot_send_msg (push),
+// aibot_respond_msg (in-window reply)
+// response — the ack the server writes for aibot_subscribe / ping / send_msg
+//
+// The wire is documented at https://developer.work.weixin.qq.com/document/path/101463 .
+
+import (
+ "encoding/json"
+ "errors"
+ "strings"
+
+ "github.com/multica-ai/multica/server/internal/integrations/channel"
+)
+
+// Frame commands the client sends.
+const (
+ cmdSubscribe = "aibot_subscribe"
+ cmdPing = "ping"
+ cmdSendMsg = "aibot_send_msg"
+ cmdRespondMsg = "aibot_respond_msg"
+)
+
+// Frame commands the server sends. These are what the read loop switches on.
+const (
+ cmdMsgCallback = "aibot_msg_callback"
+ cmdEventCallback = "aibot_event_callback"
+ cmdServerPing = "ping"
+ cmdPong = "pong"
+)
+
+// Event types inside aibot_event_callback.body.event.eventtype.
+const (
+ eventDisconnected = "disconnected_event"
+ eventEnterChat = "enter_chat"
+ eventTemplateCard = "template_card_event"
+ eventFeedback = "feedback_event"
+)
+
+// aibot receiver kinds for aibot_send_msg. WeCom uses ints, not strings.
+const (
+ chatTypeSingleInt = 1
+ chatTypeGroupInt = 2
+)
+
+// frameHeaders carries a per-frame correlation id. Server acks reflect the
+// req_id back so the client can pair requests with responses.
+type frameHeaders struct {
+ ReqID string `json:"req_id"`
+}
+
+// frameEnvelope is the outer shape of every frame the server pushes. Body
+// is left raw so downstream code can unmarshal the specific shape without
+// re-parsing the outer wrapper.
+type frameEnvelope struct {
+ Cmd string `json:"cmd"`
+ Headers frameHeaders `json:"headers"`
+ Body json.RawMessage `json:"body"`
+
+ // Response fields (present when the server acks one of our writes).
+ ErrCode int `json:"errcode"`
+ ErrMsg string `json:"errmsg"`
+}
+
+// aibotMsgCallback is the body of an aibot_msg_callback frame — a user
+// message pushed from a chat to the bot.
+type aibotMsgCallback struct {
+ MsgID string `json:"msgid"`
+ AIBotID string `json:"aibotid"`
+ ChatID string `json:"chatid"`
+ ChatType string `json:"chattype"` // "single" | "group"
+ From struct {
+ UserID string `json:"userid"`
+ } `json:"from"`
+ MsgType string `json:"msgtype"` // "text" | "image" | "voice" | "file" | "video" | "mixed"
+ Text struct {
+ Content string `json:"content"`
+ } `json:"text"`
+ // Image / voice / file / video / mixed have their own fields; we do
+ // not surface them yet — MsgType=="text" is the only case we route.
+}
+
+// aibotEventCallback is the body of an aibot_event_callback frame. We only
+// look at the event type; specific event fields (template-card selection,
+// feedback vote) are not surfaced yet.
+type aibotEventCallback struct {
+ Event struct {
+ EventType string `json:"eventtype"`
+ } `json:"event"`
+}
+
+// ---- normalization ----
+
+// InboundMessage is the wecom-side flattened envelope the WS read loop
+// builds from a decoded aibot_msg_callback. It is stashed into
+// channel.InboundMessage.Raw as JSON so wecom_resolvers.go can reach the
+// platform-specific fields (BotID, ReqID) the cross-platform envelope does
+// not carry.
+type InboundMessage struct {
+ // BotID is the smart-bot identifier this event was delivered to. It
+ // is the routing key the installation resolver uses.
+ BotID string `json:"bot_id"`
+
+ // MsgID is the WeCom per-message identifier used for two-phase dedup.
+ MsgID string `json:"msg_id,omitempty"`
+
+ // MsgType is the raw wecom type ("text", "image", "event", ...). Media
+ // / unknown types round-trip via the cross-platform channel.MsgType enum
+ // (see channelMsgType); the raw string stays here for auditing.
+ MsgType string `json:"msg_type,omitempty"`
+
+ // ChatType is the tencent-internal conversation discriminator
+ // ("single" for 1:1, "group" for a group chat).
+ ChatType string `json:"chat_type,omitempty"`
+
+ // ChatID is the userid (single) or chatid (group) that the message
+ // originated in — the routing identity for outbound + session binding.
+ ChatID string `json:"chat_id,omitempty"`
+
+ // SenderUserID is the userid of the person who typed the message.
+ SenderUserID string `json:"sender_user_id,omitempty"`
+
+ // Content is the human-readable text body when MsgType == "text";
+ // empty for media / events. The cross-platform envelope's Text field
+ // is populated from this.
+ Content string `json:"content,omitempty"`
+
+ // ReqID is the frame req_id the server sent this message with. We
+ // keep it so a future aibot_respond_msg (5s window) can echo it back;
+ // iteration 1 uses aibot_send_msg unconditionally and does not need it.
+ ReqID string `json:"req_id,omitempty"`
+}
+
+// channelMessageFromCallback converts a wecom-side aibot_msg_callback into
+// the cross-platform channel.InboundMessage the engine.Router consumes.
+// The wecom-side InboundMessage is stashed in Raw so wecom_resolvers.go can
+// access platform-specific fields.
+//
+// Routing identity:
+// - single → ChatType=p2p, ChatID=userid, SenderID=userid
+// - group → ChatType=group, ChatID=chatid, SenderID=from.userid
+//
+// A user @-mentioning the bot in a group is not distinguishable from a raw
+// group message on the wire — WeCom only forwards to the bot when it was
+// addressed, so any received group message counts as addressed.
+func channelMessageFromCallback(botID string, mc aibotMsgCallback, reqID string) channel.InboundMessage {
+ chatType := channel.ChatTypeP2P
+ if strings.EqualFold(mc.ChatType, "group") {
+ chatType = channel.ChatTypeGroup
+ }
+ senderID := mc.From.UserID
+ chatID := mc.ChatID
+ if chatType == channel.ChatTypeP2P && chatID == "" {
+ // Some flavors set ChatID only for groups; fall back to the sender.
+ chatID = senderID
+ }
+
+ wm := InboundMessage{
+ BotID: botID,
+ MsgID: mc.MsgID,
+ MsgType: mc.MsgType,
+ ChatType: mc.ChatType,
+ ChatID: chatID,
+ SenderUserID: senderID,
+ Content: mc.Text.Content,
+ ReqID: reqID,
+ }
+ raw, _ := json.Marshal(wm)
+
+ return channel.InboundMessage{
+ EventID: mc.MsgID,
+ MessageID: mc.MsgID,
+ Type: channelMsgType(mc.MsgType),
+ Text: mc.Text.Content,
+ AddressedToBot: true,
+ // A pure /issue command in WeCom should NOT trigger the
+ // agent — the engine already creates the issue and the
+ // OutboundReplier already sends "✅ 已创建 #N". Letting the agent
+ // see "/issue foo" then produces a "I don't recognize this slash
+ // command" reply that just clutters the conversation. wecom is
+ // alone on this — Slack/Lark keep the historical "let the agent
+ // see /issue and respond too" behaviour.
+ SkipAgentRun: isIssueCommand(mc.Text.Content),
+ Source: channel.Source{
+ ChannelType: TypeWecom,
+ ChatID: chatID,
+ ChatType: chatType,
+ SenderID: senderID,
+ },
+ Raw: raw,
+ }
+}
+
+// isIssueCommand mirrors engine.ParseIssueCommand's front-of-body detection
+// without materializing the parsed struct — we only need the yes/no. A pure
+// /issue command starts at the first non-empty line, "/issue" as a whole
+// token, optionally followed by whitespace and the title.
+func isIssueCommand(body string) bool {
+ for _, raw := range strings.Split(body, "\n") {
+ line := strings.TrimSpace(raw)
+ if line == "" {
+ continue
+ }
+ if line == "/issue" {
+ return true
+ }
+ if strings.HasPrefix(line, "/issue ") || strings.HasPrefix(line, "/issue\t") {
+ return true
+ }
+ return false
+ }
+ return false
+}
+
+// channelMsgType maps the raw aibot msg_type onto the normalized enum.
+func channelMsgType(wecomType string) channel.MsgType {
+ switch strings.ToLower(wecomType) {
+ case "text":
+ return channel.MsgTypeText
+ case "image":
+ return channel.MsgTypeImage
+ case "file":
+ return channel.MsgTypeFile
+ case "voice", "audio":
+ return channel.MsgTypeAudio
+ case "video":
+ return channel.MsgTypeVideo
+ default:
+ // Includes "mixed" (text + media): dispatchFrame only routes msgtype
+ // == "text", so anything else is answered with the text-only receipt
+ // and never reaches this normalization. Kept as Unknown rather than
+ // mapping "mixed" → Text, which was dead and implied mixed messages
+ // were routed as text when they are not.
+ return channel.MsgTypeUnknown
+ }
+}
+
+// ---- outbound helpers ----
+
+// subscribeBody builds an aibot_subscribe body. The server responds with an
+// echoed req_id and errcode 0 on success.
+func subscribeBody(botID, secret string) map[string]any {
+ return map[string]any{"bot_id": botID, "secret": secret}
+}
+
+// sendMsgTextBody builds an aibot_send_msg body carrying plain-text
+// content. aibot_send_msg's supported msgtypes are markdown and
+// template_card only — text is NOT accepted on this cmd (contrast
+// aibot_respond_msg, which does accept text). We therefore ship as
+// markdown; the WeCom client renders plain text through the markdown
+// path without any special escaping. chatType is 1 for single, 2 for
+// group.
+func sendMsgTextBody(chatID string, chatType int, content string) (map[string]any, error) {
+ if chatID == "" {
+ return nil, errors.New("wecom: send_msg requires chat_id")
+ }
+ if chatType != chatTypeSingleInt && chatType != chatTypeGroupInt {
+ return nil, errors.New("wecom: send_msg chat_type must be 1 (single) or 2 (group)")
+ }
+ return map[string]any{
+ "chatid": chatID,
+ "chat_type": chatType,
+ "msgtype": "markdown",
+ "markdown": map[string]string{"content": content},
+ }, nil
+}
+
+// aibotChatTypeFromChannel maps the engine's ChatType enum to the int the
+// aibot_send_msg body wants.
+func aibotChatTypeFromChannel(t channel.ChatType) int {
+ if t == channel.ChatTypeGroup {
+ return chatTypeGroupInt
+ }
+ return chatTypeSingleInt
+}
diff --git a/server/internal/integrations/wecom/ws_frame_test.go b/server/internal/integrations/wecom/ws_frame_test.go
new file mode 100644
index 0000000000..08b926484e
--- /dev/null
+++ b/server/internal/integrations/wecom/ws_frame_test.go
@@ -0,0 +1,97 @@
+package wecom
+
+// ws_frame_test.go — pure codec guards: the single-vs-group source mapping
+// (which feeds the #1 security fix — a group message must carry the group
+// chatid in Source.ChatID and the real person in Source.SenderID), the
+// msgtype normalization, and the outbound send-body shape.
+
+import (
+ "testing"
+
+ "github.com/multica-ai/multica/server/internal/integrations/channel"
+)
+
+func TestChannelMessageFromCallback_GroupKeepsSenderDistinctFromChat(t *testing.T) {
+ t.Parallel()
+ mc := aibotMsgCallback{
+ MsgID: "m1",
+ ChatID: "GROUP_CHAT_ID",
+ ChatType: "group",
+ MsgType: "text",
+ }
+ mc.From.UserID = "SENDER_USERID"
+ mc.Text.Content = "hello"
+
+ msg := channelMessageFromCallback("bot-1", mc, "req-1")
+
+ if msg.Source.ChatType != channel.ChatTypeGroup {
+ t.Errorf("chat type = %v, want group", msg.Source.ChatType)
+ }
+ if msg.Source.ChatID != "GROUP_CHAT_ID" {
+ t.Errorf("Source.ChatID = %q, want the group chatid", msg.Source.ChatID)
+ }
+ // The security fix depends on this: the sender is addressable separately
+ // from the room, so the binding token can go to the person privately.
+ if msg.Source.SenderID != "SENDER_USERID" {
+ t.Errorf("Source.SenderID = %q, want the sender userid", msg.Source.SenderID)
+ }
+}
+
+func TestChannelMessageFromCallback_P2PFallsBackChatIDToSender(t *testing.T) {
+ t.Parallel()
+ mc := aibotMsgCallback{MsgID: "m2", ChatID: "", ChatType: "single", MsgType: "text"}
+ mc.From.UserID = "USER_A"
+
+ msg := channelMessageFromCallback("bot-1", mc, "req-2")
+
+ if msg.Source.ChatType != channel.ChatTypeP2P {
+ t.Errorf("chat type = %v, want p2p", msg.Source.ChatType)
+ }
+ if msg.Source.ChatID != "USER_A" {
+ t.Errorf("p2p ChatID = %q, want fallback to sender USER_A", msg.Source.ChatID)
+ }
+}
+
+func TestChannelMsgType_NonTextIsUnknown(t *testing.T) {
+ t.Parallel()
+ cases := map[string]channel.MsgType{
+ "text": channel.MsgTypeText,
+ "image": channel.MsgTypeImage,
+ "file": channel.MsgTypeFile,
+ "voice": channel.MsgTypeAudio,
+ "audio": channel.MsgTypeAudio,
+ "video": channel.MsgTypeVideo,
+ // "mixed" must NOT map to Text: dispatchFrame drops non-text before
+ // normalization, so mapping it to Text was dead and misleading.
+ "mixed": channel.MsgTypeUnknown,
+ "": channel.MsgTypeUnknown,
+ "greetings": channel.MsgTypeUnknown,
+ }
+ for in, want := range cases {
+ if got := channelMsgType(in); got != want {
+ t.Errorf("channelMsgType(%q) = %v, want %v", in, got, want)
+ }
+ }
+}
+
+func TestSendMsgTextBody_ShapeAndChatTypeValidation(t *testing.T) {
+ t.Parallel()
+
+ body, err := sendMsgTextBody("chat-1", chatTypeSingleInt, "hi")
+ if err != nil {
+ t.Fatalf("unexpected error: %v", err)
+ }
+ if body["chatid"] != "chat-1" || body["chat_type"] != chatTypeSingleInt || body["msgtype"] != "markdown" {
+ t.Errorf("unexpected body: %#v", body)
+ }
+
+ if _, err := sendMsgTextBody("", chatTypeSingleInt, "hi"); err == nil {
+ t.Error("empty chatid should error")
+ }
+ if _, err := sendMsgTextBody("chat-1", 0, "hi"); err == nil {
+ t.Error("chat_type 0 should be rejected (must be 1 or 2)")
+ }
+ if _, err := sendMsgTextBody("chat-1", 3, "hi"); err == nil {
+ t.Error("chat_type 3 should be rejected (must be 1 or 2)")
+ }
+}
diff --git a/server/internal/integrations/wecom/ws_sender.go b/server/internal/integrations/wecom/ws_sender.go
new file mode 100644
index 0000000000..cc9dfe8c89
--- /dev/null
+++ b/server/internal/integrations/wecom/ws_sender.go
@@ -0,0 +1,111 @@
+package wecom
+
+// ws_sender.go — a serialized writer for one WebSocket connection. gorilla
+// forbids concurrent writes so every outbound frame goes through the same
+// mutex; the ping loop, subscribe handshake, and Send() calls all share
+// this writer.
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "log/slog"
+ "net/http"
+ "sync"
+ "time"
+
+ "github.com/gorilla/websocket"
+)
+
+// wsConn is the subset of gorilla's Conn the wecom package uses. Kept
+// minimal so tests can inject a fake without embedding all of gorilla's
+// surface.
+type wsConn interface {
+ ReadMessage() (int, []byte, error)
+ WriteMessage(messageType int, data []byte) error
+ SetReadDeadline(t time.Time) error
+ SetWriteDeadline(t time.Time) error
+ Close() error
+}
+
+// Dialer opens a WebSocket connection to the aibot endpoint. Production
+// uses gorilla's default dialer; tests wire a fake pointing at an
+// httptest.Server.
+type Dialer interface {
+ DialContext(ctx context.Context, url string, header http.Header) (wsConn, *http.Response, error)
+}
+
+// defaultDialer is the production Dialer. Proxy is set explicitly because a
+// zero-valued websocket.Dialer has a nil Proxy and ignores the environment,
+// unlike websocket.DefaultDialer — and self-hosted deployments behind a
+// corporate egress proxy reach the WeCom endpoint only through
+// HTTPS_PROXY.
+var defaultDialer Dialer = gorillaDialer{d: &websocket.Dialer{
+ HandshakeTimeout: handshakeTimeout,
+ Proxy: http.ProxyFromEnvironment,
+}}
+
+type gorillaDialer struct {
+ d *websocket.Dialer
+}
+
+func (g gorillaDialer) DialContext(ctx context.Context, u string, header http.Header) (wsConn, *http.Response, error) {
+ conn, resp, err := g.d.DialContext(ctx, u, header)
+ if err != nil {
+ return nil, resp, err
+ }
+ return &gorillaWSConn{Conn: conn}, resp, nil
+}
+
+// gorillaWSConn wraps *websocket.Conn so it satisfies wsConn without leaking
+// the concrete type into wsConn's method signatures.
+type gorillaWSConn struct {
+ *websocket.Conn
+}
+
+// wsSender serializes writes to one WebSocket connection. Instantiated per
+// Connect() call and dropped when the connection ends.
+type wsSender struct {
+ conn wsConn
+ mu sync.Mutex
+ log *slog.Logger
+}
+
+func newWSSender(conn wsConn, log *slog.Logger) *wsSender {
+ if log == nil {
+ log = slog.Default()
+ }
+ return &wsSender{conn: conn, log: log}
+}
+
+// write marshals frame to JSON and pushes it under the writer mutex. The
+// caller must not hold sendMu on wecomChannel — nothing here reaches back
+// into the Channel.
+func (s *wsSender) write(frame map[string]any) error {
+ payload, err := json.Marshal(frame)
+ if err != nil {
+ return fmt.Errorf("wecom: marshal frame: %w", err)
+ }
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ if err := s.conn.SetWriteDeadline(time.Now().Add(writeDeadline)); err != nil {
+ return err
+ }
+ return s.conn.WriteMessage(websocket.TextMessage, payload)
+}
+
+// sendText pushes an aibot_send_msg (proactive push) with plain text to a
+// specific chat. Callers pass channel.ChatType so the aibot chat_type int
+// (1=single, 2=group) is decided at the wecom-side boundary, not the
+// engine's. Used by wecomChannel.Send and OutboundReplier.
+func (s *wsSender) sendText(chatID string, chatTypeInt int, content string) error {
+ body, err := sendMsgTextBody(chatID, chatTypeInt, content)
+ if err != nil {
+ return err
+ }
+ return s.write(map[string]any{
+ "cmd": cmdSendMsg,
+ "headers": frameHeaders{ReqID: newReqID()},
+ "body": body,
+ })
+}
diff --git a/server/migrations/263_issue_origin_wecom_chat.down.sql b/server/migrations/263_issue_origin_wecom_chat.down.sql
new file mode 100644
index 0000000000..c164c48706
--- /dev/null
+++ b/server/migrations/263_issue_origin_wecom_chat.down.sql
@@ -0,0 +1,16 @@
+-- Revert to the pre-wecom_chat issue_origin_type_check list. This restores the
+-- state left by the newest earlier issue_origin_* migration, which includes
+-- 'dingtalk_chat' (259) — dropping it here would break DingTalk.
+--
+-- The down path deliberately VALIDATEs in this same file, unlike the up path.
+-- Narrowing a CHECK can genuinely be violated by existing data, so this must
+-- fail closed while wecom_chat rows remain rather than silently leaving rows
+-- the constraint forbids. That means accepting the ACCESS EXCLUSIVE lock for
+-- the scan — an acceptable trade for an operator-driven rollback, which is
+-- rare and supervised, where a silently untrusted constraint would be worse.
+-- Same reasoning as 259_issue_origin_dingtalk_chat.down.sql.
+ALTER TABLE issue DROP CONSTRAINT IF EXISTS issue_origin_type_check;
+ALTER TABLE issue ADD CONSTRAINT issue_origin_type_check
+ CHECK (origin_type IN ('autopilot', 'quick_create', 'lark_chat', 'slack_chat', 'agent_create', 'dingtalk_chat'))
+ NOT VALID;
+ALTER TABLE issue VALIDATE CONSTRAINT issue_origin_type_check;
diff --git a/server/migrations/263_issue_origin_wecom_chat.up.sql b/server/migrations/263_issue_origin_wecom_chat.up.sql
new file mode 100644
index 0000000000..5e49da3728
--- /dev/null
+++ b/server/migrations/263_issue_origin_wecom_chat.up.sql
@@ -0,0 +1,30 @@
+-- Extend issue.origin_type to allow the WeCom smart-bot (aibot) `/issue`
+-- command path to stamp issues with origin_type='wecom_chat' + origin_id=
+-- <chat_session.id>. Mirrors 111_issue_origin_lark_chat and
+-- 131_issue_origin_slack_chat — same origin_id semantics (the chat_session
+-- the /issue command was typed in), different label because analytics and
+-- inbound routing key on this string.
+--
+-- The full list is respecified (not just appended) because ADD CONSTRAINT
+-- cannot append a value. It must therefore carry every value added by earlier
+-- migrations — including 'dingtalk_chat' (migration 259) — or this rebuild
+-- would silently drop it. Keep this list in sync with the newest
+-- issue_origin_* migration when rebasing.
+--
+-- The CHECK is only WIDENED (one new allowed value), so every existing row
+-- already satisfies it. Add it NOT VALID so this statement takes ACCESS
+-- EXCLUSIVE on issue only briefly, without a full-table scan; migration 264
+-- runs the VALIDATE under SHARE UPDATE EXCLUSIVE, which does not block reads
+-- or writes. issue is a hot core table, so a plain validating ADD here would
+-- block all traffic on it for the length of the scan.
+--
+-- Keep the VALIDATE in its own migration file (the 259/260 pattern), NOT
+-- merely as a later statement in this one: the migration runner hands each
+-- file to a single conn.Exec, so every statement in a file shares one implicit
+-- transaction and the ACCESS EXCLUSIVE taken here would be held until the file
+-- finishes — carrying the strong lock straight through the validation scan and
+-- defeating the split.
+ALTER TABLE issue DROP CONSTRAINT IF EXISTS issue_origin_type_check;
+ALTER TABLE issue ADD CONSTRAINT issue_origin_type_check
+ CHECK (origin_type IN ('autopilot', 'quick_create', 'lark_chat', 'slack_chat', 'agent_create', 'dingtalk_chat', 'wecom_chat'))
+ NOT VALID;
diff --git a/server/migrations/264_issue_origin_wecom_chat_validate.down.sql b/server/migrations/264_issue_origin_wecom_chat_validate.down.sql
new file mode 100644
index 0000000000..bd4c9c5bb0
--- /dev/null
+++ b/server/migrations/264_issue_origin_wecom_chat_validate.down.sql
@@ -0,0 +1,8 @@
+-- PostgreSQL cannot mark a validated constraint NOT VALID again. Recreate it
+-- to restore the state immediately after migration 263 (present, enforcing new
+-- writes, not yet validated). Mirrors
+-- 260_issue_origin_dingtalk_chat_validate.down.sql.
+ALTER TABLE issue DROP CONSTRAINT IF EXISTS issue_origin_type_check;
+ALTER TABLE issue ADD CONSTRAINT issue_origin_type_check
+ CHECK (origin_type IN ('autopilot', 'quick_create', 'lark_chat', 'slack_chat', 'agent_create', 'dingtalk_chat', 'wecom_chat'))
+ NOT VALID;
diff --git a/server/migrations/264_issue_origin_wecom_chat_validate.up.sql b/server/migrations/264_issue_origin_wecom_chat_validate.up.sql
new file mode 100644
index 0000000000..e1e8496b3f
--- /dev/null
+++ b/server/migrations/264_issue_origin_wecom_chat_validate.up.sql
@@ -0,0 +1,9 @@
+-- Validate the widened issue_origin_type_check that migration 263 added
+-- NOT VALID. This takes SHARE UPDATE EXCLUSIVE while scanning issue, which
+-- permits normal SELECT/INSERT/UPDATE/DELETE traffic to continue — the whole
+-- point of splitting the two steps across migration files (the 259/260
+-- pattern).
+--
+-- 263 only WIDENED the allowed set, so every pre-existing row already
+-- satisfies the constraint and this scan cannot fail on legacy data.
+ALTER TABLE issue VALIDATE CONSTRAINT issue_origin_type_check;
diff --git a/server/pkg/db/generated/channel.sql.go b/server/pkg/db/generated/channel.sql.go
index 209fbf534c..7d50d48290 100644
--- a/server/pkg/db/generated/channel.sql.go
+++ b/server/pkg/db/generated/channel.sql.go
@@ -684,6 +684,48 @@ func (q *Queries) DeleteChannelUserBindingsByWorkspaceMember(ctx context.Context
return err
}
+const findChannelBindingForMember = `-- name: FindChannelBindingForMember :one
+SELECT b.id, b.workspace_id, b.multica_user_id, b.installation_id, b.channel_type, b.channel_user_id, b.config, b.bound_at FROM channel_user_binding b
+JOIN channel_installation ci ON ci.id = b.installation_id
+WHERE b.workspace_id = $1
+ AND b.multica_user_id = $2
+ AND b.channel_type = $3
+ AND ci.status = 'active'
+ORDER BY b.bound_at DESC
+LIMIT 1
+`
+
+type FindChannelBindingForMemberParams struct {
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ MulticaUserID pgtype.UUID `json:"multica_user_id"`
+ ChannelType string `json:"channel_type"`
+}
+
+// Outbound notification lookup: given a Multica member and a channel_type,
+// return the (installation, channel_user_id) that outbound push should
+// target. The wecom smart-bot inbox-notification path uses this to decide
+// whether to deliver via the bot at all — no row means "unbound member,
+// fall back to the legacy path (TOF/RTX)".
+//
+// If a member has bound multiple installations of the same channel_type in
+// one workspace (multi-bot org), the most-recently-bound wins — matches
+// FindReusableChannelUserBinding's tiebreak so the two lookups agree.
+func (q *Queries) FindChannelBindingForMember(ctx context.Context, arg FindChannelBindingForMemberParams) (ChannelUserBinding, error) {
+ row := q.db.QueryRow(ctx, findChannelBindingForMember, arg.WorkspaceID, arg.MulticaUserID, arg.ChannelType)
+ var i ChannelUserBinding
+ err := row.Scan(
+ &i.ID,
+ &i.WorkspaceID,
+ &i.MulticaUserID,
+ &i.InstallationID,
+ &i.ChannelType,
+ &i.ChannelUserID,
+ &i.Config,
+ &i.BoundAt,
+ )
+ return i, err
+}
+
const findReusableChannelUserBinding = `-- name: FindReusableChannelUserBinding :one
SELECT b.id, b.workspace_id, b.multica_user_id, b.installation_id, b.channel_type, b.channel_user_id, b.config, b.bound_at FROM channel_user_binding b
JOIN channel_installation ci ON ci.id = b.installation_id
diff --git a/server/pkg/db/queries/channel.sql b/server/pkg/db/queries/channel.sql
index 036eac35a8..428178c994 100644
--- a/server/pkg/db/queries/channel.sql
+++ b/server/pkg/db/queries/channel.sql
@@ -370,6 +370,25 @@ RETURNING *;
SELECT * FROM channel_user_binding
WHERE installation_id = $1 AND channel_user_id = $2;
+-- name: FindChannelBindingForMember :one
+-- Outbound notification lookup: given a Multica member and a channel_type,
+-- return the (installation, channel_user_id) that outbound push should
+-- target. The wecom smart-bot inbox-notification path uses this to decide
+-- whether to deliver via the bot at all — no row means "unbound member,
+-- fall back to the legacy path (TOF/RTX)".
+--
+-- If a member has bound multiple installations of the same channel_type in
+-- one workspace (multi-bot org), the most-recently-bound wins — matches
+-- FindReusableChannelUserBinding's tiebreak so the two lookups agree.
+SELECT b.* FROM channel_user_binding b
+JOIN channel_installation ci ON ci.id = b.installation_id
+WHERE b.workspace_id = sqlc.arg('workspace_id')
+ AND b.multica_user_id = sqlc.arg('multica_user_id')
+ AND b.channel_type = sqlc.arg('channel_type')
+ AND ci.status = 'active'
+ORDER BY b.bound_at DESC
+LIMIT 1;
+
-- name: FindReusableChannelUserBinding :one
-- Cross-installation account-link reuse (MUL-3911). When a platform user
-- messages an installation they have NOT linked, but the SAME user id is already
diff --git a/server/pkg/protocol/events.go b/server/pkg/protocol/events.go
index aabcff4a2d..3a347d885c 100644
--- a/server/pkg/protocol/events.go
+++ b/server/pkg/protocol/events.go
@@ -187,4 +187,13 @@ const (
// as Slack's BYO channel installation.
EventDingTalkInstallationCreated = "dingtalk_installation:created"
EventDingTalkInstallationRevoked = "dingtalk_installation:revoked"
+
+ // WeCom smart-bot installation lifecycle. Same semantics as Lark /
+ // Slack: `created` covers both first install and re-install via
+ // UpsertChannelInstallation (the UNIQUE on (workspace_id, agent_id,
+ // channel_type) means at most one row per agent); `revoked` flips
+ // status without deleting the row. Front-ends invalidate the wecom
+ // installations query on either.
+ EventWecomInstallationCreated = "wecom_installation:created"
+ EventWecomInstallationRevoked = "wecom_installation:revoked"
)