Skip to content

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

Go

MUL-8388: feat(wecom): create and connect a bot by scanning a QR code (#9697)

Xichang(Seacen) Zhao7468052dc3e2
diff --git a/.env.example b/.env.example
index 6b8492a6a7..572c6f3fe2 100644
--- a/.env.example
+++ b/.env.example
@@ -334,6 +334,15 @@ GOOGLE_REDIRECT_URI=${FRONTEND_ORIGIN}/auth/callback
# (64:ff9b::/96, 64:ff9b:1::/48, 2002::/16 —
# IPv4 addresses in an IPv6 spelling) are refused
# regardless and cannot be opened this way.
+# MULTICA_WECOM_SOURCE_ID The WeCom-issued caller id the scan-code
+# install flow puts in ?source= on
+# /ai/qc/generate and /ai/qc/query_result. Empty =
+# the built-in "multica"; set it only if WeCom
+# issued your organisation a source of its own.
+# Nothing else reads it — inbound and outbound
+# chat go over the long connection and never
+# touch these endpoints — so a wrong value breaks
+# scanning a QR to add the bot, and nothing else.
# MULTICA_WECOM_TRACE 1 = log every frame this adapter reads and
# writes, so a real-device session can be checked
# against the server afterwards. Empty / anything
@@ -368,6 +377,7 @@ GOOGLE_REDIRECT_URI=${FRONTEND_ORIGIN}/auth/callback
MULTICA_WECOM_SECRET_KEY=
MULTICA_WECOM_DEFAULT_LOCALE=
MULTICA_WECOM_MEDIA_ALLOW_CIDRS=
+MULTICA_WECOM_SOURCE_ID=
MULTICA_WECOM_TRACE=
# S3 / CloudFront
diff --git a/docker-compose.selfhost.yml b/docker-compose.selfhost.yml
index 232df1c1ce..97823391be 100644
--- a/docker-compose.selfhost.yml
+++ b/docker-compose.selfhost.yml
@@ -205,6 +205,11 @@ services:
# as it ships; set it only behind a fake-IP proxy whose pool would
# otherwise get every attachment refused. See .env.example.
MULTICA_WECOM_MEDIA_ALLOW_CIDRS: ${MULTICA_WECOM_MEDIA_ALLOW_CIDRS:-}
+ # The WeCom-issued caller id the scan-code install flow sends as
+ # ?source=. Empty (the default) uses the built-in "multica"; set it only
+ # if WeCom issued your organisation its own source. Nothing but the QR
+ # install endpoints reads it.
+ MULTICA_WECOM_SOURCE_ID: ${MULTICA_WECOM_SOURCE_ID:-}
# 1 = log every inbound and outbound WeCom frame, including the first
# 120 runes of each message body, so a real-device session can be
# checked against the server afterwards. Off unless set; turn it on only
diff --git a/packages/core/api/client.ts b/packages/core/api/client.ts
index e21cb3b25e..d3cbaf969c 100644
--- a/packages/core/api/client.ts
+++ b/packages/core/api/client.ts
@@ -209,6 +209,8 @@ import type {
WecomInstallation,
ListWecomInstallationsResponse,
RegisterWecomBYORequest,
+ BeginWecomInstallResponse,
+ WecomInstallStatusResponse,
RedeemWecomBindingTokenResponse,
TelegramInstallation,
ListTelegramInstallationsResponse,
@@ -384,6 +386,10 @@ import {
WecomInstallationSchema,
ListWecomInstallationsResponseSchema,
RedeemWecomBindingTokenResponseSchema,
+ BeginWecomInstallResponseSchema,
+ MALFORMED_BEGIN_WECOM_INSTALL_RESPONSE,
+ WecomInstallStatusResponseSchema,
+ MALFORMED_WECOM_INSTALL_STATUS_RESPONSE,
EMPTY_WECOM_INSTALLATION,
EMPTY_LIST_WECOM_INSTALLATIONS_RESPONSE,
ListLarkInstallationsResponseSchema,
@@ -5397,6 +5403,51 @@ export class ApiClient {
});
}
+ // beginWecomInstall starts (or resumes) a scan-code install: the backend
+ // hands back a session id, and the install worker fetches the QR from WeCom
+ // out of band. Callers poll getWecomInstallStatus for the QR itself.
+ //
+ // idempotencyKey must be stable for one user gesture — a retried or
+ // double-submitted request with the same key reuses the existing session
+ // rather than burning a WeCom generate quota slot on a second QR.
+ async beginWecomInstall(
+ workspaceId: string,
+ agentId: string,
+ idempotencyKey: string,
+ ): Promise<BeginWecomInstallResponse> {
+ const search = new URLSearchParams({ agent_id: agentId });
+ const raw = await this.fetch<unknown>(
+ `/api/workspaces/${workspaceId}/wecom/install/begin?${search.toString()}`,
+ {
+ method: "POST",
+ headers: { "Idempotency-Key": idempotencyKey },
+ },
+ );
+ return parseWithFallback(
+ raw,
+ BeginWecomInstallResponseSchema,
+ MALFORMED_BEGIN_WECOM_INSTALL_RESPONSE,
+ { endpoint: "POST /api/workspaces/:id/wecom/install/begin" },
+ );
+ }
+
+ // getWecomInstallStatus is one poll of a scan-install session. The response
+ // carries the QR while pending, and the installation id once bound.
+ async getWecomInstallStatus(
+ workspaceId: string,
+ sessionId: string,
+ ): Promise<WecomInstallStatusResponse> {
+ const raw = await this.fetch<unknown>(
+ `/api/workspaces/${workspaceId}/wecom/install/${sessionId}`,
+ );
+ return parseWithFallback(
+ raw,
+ WecomInstallStatusResponseSchema,
+ MALFORMED_WECOM_INSTALL_STATUS_RESPONSE,
+ { endpoint: "GET /api/workspaces/:id/wecom/install/:sessionId" },
+ );
+ }
+
async deleteWecomInstallation(workspaceId: string, installationId: string): Promise<void> {
await this.fetch(`/api/workspaces/${workspaceId}/wecom/installations/${installationId}`, {
method: "DELETE",
diff --git a/packages/core/api/schema.test.ts b/packages/core/api/schema.test.ts
index 9a0c3d1abf..2eea5fe34b 100644
--- a/packages/core/api/schema.test.ts
+++ b/packages/core/api/schema.test.ts
@@ -900,6 +900,51 @@ describe("ApiClient schema fallback", () => {
});
});
+ describe("listWecomInstallations", () => {
+ it("falls back to a safe empty shape when the response is malformed", async () => {
+ stubFetchJson({ installations: "not-an-array", configured: true });
+ const client = new ApiClient("https://api.example.test");
+ const res = await client.listWecomInstallations("ws-1");
+ expect(res).toEqual({ installations: [], configured: false });
+ });
+
+ // The settings tab shows the QR install entry point only when this is
+ // exactly true, so the flag has to survive parsing.
+ it("keeps both install flags, and treats a missing one as off", async () => {
+ stubFetchJson({
+ installations: [{ id: "wc-1", status: "active" }],
+ configured: true,
+ install_supported: true,
+ scan_install_supported: true,
+ future_field: true,
+ });
+ const client = new ApiClient("https://api.example.test");
+ const res = await client.listWecomInstallations("ws-1");
+ expect(res.install_supported).toBe(true);
+ expect(res.scan_install_supported).toBe(true);
+
+ // A server that predates the scan flow sends neither, and must not be
+ // read as "scanning is available".
+ stubFetchJson({ installations: [], configured: true });
+ const older = await client.listWecomInstallations("ws-1");
+ expect(older.scan_install_supported).toBeUndefined();
+ expect(older.scan_install_supported === true).toBe(false);
+ });
+
+ // The flag has to be VALIDATED, not merely passed through: this object is
+ // loose, so an undeclared key would survive parsing untouched.
+ it("does not let a non-boolean scan flag through unvalidated", async () => {
+ stubFetchJson({
+ installations: [],
+ configured: true,
+ scan_install_supported: "yes",
+ });
+ const client = new ApiClient("https://api.example.test");
+ const res = await client.listWecomInstallations("ws-1");
+ expect(res.scan_install_supported).toBeUndefined();
+ });
+ });
+
describe("getConfig", () => {
it("preserves an omitted daemon setup target for legacy self-host detection", async () => {
stubFetchJson({
diff --git a/packages/core/api/schemas.ts b/packages/core/api/schemas.ts
index 3c64bf001f..99b99c973f 100644
--- a/packages/core/api/schemas.ts
+++ b/packages/core/api/schemas.ts
@@ -46,6 +46,8 @@ import type {
WecomInstallation,
ListLarkInstallationsResponse,
ListWecomInstallationsResponse,
+ BeginWecomInstallResponse,
+ WecomInstallStatusResponse,
RedeemWecomBindingTokenResponse,
TelegramInstallation,
ListTelegramInstallationsResponse,
@@ -3495,6 +3497,10 @@ export const ListWecomInstallationsResponseSchema = z.object({
installations: z.array(WecomInstallationSchema).default([]),
configured: z.boolean().default(false),
install_supported: z.boolean().optional(),
+ // The settings tab gates the QR install entry point on this, so it is
+ // declared and validated here rather than left to pass through the loose
+ // object unchecked.
+ scan_install_supported: z.boolean().optional(),
}).loose();
export const EMPTY_LIST_WECOM_INSTALLATIONS_RESPONSE: ListWecomInstallationsResponse = {
@@ -3502,6 +3508,37 @@ export const EMPTY_LIST_WECOM_INSTALLATIONS_RESPONSE: ListWecomInstallationsResp
configured: false,
};
+export const BeginWecomInstallResponseSchema = z.object({
+ session_id: z.string(),
+ status: z.string().default("error"),
+ poll_interval_seconds: z.number().optional().default(1),
+}).loose();
+
+// A malformed begin response degrades to a terminal error rather than a session
+// the client would poll forever with an empty id.
+export const MALFORMED_BEGIN_WECOM_INSTALL_RESPONSE: BeginWecomInstallResponse = {
+ session_id: "",
+ status: "error",
+ poll_interval_seconds: 1,
+};
+
+export const WecomInstallStatusResponseSchema = z.object({
+ status: z.string().default("error"),
+ qr_code_url: z.string().optional(),
+ expires_in_seconds: z.number().optional(),
+ poll_interval_seconds: z.number().optional().default(2),
+ installation_id: z.string().optional(),
+ error_reason: z.string().optional(),
+}).loose();
+
+// Same reasoning: an unparseable status stops the poll loop instead of leaving
+// the dialog spinning on a response nobody can read.
+export const MALFORMED_WECOM_INSTALL_STATUS_RESPONSE: WecomInstallStatusResponse = {
+ status: "error",
+ poll_interval_seconds: 2,
+ error_reason: "internal_error",
+};
+
export const RedeemWecomBindingTokenResponseSchema = z.object({
workspace_id: z.string().default(""),
installation_id: z.string().default(""),
diff --git a/packages/core/types/index.ts b/packages/core/types/index.ts
index e89c4aabbd..cc2d90d352 100644
--- a/packages/core/types/index.ts
+++ b/packages/core/types/index.ts
@@ -268,6 +268,8 @@ export type {
ListWecomInstallationsResponse,
RegisterWecomBYORequest,
RedeemWecomBindingTokenResponse,
+ BeginWecomInstallResponse,
+ WecomInstallStatusResponse,
} from "./wecom";
export type {
TelegramInstallation,
diff --git a/packages/core/types/wecom.ts b/packages/core/types/wecom.ts
index 86b4fea6ea..56f3dea171 100644
--- a/packages/core/types/wecom.ts
+++ b/packages/core/types/wecom.ts
@@ -25,6 +25,10 @@ export interface ListWecomInstallationsResponse {
* a separate flag for parity with Slack / Lark; optional so a desktop build
* that predates it treats it as off. */
install_supported?: boolean;
+ /** Whether the QR scan-code install is available. It needs a QR provider on
+ * top of the secret key, so it can be off where the BYO path works. Optional
+ * so a desktop build that predates it treats it as off and shows only BYO. */
+ scan_install_supported?: boolean;
}
/** Request body for the Web UI's BYO Connect dialog. The first two fields are
@@ -51,3 +55,37 @@ export interface RedeemWecomBindingTokenResponse {
installation_id: string;
wecom_user_id: string;
}
+
+/** Response to POST /wecom/install/begin. Nothing exists yet at this point —
+ * the QR is fetched out of band by the install worker, so the client polls
+ * `session_id` until the status carries one. */
+export interface BeginWecomInstallResponse {
+ session_id: string;
+ status: "creating" | "pending" | "success" | "error" | string;
+ /** How long the client should wait before its next status poll. */
+ poll_interval_seconds: number;
+}
+
+/** One scan-install status poll.
+ *
+ * `qr_code_url` and `expires_in_seconds` are present only while the status is
+ * "pending": there is nothing to render before the QR has been generated, and
+ * nothing to render once it has been scanned or has expired. */
+export interface WecomInstallStatusResponse {
+ status: "creating" | "pending" | "success" | "error" | string;
+ qr_code_url?: string;
+ expires_in_seconds?: number;
+ poll_interval_seconds: number;
+ /** Set once the bot is bound, on status === "success". */
+ installation_id?: string;
+ /** Stable machine code the UI switches on to pick its copy. */
+ error_reason?:
+ | "expired"
+ | "generate_failed"
+ | "integration_unconfigured"
+ | "installation_conflict"
+ | "bind_failed"
+ | "wecom_protocol_error"
+ | "internal_error"
+ | string;
+}
diff --git a/packages/views/locales/en/settings.json b/packages/views/locales/en/settings.json
index a6d23a2b56..9f2073396f 100644
--- a/packages/views/locales/en/settings.json
+++ b/packages/views/locales/en/settings.json
@@ -1137,6 +1137,27 @@
"byo_credentials_rejected": "WeCom rejected this Bot ID and secret. Check both on the WeCom admin console, and that it is a smart bot with the long connection enabled.",
"byo_credentials_unverifiable": "Couldn't reach WeCom to verify this bot. Your credentials were not changed — try again in a moment.",
"byo_install_failed": "Couldn't save this bot — something went wrong on our side. Your credentials were not changed; try again, and contact support if it keeps failing.",
+ "scan_option_title": "Create a new bot",
+ "scan_option_description": "Scan a QR code in WeCom to create a brand-new smart bot and connect it.",
+ "byo_option_title": "Connect an existing bot",
+ "byo_option_description": "Paste the Bot ID and secret of a smart bot you already created.",
+ "scan_dialog_title": "Scan to create a WeCom bot",
+ "scan_starting": "Preparing the QR code…",
+ "scan_hint": "Open WeCom on your phone and scan this code to create the bot.",
+ "scan_expires_in": "Expires in {{seconds}}s",
+ "scan_success_toast": "WeCom bot created and connected",
+ "scan_again": "Get a new code",
+ "scan_close": "Close",
+ "scan_error_expired": "The QR code expired before it was scanned.",
+ "scan_error_generate_failed": "Could not get a QR code from WeCom. Try again in a moment.",
+ "scan_error_integration_unconfigured": "Scan install is not enabled on this server.",
+ "scan_error_installation_conflict": "This bot is already connected elsewhere. Disconnect it there, then scan again.",
+ "scan_error_bind_failed": "The bot was created in WeCom but could not be connected to this agent. Delete it in WeCom, then scan again.",
+ "scan_error_wecom_protocol_error": "WeCom returned an unexpected response.",
+ "scan_error_internal_error": "Something went wrong. Try again.",
+ "scan_error_session_lost": "This install session is no longer available. Get a new code.",
+ "scan_error_already_connected": "This agent already has a connected WeCom bot. Disconnect it first.",
+ "scan_error_rate_limited": "Too many attempts. Wait a few minutes and try again.",
"byo_failed_toast": "Could not connect the WeCom bot"
},
"telegram": {
diff --git a/packages/views/locales/fr/settings.json b/packages/views/locales/fr/settings.json
index 9e5d7347ac..415edae931 100644
--- a/packages/views/locales/fr/settings.json
+++ b/packages/views/locales/fr/settings.json
@@ -1137,6 +1137,27 @@
"byo_credentials_rejected": "WeCom a rejeté cet ID de bot et ce secret. Vérifiez les deux dans la console d'administration WeCom, et qu'il s'agit bien d'un bot intelligent avec la connexion longue activée.",
"byo_credentials_unverifiable": "Impossible de joindre WeCom pour vérifier ce bot. Vos identifiants n'ont pas été modifiés — réessayez dans un instant.",
"byo_install_failed": "Impossible d'enregistrer ce bot — une erreur est survenue de notre côté. Vos identifiants n'ont pas été modifiés ; réessayez, et contactez le support si le problème persiste.",
+ "scan_option_title": "Créer un nouveau bot",
+ "scan_option_description": "Scannez un code QR dans WeCom pour créer un nouveau bot intelligent et le connecter.",
+ "byo_option_title": "Connecter un bot existant",
+ "byo_option_description": "Saisissez l'ID du bot et le secret d'un bot intelligent que vous avez déjà créé.",
+ "scan_dialog_title": "Scanner pour créer un bot WeCom",
+ "scan_starting": "Préparation du code QR…",
+ "scan_hint": "Ouvrez WeCom sur votre téléphone et scannez ce code pour créer le bot.",
+ "scan_expires_in": "Expire dans {{seconds}} s",
+ "scan_success_toast": "Bot WeCom créé et connecté",
+ "scan_again": "Obtenir un nouveau code",
+ "scan_close": "Fermer",
+ "scan_error_expired": "Le code QR a expiré avant d'être scanné.",
+ "scan_error_generate_failed": "Impossible d'obtenir un code QR auprès de WeCom. Réessayez dans un instant.",
+ "scan_error_integration_unconfigured": "L'installation par code QR n'est pas activée sur ce serveur.",
+ "scan_error_installation_conflict": "Ce bot est déjà connecté ailleurs. Déconnectez-le là-bas, puis scannez à nouveau.",
+ "scan_error_bind_failed": "Le bot a été créé dans WeCom mais n'a pas pu être connecté à cet agent. Supprimez-le dans WeCom, puis scannez à nouveau.",
+ "scan_error_wecom_protocol_error": "WeCom a renvoyé une réponse inattendue.",
+ "scan_error_internal_error": "Un problème est survenu. Réessayez.",
+ "scan_error_session_lost": "Cette session d'installation n'est plus disponible. Obtenez un nouveau code.",
+ "scan_error_already_connected": "Cet agent a déjà un bot WeCom connecté. Déconnectez-le d'abord.",
+ "scan_error_rate_limited": "Trop de tentatives. Patientez quelques minutes, puis réessayez.",
"byo_failed_toast": "Impossible de connecter le bot WeCom"
},
"telegram": {
diff --git a/packages/views/locales/ja/settings.json b/packages/views/locales/ja/settings.json
index 4469345628..449db9c309 100644
--- a/packages/views/locales/ja/settings.json
+++ b/packages/views/locales/ja/settings.json
@@ -1131,6 +1131,27 @@
"byo_credentials_rejected": "WeCom がこの Bot ID とシークレットを拒否しました。WeCom 管理コンソールで両方を確認し、長時間接続が有効なスマートボットであることもご確認ください。",
"byo_credentials_unverifiable": "WeCom に接続できず、このボットを検証できませんでした。認証情報は変更されていません。少し時間をおいてもう一度お試しください。",
"byo_install_failed": "ボットを保存できませんでした。こちら側の問題です。認証情報は変更されていません。もう一度お試しいただき、続くようならサポートにご連絡ください。",
+ "scan_option_title": "新しいボットを作成",
+ "scan_option_description": "WeCom で QR コードをスキャンして新しいスマートボットを作成し、接続します。",
+ "byo_option_title": "既存のボットを接続",
+ "byo_option_description": "すでに作成済みのスマートボットの Bot ID とシークレットを入力します。",
+ "scan_dialog_title": "QR コードで WeCom ボットを作成",
+ "scan_starting": "QR コードを準備中…",
+ "scan_hint": "スマートフォンで WeCom を開き、この QR コードをスキャンしてボットを作成してください。",
+ "scan_expires_in": "残り {{seconds}} 秒",
+ "scan_success_toast": "WeCom ボットを作成して接続しました",
+ "scan_again": "新しいコードを取得",
+ "scan_close": "閉じる",
+ "scan_error_expired": "スキャンされる前に QR コードが期限切れになりました。",
+ "scan_error_generate_failed": "WeCom から QR コードを取得できませんでした。しばらくしてから再試行してください。",
+ "scan_error_integration_unconfigured": "このサーバーでは QR インストールが有効になっていません。",
+ "scan_error_installation_conflict": "このボットはすでに他の場所で接続されています。そちらで接続を解除してから、もう一度スキャンしてください。",
+ "scan_error_bind_failed": "ボットは WeCom で作成されましたが、このエージェントに接続できませんでした。WeCom でボットを削除してから、もう一度スキャンしてください。",
+ "scan_error_wecom_protocol_error": "WeCom から予期しない応答が返されました。",
+ "scan_error_internal_error": "問題が発生しました。再試行してください。",
+ "scan_error_session_lost": "このインストールセッションは利用できません。新しいコードを取得してください。",
+ "scan_error_already_connected": "このエージェントにはすでに WeCom ボットが接続されています。先に接続を解除してください。",
+ "scan_error_rate_limited": "試行回数が多すぎます。数分待ってから再試行してください。",
"byo_failed_toast": "WeCom ボットを接続できませんでした"
},
"telegram": {
diff --git a/packages/views/locales/ko/settings.json b/packages/views/locales/ko/settings.json
index 1f652ae2ce..c9b3196cdd 100644
--- a/packages/views/locales/ko/settings.json
+++ b/packages/views/locales/ko/settings.json
@@ -1400,6 +1400,27 @@
"byo_credentials_rejected": "WeCom이 이 Bot ID와 시크릿을 거부했어요. WeCom 관리 콘솔에서 두 값을 확인하고, 장기 연결이 켜진 스마트 봇인지도 확인해 주세요.",
"byo_credentials_unverifiable": "WeCom에 연결하지 못해 이 봇을 확인할 수 없었어요. 인증 정보는 변경되지 않았어요. 잠시 후 다시 시도해 주세요.",
"byo_install_failed": "봇을 저장하지 못했어요. 저희 쪽 문제입니다. 인증 정보는 변경되지 않았어요. 다시 시도해 보시고, 계속 실패하면 지원팀에 문의해 주세요.",
+ "scan_option_title": "새 봇 만들기",
+ "scan_option_description": "WeCom에서 QR 코드를 스캔해 새 스마트 봇을 만들고 연결합니다.",
+ "byo_option_title": "기존 봇 연결",
+ "byo_option_description": "이미 만든 스마트 봇의 Bot ID와 시크릿을 입력하세요.",
+ "scan_dialog_title": "QR 코드로 WeCom 봇 만들기",
+ "scan_starting": "QR 코드를 준비하는 중…",
+ "scan_hint": "휴대폰에서 WeCom을 열고 이 QR 코드를 스캔해 봇을 만드세요.",
+ "scan_expires_in": "{{seconds}}초 후 만료",
+ "scan_success_toast": "WeCom 봇을 만들고 연결했습니다",
+ "scan_again": "새 코드 받기",
+ "scan_close": "닫기",
+ "scan_error_expired": "스캔하기 전에 QR 코드가 만료되었습니다.",
+ "scan_error_generate_failed": "WeCom에서 QR 코드를 가져올 수 없습니다. 잠시 후 다시 시도하세요.",
+ "scan_error_integration_unconfigured": "이 서버에서는 QR 설치가 활성화되지 않았습니다.",
+ "scan_error_installation_conflict": "이 봇은 이미 다른 곳에 연결되어 있습니다. 그곳에서 연결을 해제한 뒤 다시 스캔하세요.",
+ "scan_error_bind_failed": "WeCom에서 봇은 만들어졌지만 이 에이전트에 연결하지 못했습니다. WeCom에서 봇을 삭제한 뒤 다시 스캔하세요.",
+ "scan_error_wecom_protocol_error": "WeCom이 예상치 못한 응답을 반환했습니다.",
+ "scan_error_internal_error": "문제가 발생했습니다. 다시 시도하세요.",
+ "scan_error_session_lost": "이 설치 세션을 사용할 수 없습니다. 새 코드를 받으세요.",
+ "scan_error_already_connected": "이 에이전트에는 이미 WeCom 봇이 연결되어 있습니다. 먼저 연결을 해제하세요.",
+ "scan_error_rate_limited": "시도 횟수가 너무 많습니다. 몇 분 후에 다시 시도하세요.",
"byo_failed_toast": "WeCom 봇을 연결하지 못했어요"
},
"integrations": {
diff --git a/packages/views/locales/zh-Hans/settings.json b/packages/views/locales/zh-Hans/settings.json
index 816a935b56..090b7b8c58 100644
--- a/packages/views/locales/zh-Hans/settings.json
+++ b/packages/views/locales/zh-Hans/settings.json
@@ -1131,6 +1131,27 @@
"byo_credentials_rejected": "企业微信拒绝了这组 Bot ID 和密钥。请在企业微信管理后台核对这两项,并确认它是已开启长连接的智能机器人。",
"byo_credentials_unverifiable": "没能连上企业微信来校验这个机器人。你的凭据没有被改动,请稍后重试。",
"byo_install_failed": "没能保存这个机器人,是我们这边出了问题。你的凭据没有被改动,请重试;如果一直失败,请联系支持。",
+ "scan_option_title": "创建新机器人",
+ "scan_option_description": "在企业微信中扫码创建一个全新的智能机器人并连接。",
+ "byo_option_title": "连接已有机器人",
+ "byo_option_description": "填写你已创建的智能机器人的 Bot ID 和密钥。",
+ "scan_dialog_title": "扫码创建企业微信机器人",
+ "scan_starting": "正在准备二维码…",
+ "scan_hint": "用手机打开企业微信扫描此二维码,即可创建机器人。",
+ "scan_expires_in": "{{seconds}} 秒后失效",
+ "scan_success_toast": "企业微信机器人已创建并连接",
+ "scan_again": "重新获取二维码",
+ "scan_close": "关闭",
+ "scan_error_expired": "二维码已失效,未完成扫描。",
+ "scan_error_generate_failed": "未能从企业微信获取二维码,请稍后重试。",
+ "scan_error_integration_unconfigured": "此服务器未启用扫码安装。",
+ "scan_error_installation_conflict": "这个机器人已在别处连接。请先在那里断开,再重新扫码。",
+ "scan_error_bind_failed": "机器人已在企业微信里创建,但没能连到这个智能体。请在企业微信里删掉它,再重新扫码。",
+ "scan_error_wecom_protocol_error": "企业微信返回了异常响应。",
+ "scan_error_internal_error": "出现问题,请重试。",
+ "scan_error_session_lost": "此安装会话已失效,请重新获取二维码。",
+ "scan_error_already_connected": "这个智能体已经连接了企业微信机器人,请先断开。",
+ "scan_error_rate_limited": "尝试次数过多,请几分钟后再试。",
"byo_failed_toast": "无法连接企业微信机器人"
},
"telegram": {
diff --git a/packages/views/locales/zh-Hant/settings.json b/packages/views/locales/zh-Hant/settings.json
index 9cb40b6087..ae04bef93d 100644
--- a/packages/views/locales/zh-Hant/settings.json
+++ b/packages/views/locales/zh-Hant/settings.json
@@ -1131,6 +1131,27 @@
"byo_credentials_rejected": "企業微信拒絕了這組 Bot ID 和金鑰。請在企業微信管理後臺核對這兩項,並確認它是已開啟長連線的智慧機器人。",
"byo_credentials_unverifiable": "沒能連上企業微信來校驗這個機器人。你的憑據沒有被改動,請稍後重試。",
"byo_install_failed": "沒能儲存這個機器人,是我們這邊出了問題。你的憑據沒有被改動,請重試;如果一直失敗,請聯絡支援。",
+ "scan_option_title": "建立新機器人",
+ "scan_option_description": "在企業微信中掃碼建立一個全新的智慧機器人並連線。",
+ "byo_option_title": "連線現有機器人",
+ "byo_option_description": "填寫你已建立的智慧機器人的 Bot ID 和 Secret。",
+ "scan_dialog_title": "掃碼建立企業微信機器人",
+ "scan_starting": "正在準備 QR 碼…",
+ "scan_hint": "用手機開啟企業微信掃描此 QR 碼,即可建立機器人。",
+ "scan_expires_in": "{{seconds}} 秒後失效",
+ "scan_success_toast": "企業微信機器人已建立並連線",
+ "scan_again": "重新取得 QR 碼",
+ "scan_close": "關閉",
+ "scan_error_expired": "QR 碼已失效,未完成掃描。",
+ "scan_error_generate_failed": "未能從企業微信取得 QR 碼,請稍後再試。",
+ "scan_error_integration_unconfigured": "此伺服器未啟用掃碼安裝。",
+ "scan_error_installation_conflict": "這個機器人已在別處連線。請先在那裡斷開,再重新掃碼。",
+ "scan_error_bind_failed": "機器人已在企業微信裡建立,但沒能連到這個智慧體。請在企業微信裡刪掉它,再重新掃碼。",
+ "scan_error_wecom_protocol_error": "企業微信回傳了異常回應。",
+ "scan_error_internal_error": "發生問題,請再試一次。",
+ "scan_error_session_lost": "此安裝工作階段已失效,請重新取得 QR 碼。",
+ "scan_error_already_connected": "這個智慧體已經連線了企業微信機器人,請先斷開。",
+ "scan_error_rate_limited": "嘗試次數過多,請幾分鐘後再試。",
"byo_failed_toast": "無法連線企業微信機器人"
},
"telegram": {
diff --git a/packages/views/settings/components/wecom-scan-install-dialog.test.tsx b/packages/views/settings/components/wecom-scan-install-dialog.test.tsx
new file mode 100644
index 0000000000..ff912489ee
--- /dev/null
+++ b/packages/views/settings/components/wecom-scan-install-dialog.test.tsx
@@ -0,0 +1,313 @@
+// @vitest-environment jsdom
+
+import { describe, it, expect, beforeEach, afterEach, vi } from "vitest";
+import { cleanup, render, screen, waitFor } from "@testing-library/react";
+import userEvent from "@testing-library/user-event";
+import { I18nProvider } from "@multica/core/i18n/react";
+import enCommon from "../../locales/en/common.json";
+import enSettings from "../../locales/en/settings.json";
+
+// wecom-scan-install-dialog.test.tsx — the QR install dialog.
+//
+// What matters here is the poll loop's shape: the QR only exists after a later
+// poll (begin returns a session in `creating`), a terminal status stops polling,
+// and a 404 mid-poll is terminal rather than an infinite retry on a dead session.
+
+const mockBegin = vi.hoisted(() => vi.fn());
+const mockStatus = vi.hoisted(() => vi.fn());
+const mockInvalidate = vi.hoisted(() => vi.fn());
+const mockToastSuccess = vi.hoisted(() => vi.fn());
+
+// Hoisted with the mocks: vi.mock factories run before top-level declarations,
+// so a plain class here would be referenced before initialization.
+const FakeApiError = vi.hoisted(
+ () =>
+ class FakeApiError extends Error {
+ status: number;
+ body: unknown;
+ constructor(status: number, message: string, body?: unknown) {
+ super(message);
+ this.status = status;
+ this.body = body;
+ }
+ },
+);
+
+vi.mock("@tanstack/react-query", () => ({
+ useQueryClient: () => ({ invalidateQueries: mockInvalidate }),
+}));
+
+vi.mock("@multica/core/wecom", () => ({
+ wecomKeys: { installations: (wsId: string) => ["wecom", "installations", wsId] },
+}));
+
+vi.mock("@multica/core/api", () => ({
+ api: { beginWecomInstall: mockBegin, getWecomInstallStatus: mockStatus },
+ ApiError: FakeApiError,
+ // Same contract as the real helper: the body's `code`, when there is one.
+ errorCode: (e: unknown) =>
+ e instanceof FakeApiError ? (e.body as { code?: string } | undefined)?.code : undefined,
+}));
+
+vi.mock("sonner", () => ({
+ toast: { success: mockToastSuccess, error: vi.fn(), message: vi.fn() },
+}));
+
+// react-qr-code renders an <svg> that jsdom does not need; a stub keeps the
+// assertion on "the QR is showing" rather than on its pixels.
+vi.mock("react-qr-code", () => ({
+ QRCode: ({ value }: { value: string }) => <div data-testid="qr" data-value={value} />,
+}));
+
+import { WecomScanInstallDialog } from "./wecom-scan-install-dialog";
+
+const TEST_RESOURCES = { en: { common: enCommon, settings: enSettings } };
+
+afterEach(cleanup);
+
+function renderDialog(onClose = vi.fn()) {
+ return render(
+ <I18nProvider locale="en" resources={TEST_RESOURCES}>
+ <WecomScanInstallDialog wsId="workspace-1" agentId="agent-1" onClose={onClose} />
+ </I18nProvider>,
+ );
+}
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ // jsdom has no crypto.randomUUID in every environment version.
+ if (!globalThis.crypto?.randomUUID) {
+ Object.defineProperty(globalThis, "crypto", {
+ value: { ...globalThis.crypto, randomUUID: () => "11111111-1111-1111-1111-111111111111" },
+ configurable: true,
+ });
+ }
+});
+
+describe("WecomScanInstallDialog", () => {
+ it("shows the preparing state before the QR exists, then renders it", async () => {
+ mockBegin.mockResolvedValue({
+ session_id: "session-1",
+ status: "creating",
+ poll_interval_seconds: 1,
+ });
+ // The QR arrives on a later poll — begin never carries it.
+ mockStatus
+ .mockResolvedValueOnce({ status: "creating", poll_interval_seconds: 1 })
+ .mockResolvedValue({
+ status: "pending",
+ qr_code_url: "https://work.weixin.qq.com/ai/qc/scan?scode=abc",
+ expires_in_seconds: 240,
+ poll_interval_seconds: 2,
+ });
+
+ renderDialog();
+
+ expect(await screen.findByTestId("wecom-scan-starting")).toBeTruthy();
+ const qr = await screen.findByTestId("qr", {}, { timeout: 5000 });
+ expect(qr.getAttribute("data-value")).toContain("scode=abc");
+ expect(screen.getByTestId("wecom-scan-expiry").textContent).toContain("240");
+ });
+
+ it("invalidates the installations cache and closes on success", async () => {
+ const onClose = vi.fn();
+ mockBegin.mockResolvedValue({
+ session_id: "session-1",
+ status: "creating",
+ poll_interval_seconds: 1,
+ });
+ mockStatus.mockResolvedValue({
+ status: "success",
+ installation_id: "install-1",
+ poll_interval_seconds: 2,
+ });
+
+ renderDialog(onClose);
+
+ await waitFor(() => expect(mockToastSuccess).toHaveBeenCalled(), { timeout: 5000 });
+ expect(mockInvalidate).toHaveBeenCalledWith({
+ queryKey: ["wecom", "installations", "workspace-1"],
+ });
+ await waitFor(() => expect(onClose).toHaveBeenCalled(), { timeout: 5000 });
+ });
+
+ it("renders the reason for a terminal error and stops polling", async () => {
+ mockBegin.mockResolvedValue({
+ session_id: "session-1",
+ status: "creating",
+ poll_interval_seconds: 1,
+ });
+ mockStatus.mockResolvedValue({
+ status: "error",
+ error_reason: "expired",
+ poll_interval_seconds: 2,
+ });
+
+ renderDialog();
+
+ const err = await screen.findByTestId("wecom-scan-error", {}, { timeout: 5000 });
+ expect(err.textContent).toBe(enSettings.wecom.scan_error_expired);
+
+ const callsAfterError = mockStatus.mock.calls.length;
+ await new Promise((r) => setTimeout(r, 300));
+ expect(mockStatus.mock.calls.length).toBe(callsAfterError);
+ });
+
+ // An unknown reason must still render copy rather than a blank panel.
+ it("falls back to generic copy for an unrecognized error reason", async () => {
+ mockBegin.mockResolvedValue({
+ session_id: "session-1",
+ status: "creating",
+ poll_interval_seconds: 1,
+ });
+ mockStatus.mockResolvedValue({
+ status: "error",
+ error_reason: "some_future_reason",
+ poll_interval_seconds: 2,
+ });
+
+ renderDialog();
+
+ const err = await screen.findByTestId("wecom-scan-error", {}, { timeout: 5000 });
+ expect(err.textContent).toContain(enSettings.wecom.scan_error_internal_error);
+ });
+
+ // The two ways a scanned bot fails to bind need different actions from the
+ // admin: one bot is held elsewhere, the other exists in WeCom unconnected.
+ it.each([
+ ["installation_conflict", "scan_error_installation_conflict"],
+ ["bind_failed", "scan_error_bind_failed"],
+ ] as const)("renders its own copy for a %s bind", async (reason, key) => {
+ mockBegin.mockResolvedValue({
+ session_id: "session-1",
+ status: "creating",
+ poll_interval_seconds: 1,
+ });
+ mockStatus.mockResolvedValue({
+ status: "error",
+ error_reason: reason,
+ poll_interval_seconds: 2,
+ });
+
+ renderDialog();
+
+ const err = await screen.findByTestId("wecom-scan-error", {}, { timeout: 5000 });
+ expect(err.textContent).toBe(enSettings.wecom[key]);
+ });
+
+ // A 404 means the session is gone (purged, or never existed). Polling on would
+ // trap the user watching a stale QR with no feedback.
+ it("treats a 404 mid-poll as a lost session", async () => {
+ mockBegin.mockResolvedValue({
+ session_id: "session-1",
+ status: "creating",
+ poll_interval_seconds: 1,
+ });
+ mockStatus.mockRejectedValue(new FakeApiError(404, "install session not found"));
+
+ renderDialog();
+
+ const err = await screen.findByTestId("wecom-scan-error", {}, { timeout: 5000 });
+ expect(err.textContent).toContain(enSettings.wecom.scan_error_session_lost);
+ });
+
+ it("surfaces a 503 begin as the unconfigured reason", async () => {
+ mockBegin.mockRejectedValue(new FakeApiError(503, "wecom scan install not enabled"));
+
+ renderDialog();
+
+ const err = await screen.findByTestId("wecom-scan-error", {}, { timeout: 5000 });
+ expect(err.textContent).toContain(enSettings.wecom.scan_error_integration_unconfigured);
+ // Nothing to poll when begin never produced a session.
+ expect(mockStatus).not.toHaveBeenCalled();
+ });
+
+ it("starts a brand-new session on retry", async () => {
+ mockBegin.mockResolvedValue({
+ session_id: "session-1",
+ status: "creating",
+ poll_interval_seconds: 1,
+ });
+ mockStatus.mockResolvedValue({
+ status: "error",
+ error_reason: "expired",
+ poll_interval_seconds: 2,
+ });
+
+ renderDialog();
+ await screen.findByTestId("wecom-scan-error", {}, { timeout: 5000 });
+
+ const beginCalls = mockBegin.mock.calls.length;
+ await userEvent.click(screen.getByTestId("wecom-scan-retry"));
+ await waitFor(() => expect(mockBegin.mock.calls.length).toBe(beginCalls + 1));
+ // A fresh idempotency key, or "get a new code" would replay the expired
+ // session instead of starting over.
+ const firstKey = mockBegin.mock.calls[0]?.[2];
+ const secondKey = mockBegin.mock.calls[beginCalls]?.[2];
+ expect(firstKey).toBeTruthy();
+ expect(secondKey).toBeTruthy();
+ expect(secondKey).not.toBe(firstKey);
+ });
+
+ // A refused begin is told apart by its code and shown in the admin's own
+ // words; the server's English sentence never reaches the dialog.
+ it.each([
+ [409, "wecom_agent_already_connected", "scan_error_already_connected"],
+ [429, "wecom_scan_install_rate_limited", "scan_error_rate_limited"],
+ [503, "wecom_scan_install_unavailable", "scan_error_integration_unconfigured"],
+ ] as const)("shows a %i %s begin refusal as %s", async (status, code, key) => {
+ const sentence = "the server's own English sentence";
+ mockBegin.mockRejectedValue(new FakeApiError(status, sentence, { error: sentence, code }));
+
+ renderDialog();
+
+ const err = await screen.findByTestId("wecom-scan-error", {}, { timeout: 5000 });
+ expect(err.textContent).toBe(enSettings.wecom[key]);
+ expect(screen.queryByText(sentence, { exact: false })).toBeNull();
+ expect(mockStatus).not.toHaveBeenCalled();
+ });
+
+ it("reports a malformed begin response as an error instead of polling forever", async () => {
+ // parseWithFallback degrades an unparseable body to an empty session id.
+ mockBegin.mockResolvedValue({ session_id: "", status: "error", poll_interval_seconds: 1 });
+
+ renderDialog();
+
+ expect(await screen.findByTestId("wecom-scan-error", {}, { timeout: 5000 })).toBeTruthy();
+ expect(mockStatus).not.toHaveBeenCalled();
+ });
+
+ // crypto.randomUUID is SecureContext-gated: it is simply absent over plain
+ // HTTP. A self-hosted deployment on http:// is the ordinary case, and minting
+ // the idempotency key through it threw inside the begin try-block, so the
+ // dialog showed "something went wrong" and never called the API at all.
+ it("still begins the install where crypto.randomUUID is unavailable", async () => {
+ const realCrypto = globalThis.crypto;
+ // A non-secure context keeps getRandomValues and loses randomUUID.
+ vi.stubGlobal("crypto", {
+ getRandomValues: (b: Uint8Array) => realCrypto.getRandomValues(b),
+ });
+ try {
+ mockBegin.mockResolvedValue({
+ session_id: "S1",
+ status: "creating",
+ poll_interval_seconds: 1,
+ });
+ mockStatus.mockResolvedValue({
+ status: "pending",
+ qr_code_url: "https://work.weixin.qq.com/qr",
+ poll_interval_seconds: 1,
+ });
+
+ renderDialog();
+
+ await waitFor(() => expect(mockBegin).toHaveBeenCalled(), { timeout: 5000 });
+ const key = mockBegin.mock.calls[0]?.[2];
+ expect(typeof key).toBe("string");
+ expect(key).toBeTruthy();
+ expect(screen.queryByTestId("wecom-scan-error")).toBeNull();
+ } finally {
+ vi.stubGlobal("crypto", realCrypto);
+ }
+ });
+});
diff --git a/packages/views/settings/components/wecom-scan-install-dialog.tsx b/packages/views/settings/components/wecom-scan-install-dialog.tsx
new file mode 100644
index 0000000000..8408702869
--- /dev/null
+++ b/packages/views/settings/components/wecom-scan-install-dialog.tsx
@@ -0,0 +1,300 @@
+"use client";
+
+// wecom-scan-install-dialog.tsx — the QR half of connecting a WeCom bot.
+//
+// Structure follows LarkInstallDialog, which solves the same problem: a bounded,
+// one-shot polled session whose whole state collapses when the dialog closes.
+// The shape is deliberately not useQuery — TanStack's refetch heuristics (window
+// focus, online/offline, retry backoff) are wrong for a session with its own
+// server-driven cadence and expiry.
+//
+// One difference from Lark worth knowing: WeCom's begin does NOT return the QR.
+// It returns a session in `creating` and the install worker fetches the QR out of
+// band, so this dialog renders a "preparing" state first and the QR appears on a
+// later poll once the status turns `pending`.
+
+import { useCallback, useEffect, useRef, useState } from "react";
+import { useQueryClient } from "@tanstack/react-query";
+import { toast } from "sonner";
+// Named import: the default export is an object, not a component, and using it
+// throws "Element type is invalid" the moment the QR mounts.
+import { QRCode } from "react-qr-code";
+import { Button } from "@multica/ui/components/ui/button";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from "@multica/ui/components/ui/dialog";
+import { api, ApiError, errorCode } from "@multica/core/api";
+import { createSafeId } from "@multica/core/utils";
+import { wecomKeys } from "@multica/core/wecom";
+import { useT } from "../../i18n";
+
+// Terminal error reasons this dialog renders copy for. Anything else falls back
+// to the generic message, so a new backend reason never renders blank.
+//
+// Every line the admin reads comes from here, in their language. The server's
+// English sentences are never shown: a session's stored detail is for the
+// operator, and a refused begin is told apart by its code.
+const SCAN_ERROR_KEYS = [
+ "expired",
+ "generate_failed",
+ "integration_unconfigured",
+ "installation_conflict",
+ "bind_failed",
+ "wecom_protocol_error",
+ "internal_error",
+ "session_lost",
+ "already_connected",
+ "rate_limited",
+] as const;
+
+type ScanErrorReason = (typeof SCAN_ERROR_KEYS)[number];
+
+// The begin refusals the server gives a code to, and the reason each one is
+// shown as.
+const BEGIN_ERROR_REASONS: Record<string, ScanErrorReason> = {
+ wecom_agent_already_connected: "already_connected",
+ wecom_scan_install_rate_limited: "rate_limited",
+ wecom_scan_install_unavailable: "integration_unconfigured",
+};
+
+function isKnownScanError(reason: string | null): reason is ScanErrorReason {
+ return reason !== null && (SCAN_ERROR_KEYS as readonly string[]).includes(reason);
+}
+
+export function WecomScanInstallDialog({
+ wsId,
+ agentId,
+ agentName,
+ onClose,
+}: {
+ wsId: string;
+ agentId: string;
+ agentName?: string;
+ onClose: () => void;
+}) {
+ const { t } = useT("settings");
+ const qc = useQueryClient();
+
+ const [sessionId, setSessionId] = useState<string | null>(null);
+ const [pollIntervalSeconds, setPollIntervalSeconds] = useState(1);
+ const [qrCodeURL, setQrCodeURL] = useState<string | null>(null);
+ const [expiresInSeconds, setExpiresInSeconds] = useState<number | null>(null);
+ const [status, setStatus] = useState<string>("creating");
+ const [errorReason, setErrorReason] = useState<string | null>(null);
+ const [beginning, setBeginning] = useState(false);
+ const closedRef = useRef(false);
+
+ const beginSession = useCallback(async () => {
+ setBeginning(true);
+ setStatus("creating");
+ setErrorReason(null);
+ setSessionId(null);
+ setQrCodeURL(null);
+ setExpiresInSeconds(null);
+ try {
+ // A fresh key per attempt: reusing one would make "get a new code" replay
+ // the previous session — including an expired one — instead of starting
+ // over. Within a single attempt the key is stable, so a retried or
+ // double-submitted POST still collapses onto one session.
+ //
+ // createSafeId, not crypto.randomUUID: that one is SecureContext-gated and
+ // simply absent over plain HTTP, where it threw in here and turned every
+ // scan install on a self-hosted http:// deployment into "something went
+ // wrong" without a request ever leaving the browser.
+ const idempotencyKey = createSafeId();
+ const res = await api.beginWecomInstall(wsId, agentId, idempotencyKey);
+ if (closedRef.current) return;
+ if (!res.session_id) {
+ setStatus("error");
+ setErrorReason("internal_error");
+ return;
+ }
+ setSessionId(res.session_id);
+ setStatus(res.status);
+ setPollIntervalSeconds(res.poll_interval_seconds);
+ } catch (e) {
+ if (closedRef.current) return;
+ setStatus("error");
+ // A server that predates the codes still says "not enabled" with a 503.
+ const code = errorCode(e);
+ setErrorReason(
+ (code && BEGIN_ERROR_REASONS[code]) ??
+ (e instanceof ApiError && e.status === 503 ? "integration_unconfigured" : "internal_error"),
+ );
+ } finally {
+ if (!closedRef.current) setBeginning(false);
+ }
+ }, [wsId, agentId]);
+
+ // Kick off on mount.
+ //
+ // closedRef is reset AT THE START of every mount, not only at construction:
+ // StrictMode runs effects twice (mount → cleanup → mount) on the same
+ // instance, so the ref survives. Without the reset, mount #1's cleanup sets
+ // closedRef=true and every await in mount #2 early-exits before setting state
+ // — the dialog then renders permanently empty.
+ useEffect(() => {
+ closedRef.current = false;
+ void beginSession();
+ return () => {
+ closedRef.current = true;
+ };
+ }, [beginSession]);
+
+ // Polling loop. Runs while the session is not terminal — through `creating`
+ // too, since that is when the QR is still being fetched.
+ useEffect(() => {
+ if (!sessionId) return;
+ if (status !== "creating" && status !== "pending") return;
+
+ const intervalMs = Math.max(1000, pollIntervalSeconds * 1000);
+ let cancelled = false;
+ let timer: ReturnType<typeof setTimeout> | null = null;
+
+ const poll = async () => {
+ if (cancelled) return;
+ try {
+ const res = await api.getWecomInstallStatus(wsId, sessionId);
+ if (cancelled) return;
+ setStatus(res.status);
+ setPollIntervalSeconds(res.poll_interval_seconds);
+ if (res.qr_code_url) setQrCodeURL(res.qr_code_url);
+ if (typeof res.expires_in_seconds === "number") {
+ setExpiresInSeconds(res.expires_in_seconds);
+ }
+ if (res.status === "success") {
+ await qc.invalidateQueries({ queryKey: wecomKeys.installations(wsId) });
+ toast.success(t(($) => $.wecom.scan_success_toast));
+ // The close itself is deliberately NOT scheduled here: `status` is a
+ // dependency of this effect, so setting it to "success" re-runs the
+ // effect and the cleanup would cancel the very timer meant to close
+ // the dialog. A dedicated effect below owns that.
+ return;
+ }
+ if (res.status === "error") {
+ setErrorReason(res.error_reason ?? "internal_error");
+ return;
+ }
+ timer = setTimeout(poll, intervalMs);
+ } catch (e) {
+ if (cancelled) return;
+ // Terminal HTTP states must not be retried: the session is gone or the
+ // caller lost permission, and polling on would trap the user watching a
+ // stale QR with no feedback.
+ if (e instanceof ApiError) {
+ // 404: purged by the retention sweep, or never existed.
+ if (e.status === 404 || e.status === 401 || e.status === 403) {
+ setStatus("error");
+ setErrorReason("session_lost");
+ return;
+ }
+ }
+ // A blip or 5xx: poll again. The next read either confirms the session
+ // or surfaces the terminal reason the worker recorded.
+ timer = setTimeout(poll, intervalMs);
+ }
+ };
+
+ timer = setTimeout(poll, intervalMs);
+ return () => {
+ cancelled = true;
+ if (timer) clearTimeout(timer);
+ };
+ }, [wsId, sessionId, status, pollIntervalSeconds, qc, t, onClose]);
+
+ // Close shortly after success so the success state is visible for a beat.
+ // Separate from the poll effect for the reason noted above.
+ useEffect(() => {
+ if (status !== "success") return;
+ const timer = setTimeout(onClose, 800);
+ return () => clearTimeout(timer);
+ }, [status, onClose]);
+
+ const scanErrorText = isKnownScanError(errorReason)
+ ? {
+ expired: t(($) => $.wecom.scan_error_expired),
+ generate_failed: t(($) => $.wecom.scan_error_generate_failed),
+ integration_unconfigured: t(($) => $.wecom.scan_error_integration_unconfigured),
+ installation_conflict: t(($) => $.wecom.scan_error_installation_conflict),
+ bind_failed: t(($) => $.wecom.scan_error_bind_failed),
+ wecom_protocol_error: t(($) => $.wecom.scan_error_wecom_protocol_error),
+ internal_error: t(($) => $.wecom.scan_error_internal_error),
+ session_lost: t(($) => $.wecom.scan_error_session_lost),
+ already_connected: t(($) => $.wecom.scan_error_already_connected),
+ rate_limited: t(($) => $.wecom.scan_error_rate_limited),
+ }[errorReason]
+ : t(($) => $.wecom.scan_error_internal_error);
+
+ return (
+ <Dialog
+ open
+ onOpenChange={(o) => {
+ if (!o) onClose();
+ }}
+ >
+ <DialogContent className="max-w-sm" data-testid="wecom-scan-dialog">
+ <DialogHeader>
+ <DialogTitle>{t(($) => $.wecom.scan_dialog_title)}</DialogTitle>
+ <DialogDescription>
+ {agentName
+ ? t(($) => $.wecom.bind_button_title, { agent: agentName })
+ : t(($) => $.wecom.scan_hint)}
+ </DialogDescription>
+ </DialogHeader>
+
+ <div className="flex flex-col items-center gap-4 py-2">
+ {(beginning || status === "creating") && !qrCodeURL && status !== "error" && (
+ <p className="text-body text-muted-foreground" data-testid="wecom-scan-starting">
+ {t(($) => $.wecom.scan_starting)}
+ </p>
+ )}
+
+ {status === "pending" && qrCodeURL && (
+ <>
+ {/* White plate regardless of theme: a QR needs light quiet zones
+ to scan, and the dark-mode surface token would invert it. */}
+ <div className="rounded-md border bg-white p-3">
+ <QRCode value={qrCodeURL} size={192} />
+ </div>
+ <p className="text-caption text-muted-foreground text-center">
+ {t(($) => $.wecom.scan_hint)}
+ </p>
+ {expiresInSeconds !== null && expiresInSeconds > 0 && (
+ <p className="text-caption text-muted-foreground" data-testid="wecom-scan-expiry">
+ {t(($) => $.wecom.scan_expires_in, { seconds: expiresInSeconds })}
+ </p>
+ )}
+ </>
+ )}
+
+ {status === "error" && (
+ <div className="text-center" data-testid="wecom-scan-error">
+ <p className="text-body">{scanErrorText}</p>
+ </div>
+ )}
+ </div>
+
+ <DialogFooter>
+ <Button variant="outline" size="sm" onClick={onClose}>
+ {t(($) => $.wecom.scan_close)}
+ </Button>
+ {status === "error" && (
+ <Button
+ size="sm"
+ onClick={() => void beginSession()}
+ disabled={beginning}
+ data-testid="wecom-scan-retry"
+ >
+ {t(($) => $.wecom.scan_again)}
+ </Button>
+ )}
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ );
+}
diff --git a/packages/views/settings/components/wecom-tab.test.tsx b/packages/views/settings/components/wecom-tab.test.tsx
index f047a223b6..1d036a0cea 100644
--- a/packages/views/settings/components/wecom-tab.test.tsx
+++ b/packages/views/settings/components/wecom-tab.test.tsx
@@ -22,9 +22,14 @@ const membersRef = vi.hoisted(() => ({
}));
const installationsRef = vi.hoisted(() => ({
current: {
- installations: [] as unknown[],
+ installations: [],
configured: true,
install_supported: true,
+ } as {
+ installations: unknown[];
+ configured: boolean;
+ install_supported: boolean;
+ scan_install_supported?: boolean;
},
}));
const mockRegisterBYO = vi.hoisted(() => vi.fn());
@@ -98,6 +103,13 @@ vi.mock("sonner", () => ({
toast: { success: vi.fn(), error: vi.fn(), message: vi.fn() },
}));
+// The scan dialog has its own test; here it only has to be the thing that opens.
+vi.mock("./wecom-scan-install-dialog", () => ({
+ WecomScanInstallDialog: ({ agentId }: { agentId: string }) => (
+ <div data-testid="wecom-scan-dialog-stub" data-agent-id={agentId} />
+ ),
+}));
+
import { toast } from "sonner";
import { WecomAgentBindButton, WecomTab } from "./wecom-tab";
@@ -122,6 +134,29 @@ function resetFixtures() {
describe("WecomAgentBindButton", () => {
beforeEach(resetFixtures);
+ // Scanning needs a QR provider on top of the secret key, so the server says
+ // separately whether it works. Anything but an explicit true — an older
+ // server sends nothing — leaves only the BYO form, rather than a button that
+ // 503s.
+ it.each([undefined, false])("offers no scan option when scan_install_supported is %s", async (flag) => {
+ installationsRef.current.scan_install_supported = flag;
+ renderUI(<WecomAgentBindButton agentId="agent-1" agentName="Bot" />);
+ await userEvent.click(screen.getByTestId("wecom-agent-connect"));
+ await screen.findByTestId("wecom-byo-bot-id");
+ expect(screen.queryByTestId("wecom-scan-option")).toBeNull();
+ });
+
+ it("opens the scan dialog for this agent from the scan option", async () => {
+ installationsRef.current.scan_install_supported = true;
+ renderUI(<WecomAgentBindButton agentId="agent-1" agentName="Bot" />);
+ await userEvent.click(screen.getByTestId("wecom-agent-connect"));
+ await userEvent.click(await screen.findByTestId("wecom-scan-option"));
+ const dialog = await screen.findByTestId("wecom-scan-dialog-stub");
+ expect(dialog.getAttribute("data-agent-id")).toBe("agent-1");
+ // The BYO dialog closes behind it rather than stacking two modals.
+ expect(screen.queryByTestId("wecom-byo-bot-id")).toBeNull();
+ });
+
it("opens the BYO dialog and submits the trimmed bot id + secret", async () => {
mockRegisterBYO.mockResolvedValue({ id: "i1", agent_id: "agent-1", status: "active" });
renderUI(<WecomAgentBindButton agentId="agent-1" agentName="Bot" />);
diff --git a/packages/views/settings/components/wecom-tab.tsx b/packages/views/settings/components/wecom-tab.tsx
index 6b050147e1..381ef97f6b 100644
--- a/packages/views/settings/components/wecom-tab.tsx
+++ b/packages/views/settings/components/wecom-tab.tsx
@@ -35,6 +35,7 @@ import { wecomInstallationsOptions, wecomKeys } from "@multica/core/wecom";
import { errorCode } from "@multica/core/api";
import { api } from "@multica/core/api";
import type { WecomInstallation } from "@multica/core/types";
+import { WecomScanInstallDialog } from "./wecom-scan-install-dialog";
import { ActorAvatar } from "../../common/actor-avatar";
import { useT } from "../../i18n";
import { TooltipHint } from "@multica/ui/components/common/tooltip-hint";
@@ -253,6 +254,7 @@ export function WecomAgentBindButton({
const user = useAuthStore((s) => s.user);
const [dialogOpen, setDialogOpen] = useState(false);
+ const [scanOpen, setScanOpen] = useState(false);
const [botId, setBotId] = useState("");
const [secret, setSecret] = useState("");
const [botName, setBotName] = useState("");
@@ -263,6 +265,9 @@ export function WecomAgentBindButton({
enabled: !!wsId,
});
const installSupported = listing?.install_supported === true;
+ // Scan needs a QR provider on top of the secret key, so it can be off where
+ // BYO works. When it is off the dialog shows only the BYO fields.
+ const scanSupported = listing?.scan_install_supported === true;
const { data: members = [] } = useQuery({
...memberListOptions(wsId),
@@ -393,6 +398,36 @@ export function WecomAgentBindButton({
</DialogHeader>
<div className="space-y-4">
+ {scanSupported && (
+ <div className="space-y-3">
+ <button
+ type="button"
+ className="w-full rounded-md border p-3 text-left transition-colors hover:bg-accent"
+ onClick={() => {
+ setDialogOpen(false);
+ setScanOpen(true);
+ }}
+ disabled={submitting}
+ data-testid="wecom-scan-option"
+ >
+ <span className="text-body font-medium">
+ {t(($) => $.wecom.scan_option_title)}
+ </span>
+ <span className="text-caption text-muted-foreground mt-0.5 block">
+ {t(($) => $.wecom.scan_option_description)}
+ </span>
+ </button>
+ <div className="space-y-0.5">
+ <p className="text-body font-medium">
+ {t(($) => $.wecom.byo_option_title)}
+ </p>
+ <p className="text-caption text-muted-foreground">
+ {t(($) => $.wecom.byo_option_description)}
+ </p>
+ </div>
+ </div>
+ )}
+
<div className="space-y-1.5">
<Label htmlFor="wecom-byo-bot-id">
{t(($) => $.wecom.byo_bot_id_label)}
@@ -468,6 +503,15 @@ export function WecomAgentBindButton({
</DialogFooter>
</DialogContent>
</Dialog>
+
+ {scanOpen && (
+ <WecomScanInstallDialog
+ wsId={wsId}
+ agentId={agentId}
+ agentName={agentName}
+ onClose={() => setScanOpen(false)}
+ />
+ )}
</div>
);
}
diff --git a/server/cmd/migrate/main.go b/server/cmd/migrate/main.go
index b0af47a8c8..4d7a82e5e6 100644
--- a/server/cmd/migrate/main.go
+++ b/server/cmd/migrate/main.go
@@ -140,6 +140,10 @@ var pgBigmOperatorClass = extensionOperatorClass{
// they are still pending: a fresh self-hosted install, which is exactly where an
// interrupted build would otherwise leave a permanently unusable index.
var concurrentIndexCleanups = map[string]string{
+ "604_wecom_install_session_begin_rate_idx": "idx_wecom_install_session_begin_rate",
+ "603_wecom_install_session_agent_pending_idx": "idx_wecom_install_session_agent_pending",
+ "602_wecom_install_session_request_idx": "idx_wecom_install_session_request",
+ "601_wecom_install_session_due_idx": "idx_wecom_install_session_due",
"594_agent_task_process_cleanup_index": "idx_agent_task_queue_process_cleanup",
"563_search_index_change_changed_at_index": "idx_search_index_change_changed_at",
"562_search_index_change_workspace_index": "idx_search_index_change_workspace_xid",
diff --git a/server/cmd/server/main.go b/server/cmd/server/main.go
index 96c33532c7..5bb3253a13 100644
--- a/server/cmd/server/main.go
+++ b/server/cmd/server/main.go
@@ -810,6 +810,14 @@ func main() {
go h.ChannelMediaReconciler.Run(sweepCtx)
}
+ // WeCom scan-code install worker: drives QR generate + poll out of band, so
+ // no HTTP request waits on WeCom. Started even when the scan flow is
+ // unconfigured, so any session already in flight reaches a terminal state
+ // instead of spinning forever in the admin's dialog.
+ if h.WecomInstallWorker != nil {
+ go h.WecomInstallWorker.Run(sweepCtx)
+ }
+
// MUL-2957: DB-backed execution scheduler. The scheduler turns the
// `sys_cron_executions` table into the distributed lease + audit
// log for internal periodic jobs. The first job is
diff --git a/server/cmd/server/router.go b/server/cmd/server/router.go
index 794c93c156..f50159461f 100644
--- a/server/cmd/server/router.go
+++ b/server/cmd/server/router.go
@@ -1171,6 +1171,51 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus
slog.Warn("wecom: frame tracing ON — records message text; unset MULTICA_WECOM_TRACE when done")
}
+ // Scan-code install: the admin scans a QR in WeCom and the bot is
+ // created and bound without anyone handling its secret. The
+ // worker drives the WeCom calls out of band and runs even when
+ // the scan flow is off, so a session already in flight reaches a
+ // terminal state instead of spinning in the admin's dialog.
+ var wecomProvider wecom.Provider
+ wecomSourceID := strings.TrimSpace(os.Getenv("MULTICA_WECOM_SOURCE_ID"))
+ if wecomSourceID == "" {
+ wecomSourceID = wecom.DefaultSourceID
+ }
+ if provider, provErr := wecom.NewHTTPProvider(wecom.HTTPProviderConfig{
+ SourceID: wecomSourceID,
+ Logger: slog.Default(),
+ }); provErr != nil {
+ slog.Error("wecom: QR provider init failed; scan install disabled", "error", provErr)
+ } else {
+ wecomProvider = provider
+ }
+ // Assigned through the interface only when non-nil: a nil
+ // *InstallationService in a BotBinder is a non-nil interface,
+ // which would defeat Configured() and panic at finalize.
+ var wecomBotBinder wecom.BotBinder
+ if svc, instErr := wecom.NewInstallationService(queries, pool, box); instErr != nil {
+ slog.Error("wecom: InstallationService init failed; scan install disabled", "error", instErr)
+ } else {
+ wecomBotBinder = svc
+ }
+ wecomInstall := wecom.NewInstallService(queries, pool, wecomBotBinder, wecom.InstallServiceConfig{
+ Provider: wecomProvider,
+ Box: box,
+ Logger: slog.Default(),
+ })
+ // Same typed-nil hazard: the supervisor is nil when its lease
+ // configuration is invalid, and a nil *Supervisor in the
+ // Notifier interface would panic on the first scanned bot.
+ var wecomInstallNotifier wecom.Notifier
+ if h.ChannelSupervisor != nil {
+ wecomInstallNotifier = h.ChannelSupervisor
+ }
+ h.WecomInstall = wecomInstall
+ h.WecomInstallWorker = wecom.NewInstallWorker(wecomInstall, wecom.InstallWorkerConfig{
+ Bus: bus,
+ Supervisor: wecomInstallNotifier,
+ })
+
slog.Info("wecom integration enabled (smart bot, long connection)")
// REPLICA TOPOLOGY: WeCom outbound (agent replies + inbox
// pushes) is written only by the replica holding each bot's
@@ -1872,6 +1917,11 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus
r.Post("/slack/install/byo", h.RegisterSlackBYO)
r.Delete("/wecom/installations/{installationId}", h.RevokeWecomInstallation)
r.Post("/wecom/install/byo", h.RegisterWecomBYO)
+ // Scan-code install creates and binds a bot, so it sits with
+ // the manual install and the revoke: whoever can connect a
+ // bot this way can also disconnect it.
+ r.Post("/wecom/install/begin", h.BeginWecomInstall)
+ r.Get("/wecom/install/{sessionId}", h.GetWecomInstallStatus)
})
r.Group(func(r chi.Router) {
diff --git a/server/cmd/server/wecom_scan_install_permission_test.go b/server/cmd/server/wecom_scan_install_permission_test.go
new file mode 100644
index 0000000000..e98b00bc5c
--- /dev/null
+++ b/server/cmd/server/wecom_scan_install_permission_test.go
@@ -0,0 +1,100 @@
+package main
+
+import (
+ "context"
+ "net/http"
+ "testing"
+)
+
+// Scan install creates and binds a bot, so it is gated where the manual install
+// and the revoke are: workspace owners and admins. An agent's owner who is a
+// plain member is refused at the route, the same as for connecting a bot by
+// hand, and could not disconnect one it had created anyway.
+//
+// Through NewRouter, because the gate is the route group the handlers are
+// registered in: a handler test would call past it.
+//
+// REVERSE VERIFICATION: register begin and status in the member group again,
+// and the member's requests reach the handlers instead of a 403.
+func TestWecomScanInstallIsForWorkspaceAdmins(t *testing.T) {
+ ctx := context.Background()
+
+ var memberID string
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO "user" (name, email) VALUES ('Scan Agent Owner', '[email protected]')
+ RETURNING id`).Scan(&memberID); err != nil {
+ t.Fatalf("create member: %v", err)
+ }
+ t.Cleanup(func() {
+ _, _ = testPool.Exec(context.Background(), `DELETE FROM "user" WHERE id = $1`, memberID)
+ })
+ if _, err := testPool.Exec(ctx, `INSERT INTO member (workspace_id, user_id, role) VALUES ($1, $2, 'member')`,
+ testWorkspaceID, memberID); err != nil {
+ t.Fatalf("add member: %v", err)
+ }
+ var agentID string
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO agent (workspace_id, name, description, runtime_mode, runtime_config, runtime_id, visibility, max_concurrent_tasks, owner_id)
+ SELECT $1, 'Scan Owner Agent', '', 'cloud', '{}'::jsonb, id, 'workspace', 1, $2
+ FROM agent_runtime WHERE workspace_id = $1 LIMIT 1
+ RETURNING id`, testWorkspaceID, memberID).Scan(&agentID); err != nil {
+ t.Fatalf("create the member's agent: %v", err)
+ }
+ t.Cleanup(func() {
+ _, _ = testPool.Exec(context.Background(), `DELETE FROM agent WHERE id = $1`, agentID)
+ })
+ var sessionID string
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO wecom_install_session (request_key_hash, workspace_id, agent_id, initiator_user_id, status, error_reason)
+ VALUES ('scan-permission', $1, $2, $3, 'error', 'expired')
+ RETURNING id::text`, testWorkspaceID, agentID, testUserID).Scan(&sessionID); err != nil {
+ t.Fatalf("insert session: %v", err)
+ }
+ t.Cleanup(func() {
+ _, _ = testPool.Exec(context.Background(), `DELETE FROM wecom_install_session WHERE id = $1`, sessionID)
+ })
+ memberToken, err := generateTestJWT(memberID, "[email protected]", "Scan Agent Owner")
+ if err != nil {
+ t.Fatalf("member token: %v", err)
+ }
+
+ base := testServer.URL + "/api/workspaces/" + testWorkspaceID + "/wecom/install/"
+ do := func(t *testing.T, token, method, url string) int {
+ t.Helper()
+ req, err := http.NewRequest(method, url, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ req.Header.Set("Authorization", "Bearer "+token)
+ req.Header.Set("X-Workspace-ID", testWorkspaceID)
+ req.Header.Set("Idempotency-Key", "scan-permission-"+method)
+ resp, err := http.DefaultClient.Do(req)
+ if err != nil {
+ t.Fatalf("%s %s: %v", method, url, err)
+ }
+ resp.Body.Close()
+ return resp.StatusCode
+ }
+ begin := base + "begin?agent_id=" + agentID
+ status := base + sessionID
+
+ t.Run("the agent's owner, a plain member, is refused", func(t *testing.T) {
+ if got := do(t, memberToken, http.MethodPost, begin); got != http.StatusForbidden {
+ t.Errorf("begin = %d, want 403", got)
+ }
+ if got := do(t, memberToken, http.MethodGet, status); got != http.StatusForbidden {
+ t.Errorf("status = %d, want 403", got)
+ }
+ })
+
+ // Past the gate the handler answers: 503 when this server has no scan
+ // install configured, otherwise the begin's 202 and the session's 200.
+ t.Run("a workspace admin reaches the handlers", func(t *testing.T) {
+ if got := do(t, testToken, http.MethodPost, begin); got != http.StatusAccepted && got != http.StatusServiceUnavailable {
+ t.Errorf("begin = %d, want 202, or 503 with scan install off", got)
+ }
+ if got := do(t, testToken, http.MethodGet, status); got != http.StatusOK && got != http.StatusServiceUnavailable {
+ t.Errorf("status = %d, want 200, or 503 with scan install off", got)
+ }
+ })
+}
diff --git a/server/cmd/server/wecom_scan_install_wiring_test.go b/server/cmd/server/wecom_scan_install_wiring_test.go
new file mode 100644
index 0000000000..24fe30a082
--- /dev/null
+++ b/server/cmd/server/wecom_scan_install_wiring_test.go
@@ -0,0 +1,92 @@
+package main
+
+import (
+ "bytes"
+ "crypto/rand"
+ "encoding/base64"
+ "log/slog"
+ "strings"
+ "testing"
+
+ "github.com/multica-ai/multica/server/internal/analytics"
+ "github.com/multica-ai/multica/server/internal/events"
+ "github.com/multica-ai/multica/server/internal/handler"
+ "github.com/multica-ai/multica/server/internal/realtime"
+ "github.com/multica-ai/multica/server/internal/util/secretbox"
+)
+
+// The scan-code install has three pieces boot has to assemble, and each one
+// fails quietly when it is missing. Without the service the endpoints 503 and
+// the settings page hides the option; without the worker's event bus a scanned
+// bot does not appear on the open page; without its supervisor the bot connects
+// a sweep late — and a nil *Supervisor passed through the Notifier interface
+// does worse, panicking on the first scanned bot. The unit tests in the wecom
+// package all build these by hand, so they stay green whatever router.go does.
+//
+// So this asserts it off the REAL boot path: NewRouterWithOptions, the call
+// main() makes. Two routers are built, one without the WeCom key and one with,
+// and the difference between them is what the WeCom block did.
+
+func bootWecomScanInstall(t *testing.T, withKey bool) (*handler.Handler, string) {
+ t.Helper()
+ var logged bytes.Buffer
+ restore := slog.Default()
+ slog.SetDefault(slog.New(slog.NewTextHandler(&logged, &slog.HandlerOptions{Level: slog.LevelDebug})))
+ defer slog.SetDefault(restore)
+
+ if withKey {
+ key := make([]byte, secretbox.KeySize)
+ if _, err := rand.Read(key); err != nil {
+ t.Fatalf("generate a wecom secretbox key: %v", err)
+ }
+ t.Setenv("MULTICA_WECOM_SECRET_KEY", base64.StdEncoding.EncodeToString(key))
+ } else {
+ t.Setenv("MULTICA_WECOM_SECRET_KEY", "")
+ }
+ _, h := NewRouterWithOptions(nil, realtime.NewHub(), events.New(), analytics.NoopClient{}, nil, RouterOptions{})
+ return h, logged.String()
+}
+
+func TestWecomScanInstallIsWiredOnTheRealBootPath(t *testing.T) {
+ t.Setenv("CHANNEL_WS_LEASE_BACKEND", "")
+
+ without, _ := bootWecomScanInstall(t, false)
+ if without.WecomInstall != nil || without.WecomInstallWorker != nil {
+ t.Fatal("scan install is wired with no WeCom key set; this test can no longer tell the WeCom block apart from the rest of boot")
+ }
+
+ h, log := bootWecomScanInstall(t, true)
+ if h.ChannelSupervisor == nil {
+ t.Fatalf("the channel supervisor is off on a default boot, so the check below proves nothing; log:\n%s", log)
+ }
+ if h.WecomInstall == nil || h.WecomInstallWorker == nil {
+ t.Fatalf("WeCom is on but scan install is not wired: service=%v worker=%v", h.WecomInstall != nil, h.WecomInstallWorker != nil)
+ }
+ if !h.WecomInstall.Configured() {
+ t.Errorf("scan install is wired but not configured, so begin 503s and the settings page hides it; log:\n%s", log)
+ }
+ for _, warning := range []string{"no event bus wired", "no channel supervisor wired"} {
+ if strings.Contains(log, warning) {
+ t.Errorf("the install worker was built without a collaborator boot has (%q); log:\n%s", warning, log)
+ }
+ }
+}
+
+// When the supervisor is off (here: a Redis lease backend with no Redis), the
+// worker has to receive a real nil, which it reports, rather than a nil
+// *Supervisor inside a non-nil interface, which it would call.
+func TestWecomScanInstallGetsANilSupervisorAsNil(t *testing.T) {
+ t.Setenv("CHANNEL_WS_LEASE_BACKEND", "redis")
+
+ h, log := bootWecomScanInstall(t, true)
+ if h.ChannelSupervisor != nil {
+ t.Fatalf("the supervisor came up with a Redis backend and no Redis, so this test proves nothing; log:\n%s", log)
+ }
+ if h.WecomInstallWorker == nil {
+ t.Fatal("scan install worker not wired")
+ }
+ if !strings.Contains(log, "no channel supervisor wired") {
+ t.Errorf("the install worker did not see the missing supervisor as missing, so the first scanned bot "+
+ "calls Notify on a nil *Supervisor; log:\n%s", log)
+ }
+}
diff --git a/server/internal/handler/handler.go b/server/internal/handler/handler.go
index b230119907..9df440adb5 100644
--- a/server/internal/handler/handler.go
+++ b/server/internal/handler/handler.go
@@ -358,6 +358,14 @@ type Handler struct {
// WecomCredentials unseals a wecom installation's smart-bot secret for the
// WebSocket subscribe frame. Nil disables the wecom integration.
WecomCredentials wecom.CredentialsResolver
+ // WecomInstall drives the scan-code install sessions (QR generate + poll).
+ // Nil unless MULTICA_WECOM_SECRET_KEY is set; Configured() is additionally
+ // false without a QR provider, in which case the endpoints return 503 but
+ // in-flight sessions still terminate cleanly.
+ WecomInstall *wecom.InstallService
+ // WecomInstallWorker drives those sessions. Built in cmd/server/router.go;
+ // main.go starts it as an independent worker.
+ WecomInstallWorker *wecom.InstallWorker
// 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
diff --git a/server/internal/handler/wecom_install_web.go b/server/internal/handler/wecom_install_web.go
new file mode 100644
index 0000000000..a09541fe46
--- /dev/null
+++ b/server/internal/handler/wecom_install_web.go
@@ -0,0 +1,203 @@
+package handler
+
+// wecom_install_web.go — the scan-code install HTTP surface: begin a session and
+// poll its status. The manual bot_id + secret path is RegisterWecomBYO in
+// wecom_web.go.
+//
+// Both handlers are Cache-Control: no-store. The status response carries a QR URL
+// that is a short-lived bearer credential for finishing the bot's creation, and
+// the begin response carries a session id; neither belongs in a shared cache.
+
+import (
+ "errors"
+ "net/http"
+ "strings"
+ "time"
+
+ "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"
+)
+
+// beginWecomInstallResponse tells the client which session to poll and how
+// often.
+type beginWecomInstallResponse struct {
+ SessionID string `json:"session_id"`
+ Status string `json:"status"`
+ PollIntervalSeconds int `json:"poll_interval_seconds"`
+}
+
+// wecomInstallStatusResponse is one status poll. QRCodeURL and
+// ExpiresInSeconds are populated only while the session is pending — there is
+// nothing to render before the QR exists, and nothing to render after it is
+// spent.
+type wecomInstallStatusResponse struct {
+ Status string `json:"status"`
+ PollIntervalSeconds int `json:"poll_interval_seconds"`
+ QRCodeURL string `json:"qr_code_url,omitempty"`
+ ExpiresInSeconds int `json:"expires_in_seconds,omitempty"`
+ InstallationID string `json:"installation_id,omitempty"`
+ // ErrorReason is the machine code the dialog translates. The operator-facing
+ // detail stored beside it stays out of the response: it is English, and it
+ // can carry an internal error string.
+ ErrorReason string `json:"error_reason,omitempty"`
+}
+
+// BeginWecomInstall (POST /api/workspaces/{id}/wecom/install/begin?agent_id=)
+// admits or resumes a scan-code install session.
+//
+// 202, not 200: nothing has been created yet. The worker calls WeCom for the QR
+// out of band, and the client polls GetWecomInstallStatus for it.
+func (h *Handler) BeginWecomInstall(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Cache-Control", "no-store")
+ if h.WecomInstall == nil || !h.WecomInstall.Configured() {
+ writeWecomScanBeginError(w, wecom.ErrInstallNotConfigured)
+ 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
+ }
+ key := strings.TrimSpace(r.Header.Get("Idempotency-Key"))
+ if key == "" {
+ writeError(w, http.StatusBadRequest, "Idempotency-Key header is required")
+ return
+ }
+
+ // The route admits workspace owners and admins only; the agent still has
+ // to be one of this workspace's.
+ 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
+ }
+
+ res, err := h.WecomInstall.BeginInstall(r.Context(), wecom.BeginInstallParams{
+ WorkspaceID: wsUUID,
+ AgentID: agentUUID,
+ InitiatorID: initiatorUUID,
+ IdempotencyKey: key,
+ })
+ if err != nil {
+ writeWecomScanBeginError(w, err)
+ return
+ }
+ writeJSON(w, http.StatusAccepted, beginWecomInstallResponse{
+ SessionID: res.SessionID,
+ Status: res.Status,
+ PollIntervalSeconds: pollIntervalForWecomStatus(res.Status),
+ })
+}
+
+// writeWecomScanBeginError turns a begin failure into its status and, for the
+// outcomes the scan dialog explains to the admin, a stable code it translates.
+// The sentence is the fallback for a client that does not know the code.
+// The rest are a caller bug or a fault on our side, and the dialog shows its
+// generic line for those.
+func writeWecomScanBeginError(w http.ResponseWriter, err error) {
+ switch {
+ case errors.Is(err, wecom.ErrActiveInstallationExists):
+ writeErrorCode(w, http.StatusConflict, "wecom_agent_already_connected",
+ "this agent already has a connected WeCom bot — disconnect it first")
+ case errors.Is(err, wecom.ErrRateLimited):
+ writeErrorCode(w, http.StatusTooManyRequests, "wecom_scan_install_rate_limited",
+ "too many install attempts — wait a few minutes and try again")
+ case errors.Is(err, wecom.ErrInstallNotConfigured):
+ writeErrorCode(w, http.StatusServiceUnavailable, "wecom_scan_install_unavailable",
+ "wecom scan install not enabled")
+ case errors.Is(err, wecom.ErrAgentMismatch):
+ writeError(w, http.StatusConflict, "this Idempotency-Key was already used to start an install for a different agent")
+ case errors.Is(err, wecom.ErrIdempotencyKeyRequired):
+ writeError(w, http.StatusBadRequest, "Idempotency-Key header is required")
+ case errors.Is(err, wecom.ErrIdempotencyKeyTooLong):
+ writeError(w, http.StatusBadRequest, "Idempotency-Key is too long")
+ default:
+ writeError(w, http.StatusInternalServerError, "could not start the WeCom install")
+ }
+}
+
+// GetWecomInstallStatus (GET /api/workspaces/{id}/wecom/install/{sessionId})
+// is the status poll behind the QR dialog.
+func (h *Handler) GetWecomInstallStatus(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Cache-Control", "no-store")
+ if h.WecomInstall == nil {
+ writeError(w, http.StatusServiceUnavailable, "wecom scan install not enabled")
+ return
+ }
+ if _, ok := requireUserID(w, r); !ok {
+ return
+ }
+ wsUUID, ok := parseUUIDOrBadRequest(w, chi.URLParam(r, "id"), "workspace id")
+ if !ok {
+ return
+ }
+ sessionUUID, ok := parseUUIDOrBadRequest(w, strings.TrimSpace(chi.URLParam(r, "sessionId")), "session id")
+ if !ok {
+ return
+ }
+
+ // The route admits workspace owners and admins only, and GetSession reads
+ // within this workspace, so a session from another one is not found.
+ snap, err := h.WecomInstall.GetSession(r.Context(), wsUUID, sessionUUID, true)
+ if err != nil {
+ h.writeWecomSessionError(w, err)
+ return
+ }
+
+ resp := wecomInstallStatusResponse{
+ Status: snap.Status,
+ PollIntervalSeconds: pollIntervalForWecomStatus(snap.Status),
+ ErrorReason: snap.ErrorReason,
+ }
+ if snap.Status == wecom.InstallStatusPending {
+ resp.QRCodeURL = snap.QRCodeURL
+ if !snap.ExpiresAt.IsZero() {
+ if remaining := int(time.Until(snap.ExpiresAt) / time.Second); remaining > 0 {
+ resp.ExpiresInSeconds = remaining
+ }
+ }
+ }
+ if snap.InstallationID.Valid {
+ resp.InstallationID = uuidToString(snap.InstallationID)
+ }
+ writeJSON(w, http.StatusOK, resp)
+}
+
+func (h *Handler) writeWecomSessionError(w http.ResponseWriter, err error) {
+ if errors.Is(err, wecom.ErrSessionNotFound) {
+ writeError(w, http.StatusNotFound, "install session not found")
+ return
+ }
+ writeError(w, http.StatusInternalServerError, "could not load the install session")
+}
+
+// pollIntervalForWecomStatus is the client's next poll delay. creating polls
+// fast because it is only waiting on our own generate call; pending polls at
+// WeCom's own minimum query_result interval. Terminal states still return a
+// value, but the client stops on receipt.
+func pollIntervalForWecomStatus(status string) int {
+ if status == wecom.InstallStatusCreating {
+ return 1
+ }
+ return 2
+}
diff --git a/server/internal/handler/wecom_install_web_test.go b/server/internal/handler/wecom_install_web_test.go
new file mode 100644
index 0000000000..7d4d41e1ba
--- /dev/null
+++ b/server/internal/handler/wecom_install_web_test.go
@@ -0,0 +1,164 @@
+package handler
+
+// wecom_install_web_test.go — what the scan dialog can read off the two
+// scan-install endpoints.
+//
+// The dialog is read by a workspace admin in their own language, so everything
+// it shows has to arrive as a code it can translate. The begin refusals carry a
+// `code`; the status poll carries `error_reason` and nothing else, because the
+// detail stored beside the reason is an English, operator-facing string.
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "net/http"
+ "net/http/httptest"
+ "testing"
+
+ "github.com/multica-ai/multica/server/internal/integrations/channel/engine"
+ "github.com/multica-ai/multica/server/internal/integrations/wecom"
+ "github.com/multica-ai/multica/server/internal/util/secretbox"
+)
+
+// TestWecomScanBeginErrorMatrix pins status + code for every refusal the scan
+// dialog explains to the admin, and pins that the rest carry no code — the
+// dialog shows its generic line for those, and a code there would be one it
+// has no translation for.
+func TestWecomScanBeginErrorMatrix(t *testing.T) {
+ cases := []struct {
+ name string
+ err error
+ wantStatus int
+ wantCode string
+ }{
+ {"agent already has a bot", wecom.ErrActiveInstallationExists, http.StatusConflict, "wecom_agent_already_connected"},
+ {"rate limited", wecom.ErrRateLimited, http.StatusTooManyRequests, "wecom_scan_install_rate_limited"},
+ {"scan install off", wecom.ErrInstallNotConfigured, http.StatusServiceUnavailable, "wecom_scan_install_unavailable"},
+ {"wrapped sentinel", fmt.Errorf("begin: %w", wecom.ErrRateLimited), http.StatusTooManyRequests, "wecom_scan_install_rate_limited"},
+ {"key reused for another agent", wecom.ErrAgentMismatch, http.StatusConflict, ""},
+ {"missing key", wecom.ErrIdempotencyKeyRequired, http.StatusBadRequest, ""},
+ {"key too long", wecom.ErrIdempotencyKeyTooLong, http.StatusBadRequest, ""},
+ {"database down", errors.New("dial tcp: connection refused"), http.StatusInternalServerError, ""},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ w := httptest.NewRecorder()
+ writeWecomScanBeginError(w, tc.err)
+ if w.Code != tc.wantStatus {
+ t.Errorf("status = %d, want %d", w.Code, tc.wantStatus)
+ }
+ var body struct {
+ Error string `json:"error"`
+ Code string `json:"code"`
+ }
+ if err := json.Unmarshal(w.Body.Bytes(), &body); err != nil {
+ t.Fatalf("decode: %v (body %q)", err, w.Body.String())
+ }
+ if body.Code != tc.wantCode {
+ t.Errorf("code = %q, want %q", body.Code, tc.wantCode)
+ }
+ if body.Error == "" {
+ t.Error("no fallback sentence for a client that does not know the code")
+ }
+ })
+ }
+}
+
+// The status poll returns the failure as a reason code and never as the stored
+// detail, which is English and can hold an internal error string.
+func TestWecomInstallStatusOmitsTheOperatorDetail(t *testing.T) {
+ ctx := context.Background()
+ var sessionID string
+ if err := testPool.QueryRow(ctx, `
+INSERT INTO wecom_install_session (request_key_hash, workspace_id, agent_id, initiator_user_id, status, error_reason, error_message)
+VALUES ('status-detail', $1, gen_random_uuid(), $2, 'error', 'bind_failed', 'Could not finalize the WeCom install: wecom: lock bot routing slot: dial tcp 10.0.0.5:5432')
+RETURNING id::text`, testWorkspaceID, testUserID).Scan(&sessionID); err != nil {
+ t.Fatalf("insert session: %v", err)
+ }
+ t.Cleanup(func() {
+ _, _ = testPool.Exec(context.Background(), `DELETE FROM wecom_install_session WHERE id = $1`, sessionID)
+ })
+
+ h := *testHandler
+ h.WecomInstall = wecom.NewInstallService(testHandler.Queries, testPool, nil, wecom.InstallServiceConfig{})
+
+ req := withURLParams(newRequest(http.MethodGet, "/api/workspaces/"+testWorkspaceID+"/wecom/install/"+sessionID, nil),
+ "id", testWorkspaceID, "sessionId", sessionID)
+ w := httptest.NewRecorder()
+ h.GetWecomInstallStatus(w, req)
+ if w.Code != http.StatusOK {
+ t.Fatalf("status = %d, body %s", w.Code, w.Body.String())
+ }
+ var body map[string]any
+ if err := json.Unmarshal(w.Body.Bytes(), &body); err != nil {
+ t.Fatalf("decode: %v", err)
+ }
+ if body["error_reason"] != "bind_failed" {
+ t.Errorf("error_reason = %v, want bind_failed", body["error_reason"])
+ }
+ if _, ok := body["error_message"]; ok {
+ t.Errorf("the poll returned the operator detail to the browser: %s", w.Body.String())
+ }
+}
+
+// The settings tab offers "create a new bot" only when the listing says scan
+// install works. BYO needs just the secret key; scanning also needs the install
+// service fully configured, so the two flags can differ.
+func TestListWecomInstallationsReportsScanSupportSeparately(t *testing.T) {
+ box, err := secretbox.New(make([]byte, secretbox.KeySize))
+ if err != nil {
+ t.Fatalf("secretbox.New: %v", err)
+ }
+ creds, err := wecom.NewSecretboxCredentialsResolver(box)
+ if err != nil {
+ t.Fatalf("credentials resolver: %v", err)
+ }
+ h := *testHandler
+ h.WecomStore = wecom.NewStore(testHandler.Queries)
+ h.WecomCredentials = creds
+ h.ChannelRouter = &engine.Router{}
+
+ list := func() map[string]any {
+ t.Helper()
+ req := withURLParams(newRequest(http.MethodGet, "/api/workspaces/"+testWorkspaceID+"/wecom/installations", nil),
+ "id", testWorkspaceID)
+ w := httptest.NewRecorder()
+ h.ListWecomInstallations(w, req)
+ if w.Code != http.StatusOK {
+ t.Fatalf("status = %d, body %s", w.Code, w.Body.String())
+ }
+ var body map[string]any
+ if err := json.Unmarshal(w.Body.Bytes(), &body); err != nil {
+ t.Fatalf("decode: %v", err)
+ }
+ return body
+ }
+
+ if body := list(); body["install_supported"] != true || body["scan_install_supported"] != false {
+ t.Fatalf("no scan service: install_supported=%v scan_install_supported=%v, want true/false",
+ body["install_supported"], body["scan_install_supported"])
+ }
+
+ binder, err := wecom.NewInstallationService(testHandler.Queries, testPool, box)
+ if err != nil {
+ t.Fatalf("installation service: %v", err)
+ }
+
+ // A service that cannot reach WeCom's QR endpoints is no scan support: the
+ // option would only lead to a 503.
+ h.WecomInstall = wecom.NewInstallService(testHandler.Queries, testPool, binder, wecom.InstallServiceConfig{Box: box})
+ if body := list(); body["scan_install_supported"] != false {
+ t.Fatalf("scan service without a provider: scan_install_supported=%v, want false", body["scan_install_supported"])
+ }
+
+ provider, err := wecom.NewHTTPProvider(wecom.HTTPProviderConfig{SourceID: wecom.DefaultSourceID})
+ if err != nil {
+ t.Fatalf("provider: %v", err)
+ }
+ h.WecomInstall = wecom.NewInstallService(testHandler.Queries, testPool, binder, wecom.InstallServiceConfig{Provider: provider, Box: box})
+ if body := list(); body["scan_install_supported"] != true {
+ t.Fatalf("configured scan service: scan_install_supported=%v, want true", body["scan_install_supported"])
+ }
+}
diff --git a/server/internal/handler/wecom_web.go b/server/internal/handler/wecom_web.go
index 3d9bdf4894..d21b0c5643 100644
--- a/server/internal/handler/wecom_web.go
+++ b/server/internal/handler/wecom_web.go
@@ -74,9 +74,10 @@ func (h *Handler) wecomIntegrationConfigured() bool {
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,
+ "installations": []WecomInstallationResponse{},
+ "configured": false,
+ "install_supported": false,
+ "scan_install_supported": false,
})
return
}
@@ -102,6 +103,10 @@ func (h *Handler) ListWecomInstallations(w http.ResponseWriter, r *http.Request)
"installations": out,
"configured": true,
"install_supported": true,
+ // Scan install additionally needs a QR provider (a source id), so it can
+ // be off on a deployment where the BYO path works. The UI hides the
+ // "create a new bot" option rather than offering a button that 503s.
+ "scan_install_supported": h.WecomInstall != nil && h.WecomInstall.Configured(),
})
}
diff --git a/server/internal/handler/workspace_delete_manifest_test.go b/server/internal/handler/workspace_delete_manifest_test.go
index 3d34fd9782..582bdfed33 100644
--- a/server/internal/handler/workspace_delete_manifest_test.go
+++ b/server/internal/handler/workspace_delete_manifest_test.go
@@ -145,6 +145,7 @@ var workspaceDeletionManifest = map[string]workspaceDeleteAction{
"vcs_pull_request": workspaceDelete,
"verification_code": workspaceDeleteKeep,
"webhook_delivery": workspaceDelete,
+ "wecom_install_session": workspaceDelete,
"workspace": workspaceDelete,
"workspace_invitation": workspaceDelete,
"workspace_share_link": workspaceDelete,
diff --git a/server/internal/integrations/channel/engine/supervisor.go b/server/internal/integrations/channel/engine/supervisor.go
index 76c1c17ea2..80dd7b66f4 100644
--- a/server/internal/integrations/channel/engine/supervisor.go
+++ b/server/internal/integrations/channel/engine/supervisor.go
@@ -319,6 +319,12 @@ type Supervisor struct {
wg sync.WaitGroup
stopped bool
stopChan chan struct{}
+
+ // notify coalesces wake requests from Notify into Run's select loop.
+ // Buffered at 1 so a Notify racing an in-progress sweep is not lost: the
+ // pending value guarantees at least one more sweep runs after the current
+ // one finishes, instead of blocking the caller.
+ notify chan struct{}
}
// supervisorEntry is the per-installation state the Supervisor holds on
@@ -366,6 +372,7 @@ func NewSupervisor(store InstallationStore, leaseStore LeaseStore, registry *cha
contendedSince: make(map[string]time.Time),
renewalErrors: make(map[string]struct{}),
stopChan: make(chan struct{}),
+ notify: make(chan struct{}, 1),
}
}
@@ -394,10 +401,26 @@ func (s *Supervisor) Run(ctx context.Context) {
return
case <-t.C:
s.sweep(ctx)
+ case <-s.notify:
+ s.sweep(ctx)
}
}
}
+// Notify wakes the Run loop for an immediate sweep, ahead of the next
+// PollInterval tick (30s by default). It never blocks and is safe to call
+// concurrently: a wake already queued coalesces with this one, since one sweep
+// picks up whatever prompted every Notify since the last sweep ran.
+//
+// The scan-code install uses it so a bot that was just created connects now rather
+// than up to a poll interval after the admin was told it succeeded.
+func (s *Supervisor) Notify() {
+ select {
+ case s.notify <- struct{}{}:
+ default:
+ }
+}
+
// Wait blocks until every supervisor goroutine the Supervisor started has
// exited. Call this AFTER cancelling Run's context.
//
diff --git a/server/internal/integrations/channel/engine/supervisor_test.go b/server/internal/integrations/channel/engine/supervisor_test.go
index 568e12ca29..6692422f4e 100644
--- a/server/internal/integrations/channel/engine/supervisor_test.go
+++ b/server/internal/integrations/channel/engine/supervisor_test.go
@@ -1073,3 +1073,39 @@ func TestSupervisorExitLogOmitsLeaseTokenField(t *testing.T) {
}
}
}
+
+// Notify is how a freshly installed bot gets its connection now instead of on
+// the next scheduled sweep. The poll interval here is an hour, so only the wake
+// can explain a connect.
+func TestSupervisorNotifySweepsBeforeTheNextTick(t *testing.T) {
+ q := newFakeStore()
+ fc := &fakeChannel{typ: channel.TypeFeishu}
+ var builds int32
+ reg := fakeRegistry(fc, &builds, nil)
+
+ cfg := fastConfig()
+ cfg.PollInterval = time.Hour
+ cfg.LeaseRenewInterval = 2 * time.Hour
+ cfg.LeaseTTL = 3 * time.Hour
+ sup := NewSupervisor(q, q, reg, nil, cfg)
+ ctx, cancel := context.WithCancel(context.Background())
+ defer func() {
+ cancel()
+ sup.Wait()
+ }()
+ go sup.Run(ctx)
+
+ // Let the start-up sweep run against an empty store, then install a bot.
+ time.Sleep(50 * time.Millisecond)
+ q.mu.Lock()
+ q.installations = []Installation{activeInst(uuidFromString(t, "22222222-2222-2222-2222-222222222222"), "fp1")}
+ q.mu.Unlock()
+ if fc.Connects() != 0 {
+ t.Fatalf("connected before any sweep could see the installation")
+ }
+
+ sup.Notify()
+ if !waitFor(time.Second, func() bool { return fc.Connects() >= 1 }) {
+ t.Fatal("the new installation did not connect after Notify; it waits for the hourly tick")
+ }
+}
diff --git a/server/internal/integrations/wecom/install.go b/server/internal/integrations/wecom/install.go
new file mode 100644
index 0000000000..84fe2300ee
--- /dev/null
+++ b/server/internal/integrations/wecom/install.go
@@ -0,0 +1,476 @@
+package wecom
+
+// install.go — the scan-code install session lifecycle.
+//
+// Creating a WeCom smart bot by QR is a multi-minute conversation: ask WeCom for
+// a QR, show it to an admin, then poll until they scan it and WeCom hands back
+// the bot's credentials. None of that fits in the request that started it, so a
+// session row carries the state and install_worker.go drives it.
+//
+// This file owns the HTTP-facing half — admitting a begin, and reading a session
+// back for the status poll. It deliberately does NOT call WeCom: the worker owns
+// every upstream call, so a slow or wedged WeCom cannot hold an HTTP request
+// open.
+//
+// The manual bot_id + secret path is not here; that is installation.go's
+// Upsert, which the worker also reuses to bind a scanned bot.
+
+import (
+ "context"
+ "crypto/rand"
+ "crypto/sha256"
+ "encoding/base64"
+ "encoding/hex"
+ "errors"
+ "fmt"
+ "log/slog"
+ "strings"
+ "time"
+
+ "github.com/jackc/pgx/v5"
+ "github.com/jackc/pgx/v5/pgtype"
+
+ "github.com/multica-ai/multica/server/internal/integrations/channel/engine"
+ "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"
+)
+
+// Session status wire values. String constants because the DB CHECK constraint
+// uses the same literals and the frontend switches on them directly.
+const (
+ InstallStatusCreating = "creating"
+ InstallStatusPending = "pending"
+ InstallStatusSuccess = "success"
+ InstallStatusError = "error"
+)
+
+// Install error reasons are the stable machine codes the frontend switches on.
+// The error_message stored alongside is operator-facing detail.
+const (
+ InstallErrorExpired = "expired"
+ InstallErrorGenerateFailed = "generate_failed"
+ InstallErrorIntegrationUnconfigured = "integration_unconfigured"
+ InstallErrorInstallationConflict = "installation_conflict"
+ InstallErrorBindFailed = "bind_failed"
+ InstallErrorWecomProtocolError = "wecom_protocol_error"
+ InstallErrorInternalError = "internal_error"
+)
+
+// Install flow tunables. Each is a field on InstallServiceConfig so tests can
+// shrink a window without redefining the service.
+const (
+ defaultQRTTL = 5 * time.Minute
+ defaultGenerateDeadline = 30 * time.Second
+ defaultPendingPollInterval = 2 * time.Second
+ defaultCreatingPollInterval = 1 * time.Second
+ defaultLeaseTTL = 30 * time.Second
+ defaultUpstreamTimeout = 10 * time.Second
+ defaultTerminalRetention = 30 * time.Minute
+ defaultRateWindow = 10 * time.Minute
+ defaultRatePerUser = 5
+ defaultRatePerWorkspace = 30
+)
+
+// DefaultSourceID is the WeCom-issued caller identifier. Operators may override
+// it with MULTICA_WECOM_SOURCE_ID without re-provisioning the source.
+const DefaultSourceID = "multica"
+
+var (
+ // ErrAgentMismatch: the idempotency key hit an existing session whose agent
+ // differs. A replayed HTTP request must not silently retarget which agent
+ // gets the bot. HTTP 409.
+ ErrAgentMismatch = errors.New("wecom: idempotency key belongs to a different agent")
+ // ErrActiveInstallationExists: a live WeCom installation is already bound to
+ // this agent; disconnect it first. HTTP 409.
+ ErrActiveInstallationExists = errors.New("wecom: agent already has an active wecom installation")
+ // ErrRateLimited: the begin window count was exceeded, per user or per
+ // workspace. HTTP 429.
+ ErrRateLimited = errors.New("wecom: install begin rate limit exceeded")
+ // ErrIdempotencyKeyRequired: begin was called without the header. HTTP 400.
+ ErrIdempotencyKeyRequired = errors.New("wecom: Idempotency-Key header is required")
+ // ErrIdempotencyKeyTooLong: the header exceeded maxIdempotencyKeyLen. HTTP 400.
+ ErrIdempotencyKeyTooLong = errors.New("wecom: Idempotency-Key is too long")
+ // ErrSessionNotFound: unknown, purged, or cross-workspace session. HTTP 404.
+ ErrSessionNotFound = errors.New("wecom: install session not found")
+ // ErrInstallNotConfigured: no secret key or no provider, so the scan flow
+ // cannot run at all. HTTP 503.
+ ErrInstallNotConfigured = errors.New("wecom: scan install not configured")
+)
+
+// maxIdempotencyKeyLen bounds the client-chosen header so a paste accident
+// cannot push an unbounded string at the hash.
+const maxIdempotencyKeyLen = 128
+
+// BotBinder is the bind half of the finalize step: exactly the slice of
+// InstallationService the worker needs. An interface so the worker's success
+// path is testable without a live Postgres, and so boot can declare an
+// interface-typed variable rather than storing a possibly-nil
+// *InstallationService (a typed nil in an interface is not nil, which would
+// defeat Configured() and panic at finalize). *InstallationService is the
+// production value.
+type BotBinder interface {
+ Upsert(ctx context.Context, p InstallationParams) (Installation, error)
+}
+
+// InstallStore is the narrow slice of generated queries the install flow needs.
+// WithTx returns the same interface bound to a transaction; tests inject a fake
+// so the service runs without a live Postgres.
+type InstallStore interface {
+ WithTx(tx pgx.Tx) InstallStore
+ LockWecomInstallBeginWorkspace(ctx context.Context, workspaceID pgtype.UUID) error
+ GetWecomInstallSessionByRequestHash(ctx context.Context, arg db.GetWecomInstallSessionByRequestHashParams) (db.WecomInstallSession, error)
+ GetPendingWecomInstallSessionByAgent(ctx context.Context, arg db.GetPendingWecomInstallSessionByAgentParams) (db.WecomInstallSession, error)
+ CountWecomInstallSessionsInWindow(ctx context.Context, arg db.CountWecomInstallSessionsInWindowParams) (db.CountWecomInstallSessionsInWindowRow, error)
+ GetActiveWecomInstallationForAgent(ctx context.Context, arg db.GetActiveWecomInstallationForAgentParams) (db.ChannelInstallation, error)
+ CreateWecomInstallSession(ctx context.Context, arg db.CreateWecomInstallSessionParams) (db.WecomInstallSession, error)
+ GetWecomInstallSession(ctx context.Context, id pgtype.UUID) (db.WecomInstallSession, error)
+ ClaimDueWecomInstallSession(ctx context.Context, arg db.ClaimDueWecomInstallSessionParams) (db.WecomInstallSession, error)
+ DeferClaimedWecomInstallSession(ctx context.Context, arg db.DeferClaimedWecomInstallSessionParams) (int64, error)
+ CompleteWecomInstallSession(ctx context.Context, arg db.CompleteWecomInstallSessionParams) (int64, error)
+ FailWecomInstallSession(ctx context.Context, arg db.FailWecomInstallSessionParams) (int64, error)
+ PurgeTerminalWecomInstallSessions(ctx context.Context, arg db.PurgeTerminalWecomInstallSessionsParams) (int64, error)
+}
+
+type dbInstallStore struct{ *db.Queries }
+
+// NewInstallStore returns the production adapter.
+func NewInstallStore(q *db.Queries) InstallStore { return dbInstallStore{q} }
+
+// WithTx binds a transaction and returns the interface-typed store.
+func (s dbInstallStore) WithTx(tx pgx.Tx) InstallStore {
+ return dbInstallStore{s.Queries.WithTx(tx)}
+}
+
+// InstallServiceConfig captures the tunables. The zero value is filled in by
+// withDefaults, so a caller only sets what it wants to change.
+type InstallServiceConfig struct {
+ // Provider talks to WeCom's QR endpoints. Nil disables the scan flow; the
+ // worker still runs so in-flight sessions reach a terminal state instead of
+ // hanging as a forever-spinning dialog.
+ Provider Provider
+
+ // Box seals scode and qr_code_url at rest. Nil disables the scan flow for
+ // the same reason a nil box disables InstallationService: those values are a
+ // bearer credential for "finish creating this bot".
+ Box *secretbox.Box
+
+ QRTTL time.Duration
+ GenerateDeadline time.Duration
+ PendingPollInterval time.Duration
+ CreatingPollInterval time.Duration
+ LeaseTTL time.Duration
+ UpstreamTimeout time.Duration
+ TerminalRetention time.Duration
+ RateWindow time.Duration
+ RatePerUser int
+ RatePerWorkspace int
+
+ Logger *slog.Logger
+ Now func() time.Time
+}
+
+func (c InstallServiceConfig) withDefaults() InstallServiceConfig {
+ if c.QRTTL <= 0 {
+ c.QRTTL = defaultQRTTL
+ }
+ if c.GenerateDeadline <= 0 {
+ c.GenerateDeadline = defaultGenerateDeadline
+ }
+ if c.PendingPollInterval <= 0 {
+ c.PendingPollInterval = defaultPendingPollInterval
+ }
+ if c.CreatingPollInterval <= 0 {
+ c.CreatingPollInterval = defaultCreatingPollInterval
+ }
+ if c.LeaseTTL <= 0 {
+ c.LeaseTTL = defaultLeaseTTL
+ }
+ if c.UpstreamTimeout <= 0 {
+ c.UpstreamTimeout = defaultUpstreamTimeout
+ }
+ if c.TerminalRetention <= 0 {
+ c.TerminalRetention = defaultTerminalRetention
+ }
+ if c.RateWindow <= 0 {
+ c.RateWindow = defaultRateWindow
+ }
+ if c.RatePerUser <= 0 {
+ c.RatePerUser = defaultRatePerUser
+ }
+ if c.RatePerWorkspace <= 0 {
+ c.RatePerWorkspace = defaultRatePerWorkspace
+ }
+ if c.Logger == nil {
+ c.Logger = slog.Default()
+ }
+ if c.Now == nil {
+ c.Now = time.Now
+ }
+ return c
+}
+
+// InstallService owns the HTTP-facing install lifecycle: admitting a begin
+// (idempotency, guards, rate limit) and reading a session back.
+type InstallService struct {
+ store InstallStore
+ tx engine.TxStarter
+ installations BotBinder
+ cfg InstallServiceConfig
+ // notify wakes the worker so generate runs immediately rather than on the
+ // next poll tick. NewInstallWorker sets it; until then it does nothing.
+ notify func()
+}
+
+// NewInstallService binds the production store to the pool. installations is
+// what the worker uses to bind a scanned bot.
+func NewInstallService(q *db.Queries, tx engine.TxStarter, installations BotBinder, cfg InstallServiceConfig) *InstallService {
+ return newInstallService(NewInstallStore(q), tx, installations, cfg)
+}
+
+func newInstallService(store InstallStore, tx engine.TxStarter, installations BotBinder, cfg InstallServiceConfig) *InstallService {
+ return &InstallService{
+ store: store,
+ tx: tx,
+ installations: installations,
+ cfg: cfg.withDefaults(),
+ notify: func() {},
+ }
+}
+
+// Configured reports whether the service can drive a scan install end to end.
+// A false result still lets the worker run: in-flight sessions need to reach a
+// terminal state rather than spin forever.
+func (s *InstallService) Configured() bool {
+ return s != nil && s.cfg.Provider != nil && s.cfg.Box != nil && s.installations != nil
+}
+
+// BeginInstallParams is the trusted input the handler has already authorized.
+type BeginInstallParams struct {
+ WorkspaceID pgtype.UUID
+ AgentID pgtype.UUID
+ InitiatorID pgtype.UUID
+ IdempotencyKey string
+}
+
+// BeginInstallResult is what POST /wecom/install/begin returns. The QR itself
+// arrives on the status poll, once the worker has fetched it.
+type BeginInstallResult struct {
+ SessionID string `json:"session_id"`
+ Status string `json:"status"`
+}
+
+// BeginInstall admits or reuses a session.
+//
+// Everything runs under a per-workspace advisory lock. Without it, concurrent
+// begins race past each of the guards below — two `creating` rows for one agent,
+// a missed pending recovery, a rate limit both callers read as unexceeded — and
+// every duplicate spends a WeCom generate quota slot and shows the admin a
+// second QR for a bot nobody will own.
+func (s *InstallService) BeginInstall(ctx context.Context, p BeginInstallParams) (BeginInstallResult, error) {
+ if !s.Configured() {
+ return BeginInstallResult{}, ErrInstallNotConfigured
+ }
+ key := strings.TrimSpace(p.IdempotencyKey)
+ if key == "" {
+ return BeginInstallResult{}, ErrIdempotencyKeyRequired
+ }
+ if len(key) > maxIdempotencyKeyLen {
+ return BeginInstallResult{}, ErrIdempotencyKeyTooLong
+ }
+ hash := hashIdempotencyKey(key)
+
+ tx, err := s.tx.Begin(ctx)
+ if err != nil {
+ return BeginInstallResult{}, fmt.Errorf("wecom begin: start tx: %w", err)
+ }
+ defer func() { _ = tx.Rollback(ctx) }()
+ qtx := s.store.WithTx(tx)
+
+ if err := qtx.LockWecomInstallBeginWorkspace(ctx, p.WorkspaceID); err != nil {
+ return BeginInstallResult{}, fmt.Errorf("wecom begin: advisory lock: %w", err)
+ }
+
+ // Replay: the same key from the same initiator always returns the same
+ // session. A cross-agent replay is a hard conflict, never a retarget.
+ if existing, err := qtx.GetWecomInstallSessionByRequestHash(ctx, db.GetWecomInstallSessionByRequestHashParams{
+ WorkspaceID: p.WorkspaceID,
+ InitiatorUserID: p.InitiatorID,
+ RequestKeyHash: hash,
+ }); err == nil {
+ if !uuidsEqual(existing.AgentID, p.AgentID) {
+ return BeginInstallResult{}, ErrAgentMismatch
+ }
+ if err := tx.Commit(ctx); err != nil {
+ return BeginInstallResult{}, fmt.Errorf("wecom begin: commit replay: %w", err)
+ }
+ return BeginInstallResult{SessionID: util.UUIDToString(existing.ID), Status: existing.Status}, nil
+ } else if !errors.Is(err, pgx.ErrNoRows) {
+ return BeginInstallResult{}, fmt.Errorf("wecom begin: replay lookup: %w", err)
+ }
+
+ // A live bot already exists for this agent. Creating a second one on WeCom's
+ // side would leave the first orphaned there.
+ if _, err := qtx.GetActiveWecomInstallationForAgent(ctx, db.GetActiveWecomInstallationForAgentParams{
+ WorkspaceID: p.WorkspaceID,
+ AgentID: p.AgentID,
+ }); err == nil {
+ return BeginInstallResult{}, ErrActiveInstallationExists
+ } else if !errors.Is(err, pgx.ErrNoRows) {
+ return BeginInstallResult{}, fmt.Errorf("wecom begin: active install lookup: %w", err)
+ }
+
+ // At most one live session per agent (enforced by a partial unique index).
+ // Any caller resumes it: only workspace admins reach begin, and any of them
+ // may finish a scan a colleague started, so a colleague who closed their
+ // laptop mid-scan does not leave the agent's slot locked until it expires.
+ if pending, err := qtx.GetPendingWecomInstallSessionByAgent(ctx, db.GetPendingWecomInstallSessionByAgentParams{
+ WorkspaceID: p.WorkspaceID,
+ AgentID: p.AgentID,
+ }); err == nil {
+ if err := tx.Commit(ctx); err != nil {
+ return BeginInstallResult{}, fmt.Errorf("wecom begin: commit resume: %w", err)
+ }
+ return BeginInstallResult{SessionID: util.UUIDToString(pending.ID), Status: pending.Status}, nil
+ } else if !errors.Is(err, pgx.ErrNoRows) {
+ return BeginInstallResult{}, fmt.Errorf("wecom begin: pending lookup: %w", err)
+ }
+
+ // Rate window. Counts every session in the window regardless of outcome:
+ // each begin can spend a WeCom generate slot, and that quota belongs to the
+ // deployment, shared across workspaces.
+ counts, err := qtx.CountWecomInstallSessionsInWindow(ctx, db.CountWecomInstallSessionsInWindowParams{
+ WorkspaceID: p.WorkspaceID,
+ InitiatorUserID: p.InitiatorID,
+ Since: pgtype.Timestamptz{Time: s.cfg.Now().Add(-s.cfg.RateWindow), Valid: true},
+ })
+ if err != nil {
+ return BeginInstallResult{}, fmt.Errorf("wecom begin: rate count: %w", err)
+ }
+ if counts.ByUser >= int64(s.cfg.RatePerUser) || counts.Total >= int64(s.cfg.RatePerWorkspace) {
+ return BeginInstallResult{}, ErrRateLimited
+ }
+
+ session, err := qtx.CreateWecomInstallSession(ctx, db.CreateWecomInstallSessionParams{
+ WorkspaceID: p.WorkspaceID,
+ AgentID: p.AgentID,
+ InitiatorUserID: p.InitiatorID,
+ RequestKeyHash: hash,
+ })
+ if err != nil {
+ return BeginInstallResult{}, fmt.Errorf("wecom begin: create session: %w", err)
+ }
+ if err := tx.Commit(ctx); err != nil {
+ return BeginInstallResult{}, fmt.Errorf("wecom begin: commit: %w", err)
+ }
+ // Wake the worker so generate runs now instead of on the next poll tick —
+ // the admin is watching a spinner.
+ s.notify()
+ return BeginInstallResult{SessionID: util.UUIDToString(session.ID), Status: session.Status}, nil
+}
+
+// SessionSnapshot is what the status handler returns. It never carries the
+// ciphertext columns; QRCodeURL is populated only for an authorized viewer.
+type SessionSnapshot struct {
+ ID pgtype.UUID
+ WorkspaceID pgtype.UUID
+ AgentID pgtype.UUID
+ InitiatorUserID pgtype.UUID
+ Status string
+ QRCodeURL string
+ ExpiresAt time.Time
+ InstallationID pgtype.UUID
+ ErrorReason string
+}
+
+// GetSession loads a session, scoped to the workspace so a session id cannot be
+// used to enumerate across tenants. The handler already scoped the route; this
+// re-checks because the cost is one comparison.
+//
+// decryptQR must be true only for a caller who may connect a bot to this
+// workspace (the route admits owners and admins): the QR URL embeds the scode,
+// so anyone holding it can finish creating the bot.
+func (s *InstallService) GetSession(ctx context.Context, workspaceID, sessionID pgtype.UUID, decryptQR bool) (SessionSnapshot, error) {
+ row, err := s.store.GetWecomInstallSession(ctx, sessionID)
+ if err != nil {
+ if errors.Is(err, pgx.ErrNoRows) {
+ return SessionSnapshot{}, ErrSessionNotFound
+ }
+ return SessionSnapshot{}, fmt.Errorf("wecom get session: %w", err)
+ }
+ if !uuidsEqual(row.WorkspaceID, workspaceID) {
+ return SessionSnapshot{}, ErrSessionNotFound
+ }
+ snap := SessionSnapshot{
+ ID: row.ID,
+ WorkspaceID: row.WorkspaceID,
+ AgentID: row.AgentID,
+ InitiatorUserID: row.InitiatorUserID,
+ Status: row.Status,
+ }
+ if row.ExpiresAt.Valid {
+ snap.ExpiresAt = row.ExpiresAt.Time
+ }
+ if row.InstallationID.Valid {
+ snap.InstallationID = row.InstallationID
+ }
+ if row.ErrorReason.Valid {
+ snap.ErrorReason = row.ErrorReason.String
+ }
+ if decryptQR && row.QrCodeUrlEncrypted.Valid && s.cfg.Box != nil {
+ if plain, err := decodeAndOpen(s.cfg.Box, row.QrCodeUrlEncrypted.String); err == nil {
+ snap.QRCodeURL = string(plain)
+ } else {
+ // A QR we cannot decrypt is no reason to fail the poll: the status is
+ // still useful, and the worker will terminate the session.
+ s.cfg.Logger.WarnContext(ctx, "wecom: decrypt qr_code_url failed",
+ "session_id", util.UUIDToString(row.ID), "error", err)
+ }
+ }
+ return snap, nil
+}
+
+// hashIdempotencyKey collapses the client's string onto a fixed-width column.
+// Storing it raw would put a client-chosen value in every DB dump for no product
+// benefit.
+func hashIdempotencyKey(key string) string {
+ sum := sha256.Sum256([]byte(key))
+ return hex.EncodeToString(sum[:])
+}
+
+// mintLeaseToken returns the token that fences one worker's claim.
+func mintLeaseToken() (string, error) {
+ var buf [16]byte
+ if _, err := rand.Read(buf[:]); err != nil {
+ return "", fmt.Errorf("wecom: mint lease token: %w", err)
+ }
+ return hex.EncodeToString(buf[:]), nil
+}
+
+// sealAndEncode seals plaintext and base64-encodes it for a TEXT column.
+func sealAndEncode(box *secretbox.Box, plaintext []byte) (string, error) {
+ if box == nil {
+ return "", errors.New("wecom: secretbox not configured")
+ }
+ sealed, err := box.Seal(plaintext)
+ if err != nil {
+ return "", fmt.Errorf("wecom: seal: %w", err)
+ }
+ return base64.StdEncoding.EncodeToString(sealed), nil
+}
+
+// decodeAndOpen is sealAndEncode's inverse.
+func decodeAndOpen(box *secretbox.Box, encoded string) ([]byte, error) {
+ if box == nil {
+ return nil, errors.New("wecom: secretbox not configured")
+ }
+ raw, err := base64.StdEncoding.DecodeString(encoded)
+ if err != nil {
+ return nil, fmt.Errorf("wecom: decode: %w", err)
+ }
+ return box.Open(raw)
+}
+
+func uuidsEqual(a, b pgtype.UUID) bool {
+ return a.Valid && b.Valid && a.Bytes == b.Bytes
+}
diff --git a/server/internal/integrations/wecom/install_db_test.go b/server/internal/integrations/wecom/install_db_test.go
new file mode 100644
index 0000000000..f1810d5705
--- /dev/null
+++ b/server/internal/integrations/wecom/install_db_test.go
@@ -0,0 +1,612 @@
+package wecom
+
+// install_db_test.go — the scan-install guarantees that live in SQL, run against
+// a real Postgres.
+//
+// install_test.go drives the service and worker against an in-memory store, so
+// everything it proves is about the Go code's decisions. What the Go code relies
+// on and cannot prove for itself is in the queries: the per-workspace advisory
+// lock that serializes begin, the FOR UPDATE SKIP LOCKED claim, the lease
+// predicate that makes a live claim unclaimable, and the lease_token match on
+// every mutation that stops a worker whose lease expired from writing over the
+// replica that now owns the session. A fake answers whatever the test tells it
+// to; only the database can show those clauses do what the comments say.
+//
+// They skip when no migrated database is reachable (CI has one). Fixtures are
+// disjoint from the other DB tests in this package.
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/jackc/pgx/v5"
+ "github.com/jackc/pgx/v5/pgtype"
+ "github.com/jackc/pgx/v5/pgxpool"
+
+ "github.com/multica-ai/multica/server/internal/util"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+)
+
+const (
+ wcScanWS = "5c0a1500-0000-4000-8000-000000000001"
+ wcScanRuntime = "5c0a1500-0000-4000-8000-000000000002"
+ wcScanUser = "5c0a1500-0000-4000-8000-000000000003"
+ // Agents are numbered from here: wcScanAgent(0), wcScanAgent(1), ...
+ wcScanAgentBase = "5c0a1500-0000-4000-8000-0000000001%02x"
+)
+
+func wcScanAgent(n int) string { return fmt.Sprintf(wcScanAgentBase, n) }
+
+// setupScanDB returns a pool with the fixture workspace and n agents seeded and
+// every install session in that workspace removed.
+//
+// The claim query is not workspace-scoped — a worker takes the oldest due
+// session anywhere — so a live session left in the table by something else would
+// be claimed by these tests in place of their own. That is checked rather than
+// cleaned up: deleting another test's rows would hide its leak.
+func setupScanDB(t *testing.T, agents int) (context.Context, *pgxpool.Pool) {
+ t.Helper()
+ pool := reclaimTestDB(t)
+ ctx := context.Background()
+ var present bool
+ if err := pool.QueryRow(ctx, "SELECT to_regclass('public.wecom_install_session') IS NOT NULL").Scan(&present); err != nil || !present {
+ t.Skip("wecom_install_session not present (database not migrated)")
+ }
+ cleanScan := func() {
+ _, _ = pool.Exec(ctx, `DELETE FROM wecom_install_session WHERE workspace_id = $1`, wcScanWS)
+ _, _ = pool.Exec(ctx, `DELETE FROM channel_installation WHERE workspace_id = $1`, wcScanWS)
+ _, _ = pool.Exec(ctx, `DELETE FROM agent WHERE workspace_id = $1`, wcScanWS)
+ _, _ = pool.Exec(ctx, `DELETE FROM agent_runtime WHERE workspace_id = $1`, wcScanWS)
+ _, _ = pool.Exec(ctx, `DELETE FROM workspace WHERE id = $1`, wcScanWS)
+ }
+ cleanScan()
+ t.Cleanup(cleanScan)
+
+ var foreign int
+ if err := pool.QueryRow(ctx, `SELECT count(*) FROM wecom_install_session WHERE status IN ('creating', 'pending')`).Scan(&foreign); err != nil {
+ t.Fatalf("count live sessions: %v", err)
+ }
+ if foreign != 0 {
+ t.Fatalf("%d live install session(s) outside this test's workspace; the claim would take them instead of this test's own", foreign)
+ }
+
+ exec := func(q string, args ...any) {
+ t.Helper()
+ if _, err := pool.Exec(ctx, q, args...); err != nil {
+ t.Fatalf("seed: %v", err)
+ }
+ }
+ exec(`INSERT INTO workspace (id, name, slug, description) VALUES ($1, 'wecom scan', 'wecom-scan', '')`, wcScanWS)
+ exec(`INSERT INTO agent_runtime (id, workspace_id, name, runtime_mode, provider)
+VALUES ($1, $2, 'wecom scan runtime', 'local', 'multica_daemon')`, wcScanRuntime, wcScanWS)
+ for i := 0; i < agents; i++ {
+ exec(`INSERT INTO agent (id, workspace_id, name, runtime_mode, runtime_id)
+VALUES ($1, $2, $3, 'local', $4)`, wcScanAgent(i), wcScanWS, fmt.Sprintf("wecom scan %d", i), wcScanRuntime)
+ }
+ return ctx, pool
+}
+
+func newDBInstallService(t *testing.T, pool *pgxpool.Pool, provider Provider, binder BotBinder, cfg InstallServiceConfig) *InstallService {
+ t.Helper()
+ cfg.Provider = provider
+ cfg.Box = testBox(t)
+ return NewInstallService(db.New(pool), pool, binder, cfg)
+}
+
+func scanBegin(agent int, key string) BeginInstallParams {
+ return BeginInstallParams{
+ WorkspaceID: mustUUID(wcScanWS),
+ AgentID: mustUUID(wcScanAgent(agent)),
+ InitiatorID: mustUUID(wcScanUser),
+ IdempotencyKey: key,
+ }
+}
+
+func loadSession(t *testing.T, ctx context.Context, pool *pgxpool.Pool, id string) db.WecomInstallSession {
+ t.Helper()
+ row, err := db.New(pool).GetWecomInstallSession(ctx, mustUUID(id))
+ if err != nil {
+ t.Fatalf("load session %s: %v", id, err)
+ }
+ return row
+}
+
+// makeDue moves a session's next poll to the database's now, so the next claim
+// takes it without the test depending on the Go and Postgres clocks agreeing.
+func makeDue(t *testing.T, ctx context.Context, pool *pgxpool.Pool, id string) {
+ t.Helper()
+ if _, err := pool.Exec(ctx, `UPDATE wecom_install_session SET poll_after = now() WHERE id = $1`, id); err != nil {
+ t.Fatalf("make due: %v", err)
+ }
+}
+
+func claimParams(token string, ttl time.Duration) db.ClaimDueWecomInstallSessionParams {
+ return db.ClaimDueWecomInstallSessionParams{
+ LeaseToken: pgtype.Text{String: token, Valid: true},
+ LeaseExpiresAt: pgtype.Timestamptz{Time: time.Now().Add(ttl), Valid: true},
+ }
+}
+
+// The advisory lock is what makes begin's read-then-insert a single decision. A
+// begin that arrives while another holds the workspace's lock must wait for it,
+// or the two read the same "nothing pending, under the limit" and both insert.
+func TestInstallDB_BeginWaitsForTheWorkspaceLock(t *testing.T) {
+ ctx, pool := setupScanDB(t, 1)
+ svc := newDBInstallService(t, pool, &fakeProvider{}, &fakeBotBinder{}, InstallServiceConfig{})
+
+ holder, err := pool.Begin(ctx)
+ if err != nil {
+ t.Fatalf("begin holder tx: %v", err)
+ }
+ defer func() { _ = holder.Rollback(ctx) }()
+ if err := db.New(pool).WithTx(holder).LockWecomInstallBeginWorkspace(ctx, mustUUID(wcScanWS)); err != nil {
+ t.Fatalf("take the workspace lock: %v", err)
+ }
+
+ done := make(chan error, 1)
+ go func() {
+ _, err := svc.BeginInstall(ctx, scanBegin(0, "lock-wait"))
+ done <- err
+ }()
+
+ select {
+ case err := <-done:
+ t.Fatalf("BeginInstall returned (err=%v) while another transaction held the workspace's begin lock; "+
+ "concurrent begins are not serialized, so two of them can both pass the pending and rate checks", err)
+ case <-time.After(500 * time.Millisecond):
+ }
+
+ if err := holder.Commit(ctx); err != nil {
+ t.Fatalf("release the lock: %v", err)
+ }
+ select {
+ case err := <-done:
+ if err != nil {
+ t.Fatalf("BeginInstall after the lock was released: %v", err)
+ }
+ case <-time.After(5 * time.Second):
+ t.Fatal("BeginInstall still blocked 5s after the lock was released")
+ }
+}
+
+// Many begins for one agent at once, each with its own key (two tabs, two
+// clicks): they must all land on one session. The begins that find a live
+// session resume it; a begin that tried to insert a second one instead would hit
+// the one-live-session-per-agent index and come back as a 500.
+func TestInstallDB_ConcurrentBeginsForOneAgentShareOneSession(t *testing.T) {
+ ctx, pool := setupScanDB(t, 1)
+ svc := newDBInstallService(t, pool, &fakeProvider{}, &fakeBotBinder{}, InstallServiceConfig{RatePerUser: 100, RatePerWorkspace: 100})
+
+ const n = 8
+ var wg sync.WaitGroup
+ results := make([]BeginInstallResult, n)
+ errs := make([]error, n)
+ start := make(chan struct{})
+ for i := 0; i < n; i++ {
+ wg.Add(1)
+ go func(i int) {
+ defer wg.Done()
+ <-start
+ results[i], errs[i] = svc.BeginInstall(ctx, scanBegin(0, fmt.Sprintf("tab-%d", i)))
+ }(i)
+ }
+ close(start)
+ wg.Wait()
+
+ for i, err := range errs {
+ if err != nil {
+ t.Fatalf("begin %d: %v", i, err)
+ }
+ if results[i].SessionID != results[0].SessionID {
+ t.Fatalf("begin %d got session %s, begin 0 got %s: one agent has two live sessions", i, results[i].SessionID, results[0].SessionID)
+ }
+ }
+ var rows int
+ if err := pool.QueryRow(ctx, `SELECT count(*) FROM wecom_install_session WHERE workspace_id = $1`, wcScanWS).Scan(&rows); err != nil {
+ t.Fatalf("count: %v", err)
+ }
+ if rows != 1 {
+ t.Fatalf("%d session rows for one agent, want 1", rows)
+ }
+}
+
+// The rate cap is a count read under the same lock. Concurrent begins for
+// different agents must not all read "under the limit" and all get in.
+func TestInstallDB_ConcurrentBeginsRespectTheRateCap(t *testing.T) {
+ const agents, limit = 6, 3
+ ctx, pool := setupScanDB(t, agents)
+ svc := newDBInstallService(t, pool, &fakeProvider{}, &fakeBotBinder{}, InstallServiceConfig{RatePerUser: limit, RatePerWorkspace: 100})
+
+ var wg sync.WaitGroup
+ errs := make([]error, agents)
+ start := make(chan struct{})
+ for i := 0; i < agents; i++ {
+ wg.Add(1)
+ go func(i int) {
+ defer wg.Done()
+ <-start
+ _, errs[i] = svc.BeginInstall(ctx, scanBegin(i, fmt.Sprintf("agent-%d", i)))
+ }(i)
+ }
+ close(start)
+ wg.Wait()
+
+ admitted := 0
+ for i, err := range errs {
+ switch {
+ case err == nil:
+ admitted++
+ case errors.Is(err, ErrRateLimited):
+ default:
+ t.Fatalf("begin for agent %d: %v", i, err)
+ }
+ }
+ if admitted != limit {
+ t.Fatalf("%d of %d concurrent begins admitted with a per-user cap of %d", admitted, agents, limit)
+ }
+}
+
+// A claim that is in flight holds its row locked until its statement commits.
+// A second worker must step past it to the next row — not wait on it, and not
+// take it too.
+func TestInstallDB_ClaimSkipsARowAnotherWorkerIsClaiming(t *testing.T) {
+ ctx, pool := setupScanDB(t, 2)
+ svc := newDBInstallService(t, pool, &fakeProvider{}, &fakeBotBinder{}, InstallServiceConfig{})
+ first, err := svc.BeginInstall(ctx, scanBegin(0, "skip-a"))
+ if err != nil {
+ t.Fatalf("begin a: %v", err)
+ }
+ second, err := svc.BeginInstall(ctx, scanBegin(1, "skip-b"))
+ if err != nil {
+ t.Fatalf("begin b: %v", err)
+ }
+
+ slow, err := pool.Begin(ctx)
+ if err != nil {
+ t.Fatalf("begin slow tx: %v", err)
+ }
+ defer func() { _ = slow.Rollback(ctx) }()
+ held, err := db.New(pool).WithTx(slow).ClaimDueWecomInstallSession(ctx, claimParams("slow", time.Minute))
+ if err != nil {
+ t.Fatalf("slow claim: %v", err)
+ }
+
+ type claimed struct {
+ row db.WecomInstallSession
+ err error
+ }
+ got := make(chan claimed, 1)
+ go func() {
+ row, err := db.New(pool).ClaimDueWecomInstallSession(ctx, claimParams("fast", time.Minute))
+ got <- claimed{row, err}
+ }()
+ select {
+ case c := <-got:
+ if c.err != nil {
+ t.Fatalf("second claim: %v", c.err)
+ }
+ if c.row.ID == held.ID {
+ t.Fatalf("both workers claimed session %s", util.UUIDToString(held.ID))
+ }
+ want := map[string]bool{first.SessionID: true, second.SessionID: true}
+ if !want[util.UUIDToString(c.row.ID)] {
+ t.Fatalf("second claim took %s, which is neither fixture session", util.UUIDToString(c.row.ID))
+ }
+ case <-time.After(2 * time.Second):
+ t.Fatal("the second claim blocked on the row the first claim holds instead of skipping it; " +
+ "replicas would serialize on one hot session")
+ }
+}
+
+// A live lease makes a session unclaimable; an expired one hands it to the next
+// worker. And from then on the old worker's writes all miss: deferring, failing
+// and completing each match on the lease token, so a worker that stalled past
+// its lease cannot overwrite what the new owner is doing.
+func TestInstallDB_LeaseFencesEveryWrite(t *testing.T) {
+ ctx, pool := setupScanDB(t, 1)
+ q := db.New(pool)
+ svc := newDBInstallService(t, pool, &fakeProvider{}, &fakeBotBinder{}, InstallServiceConfig{})
+ begun, err := svc.BeginInstall(ctx, scanBegin(0, "fence"))
+ if err != nil {
+ t.Fatalf("begin: %v", err)
+ }
+ id := mustUUID(begun.SessionID)
+
+ if _, err := q.ClaimDueWecomInstallSession(ctx, claimParams("old", time.Minute)); err != nil {
+ t.Fatalf("first claim: %v", err)
+ }
+ if _, err := q.ClaimDueWecomInstallSession(ctx, claimParams("thief", time.Minute)); !errors.Is(err, pgx.ErrNoRows) {
+ t.Fatalf("claim while the lease is live: err=%v, want ErrNoRows — two workers would drive one session", err)
+ }
+
+ // The old worker stalls past its lease; a second worker takes the session
+ // and moves it to pending.
+ if _, err := pool.Exec(ctx, `UPDATE wecom_install_session SET lease_expires_at = now() - interval '1 second' WHERE id = $1`, id); err != nil {
+ t.Fatalf("expire lease: %v", err)
+ }
+ if _, err := q.ClaimDueWecomInstallSession(ctx, claimParams("new", time.Minute)); err != nil {
+ t.Fatalf("claim after expiry: %v", err)
+ }
+ // The new owner is mid-step: still holding its lease, moving to pending.
+ if _, err := pool.Exec(ctx, `UPDATE wecom_install_session SET status = 'pending' WHERE id = $1`, id); err != nil {
+ t.Fatalf("advance to pending: %v", err)
+ }
+
+ stale := pgtype.Text{String: "old", Valid: true}
+ if n, err := q.DeferClaimedWecomInstallSession(ctx, db.DeferClaimedWecomInstallSessionParams{
+ ID: id, LeaseToken: stale, Status: InstallStatusCreating,
+ PollAfter: pgtype.Timestamptz{Time: time.Now(), Valid: true},
+ }); err != nil || n != 0 {
+ t.Errorf("defer under the expired lease: rows=%d err=%v, want 0 rows", n, err)
+ }
+ if n, err := q.FailWecomInstallSession(ctx, db.FailWecomInstallSessionParams{
+ ID: id, LeaseToken: stale,
+ ErrorReason: pgtype.Text{String: InstallErrorInternalError, Valid: true},
+ }); err != nil || n != 0 {
+ t.Errorf("fail under the expired lease: rows=%d err=%v, want 0 rows", n, err)
+ }
+ if n, err := q.CompleteWecomInstallSession(ctx, db.CompleteWecomInstallSessionParams{
+ ID: id, LeaseToken: stale, InstallationID: mustUUID(wcScanRuntime),
+ }); err != nil || n != 0 {
+ t.Errorf("complete under the expired lease: rows=%d err=%v, want 0 rows", n, err)
+ }
+
+ row := loadSession(t, ctx, pool, begun.SessionID)
+ if row.Status != InstallStatusPending || row.LeaseToken.String != "new" || row.ErrorReason.Valid || row.InstallationID.Valid {
+ t.Fatalf("the stale worker changed the session: status=%s lease=%q error_reason=%v installation_id=%v",
+ row.Status, row.LeaseToken.String, row.ErrorReason, row.InstallationID.Valid)
+ }
+
+ // The current owner's writes still land.
+ if n, err := q.CompleteWecomInstallSession(ctx, db.CompleteWecomInstallSessionParams{
+ ID: id, LeaseToken: pgtype.Text{String: "new", Valid: true}, InstallationID: mustUUID(wcScanRuntime),
+ }); err != nil || n != 1 {
+ t.Fatalf("complete under the live lease: rows=%d err=%v, want 1", n, err)
+ }
+}
+
+// Complete is fenced on status as well as lease: a session still creating has
+// no scanned bot, so completing it would record a success that never happened.
+func TestInstallDB_CompleteRequiresPending(t *testing.T) {
+ ctx, pool := setupScanDB(t, 1)
+ q := db.New(pool)
+ svc := newDBInstallService(t, pool, &fakeProvider{}, &fakeBotBinder{}, InstallServiceConfig{})
+ begun, err := svc.BeginInstall(ctx, scanBegin(0, "complete-creating"))
+ if err != nil {
+ t.Fatalf("begin: %v", err)
+ }
+ if _, err := q.ClaimDueWecomInstallSession(ctx, claimParams("owner", time.Minute)); err != nil {
+ t.Fatalf("claim: %v", err)
+ }
+ if n, err := q.CompleteWecomInstallSession(ctx, db.CompleteWecomInstallSessionParams{
+ ID: mustUUID(begun.SessionID), LeaseToken: pgtype.Text{String: "owner", Valid: true}, InstallationID: mustUUID(wcScanRuntime),
+ }); err != nil || n != 0 {
+ t.Fatalf("complete on a creating session: rows=%d err=%v, want 0", n, err)
+ }
+ if row := loadSession(t, ctx, pool, begun.SessionID); row.Status != InstallStatusCreating {
+ t.Fatalf("status = %s, want creating", row.Status)
+ }
+}
+
+// The whole walk on the real tables: begin, the worker fetches and seals the QR,
+// the admin scans, the bot is bound through the same InstallationService the
+// manual form uses, and the session settles with its secrets wiped. Then a
+// settled session is never claimed again.
+func TestInstallDB_WorkerWalksASessionToSuccess(t *testing.T) {
+ ctx, pool := setupScanDB(t, 1)
+ provider := &fakeProvider{gen: GenerateResult{Scode: "scode-walk", AuthURL: "https://example.test/qr?scode=scode-walk"}}
+ binder, err := NewInstallationService(db.New(pool), pool, testBox(t), WithCredentialProbe(&fakeProbe{}))
+ if err != nil {
+ t.Fatalf("NewInstallationService: %v", err)
+ }
+ svc := newDBInstallService(t, pool, provider, binder, InstallServiceConfig{})
+ w := NewInstallWorker(svc, InstallWorkerConfig{})
+
+ begun, err := svc.BeginInstall(ctx, scanBegin(0, "walk"))
+ if err != nil {
+ t.Fatalf("begin: %v", err)
+ }
+
+ // creating → pending
+ if worked, err := w.processOne(ctx); err != nil || !worked {
+ t.Fatalf("generate step: worked=%v err=%v", worked, err)
+ }
+ row := loadSession(t, ctx, pool, begun.SessionID)
+ if row.Status != InstallStatusPending || row.LeaseToken.Valid || !row.ExpiresAt.Valid {
+ t.Fatalf("after generate: status=%s lease=%v expires_at=%v, want pending, lease released, expiry set",
+ row.Status, row.LeaseToken.Valid, row.ExpiresAt.Valid)
+ }
+ if row.ScodeEncrypted.String == "" || row.ScodeEncrypted.String == "scode-walk" {
+ t.Fatalf("scode stored as %q, want sealed ciphertext", row.ScodeEncrypted.String)
+ }
+ snap, err := svc.GetSession(ctx, mustUUID(wcScanWS), mustUUID(begun.SessionID), true)
+ if err != nil || snap.QRCodeURL != provider.gen.AuthURL {
+ t.Fatalf("status read: qr=%q err=%v, want the generated URL back", snap.QRCodeURL, err)
+ }
+
+ // Not scanned yet: the poll defers and the session stays pending.
+ provider.query = QueryResult{Status: QueryStatusPending}
+ makeDue(t, ctx, pool, begun.SessionID)
+ if worked, err := w.processOne(ctx); err != nil || !worked {
+ t.Fatalf("pending poll: worked=%v err=%v", worked, err)
+ }
+ if row := loadSession(t, ctx, pool, begun.SessionID); row.Status != InstallStatusPending || row.LeaseToken.Valid {
+ t.Fatalf("after an unscanned poll: status=%s lease=%v, want pending with the lease released", row.Status, row.LeaseToken.Valid)
+ }
+
+ // Scanned.
+ provider.query = QueryResult{Status: QueryStatusSuccess, BotInfo: &BotInfo{BotID: "bot_scan_walk", Secret: "s3cret"}}
+ makeDue(t, ctx, pool, begun.SessionID)
+ if worked, err := w.processOne(ctx); err != nil || !worked {
+ t.Fatalf("success poll: worked=%v err=%v", worked, err)
+ }
+ row = loadSession(t, ctx, pool, begun.SessionID)
+ if row.Status != InstallStatusSuccess || !row.InstallationID.Valid {
+ t.Fatalf("after scan: status=%s installation_id=%v, want success with an installation", row.Status, row.InstallationID.Valid)
+ }
+ if row.ScodeEncrypted.Valid || row.QrCodeUrlEncrypted.Valid || row.LeaseToken.Valid {
+ t.Fatalf("a settled session still carries scode=%v qr=%v lease=%v", row.ScodeEncrypted.Valid, row.QrCodeUrlEncrypted.Valid, row.LeaseToken.Valid)
+ }
+ var app, status string
+ if err := pool.QueryRow(ctx, `SELECT config->>'app_id', status FROM channel_installation WHERE id = $1`, row.InstallationID).Scan(&app, &status); err != nil {
+ t.Fatalf("read the bound installation: %v", err)
+ }
+ if app != "bot_scan_walk" || status != "active" {
+ t.Fatalf("installation app_id=%q status=%q, want the scanned bot, active", app, status)
+ }
+
+ if worked, err := w.processOne(ctx); err != nil || worked {
+ t.Fatalf("a settled session was claimed again: worked=%v err=%v", worked, err)
+ }
+}
+
+// The reason a failed bind ends with comes from what the real InstallationService
+// returns, not from a stub: a bot another agent already holds is a conflict,
+// and a bot the probe could not reach is one that was created and not
+// connected. If Upsert ever stopped returning the sentinels errors.Is can see,
+// the first case would silently turn into the second.
+func TestInstallDB_BindFailureReasonComesFromTheRealBind(t *testing.T) {
+ ctx, pool := setupScanDB(t, 2)
+ exec := func(q string, args ...any) {
+ t.Helper()
+ if _, err := pool.Exec(ctx, q, args...); err != nil {
+ t.Fatalf("seed: %v", err)
+ }
+ }
+ // Agent 1 already holds bot_scan_held.
+ exec(`INSERT INTO channel_installation (workspace_id, agent_id, channel_type, config, installer_user_id, status)
+VALUES ($1, $2, 'wecom', '{"app_id":"bot_scan_held","bot_id":"bot_scan_held","app_secret_encrypted":""}', $3, 'active')`,
+ wcScanWS, wcScanAgent(1), wcScanUser)
+
+ for _, tc := range []struct {
+ name string
+ bot string
+ probe error
+ want string
+ }{
+ {"bot held by another agent", "bot_scan_held", nil, InstallErrorInstallationConflict},
+ {"probe cannot reach WeCom", "bot_scan_fresh", context.DeadlineExceeded, InstallErrorBindFailed},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ exec(`DELETE FROM wecom_install_session WHERE workspace_id = $1`, wcScanWS)
+ provider := &fakeProvider{gen: GenerateResult{Scode: "scode-" + tc.bot, AuthURL: "https://example.test/qr"}}
+ binder, err := NewInstallationService(db.New(pool), pool, testBox(t), WithCredentialProbe(&fakeProbe{err: tc.probe}))
+ if err != nil {
+ t.Fatalf("NewInstallationService: %v", err)
+ }
+ svc := newDBInstallService(t, pool, provider, binder, InstallServiceConfig{})
+ w := NewInstallWorker(svc, InstallWorkerConfig{})
+
+ begun, err := svc.BeginInstall(ctx, scanBegin(0, tc.bot))
+ if err != nil {
+ t.Fatalf("begin: %v", err)
+ }
+ if worked, err := w.processOne(ctx); err != nil || !worked {
+ t.Fatalf("generate step: worked=%v err=%v", worked, err)
+ }
+ provider.query = QueryResult{Status: QueryStatusSuccess, BotInfo: &BotInfo{BotID: tc.bot, Secret: "s3cret"}}
+ makeDue(t, ctx, pool, begun.SessionID)
+ if worked, err := w.processOne(ctx); err != nil || !worked {
+ t.Fatalf("success poll: worked=%v err=%v", worked, err)
+ }
+ row := loadSession(t, ctx, pool, begun.SessionID)
+ if row.Status != InstallStatusError || row.ErrorReason.String != tc.want {
+ t.Fatalf("status=%s reason=%q, want failed with %s", row.Status, row.ErrorReason.String, tc.want)
+ }
+ })
+ }
+}
+
+// A QR nobody scanned in time ends as expired, with the ciphertext wiped.
+func TestInstallDB_ExpiredSessionEndsAsExpired(t *testing.T) {
+ ctx, pool := setupScanDB(t, 1)
+ provider := &fakeProvider{gen: GenerateResult{Scode: "scode-exp", AuthURL: "https://example.test/qr?scode=scode-exp"}}
+ svc := newDBInstallService(t, pool, provider, &fakeBotBinder{}, InstallServiceConfig{})
+ w := NewInstallWorker(svc, InstallWorkerConfig{})
+ begun, err := svc.BeginInstall(ctx, scanBegin(0, "expire"))
+ if err != nil {
+ t.Fatalf("begin: %v", err)
+ }
+ if _, err := w.processOne(ctx); err != nil {
+ t.Fatalf("generate: %v", err)
+ }
+ if _, err := pool.Exec(ctx, `UPDATE wecom_install_session SET expires_at = now() - interval '1 second', poll_after = now() WHERE id = $1`, mustUUID(begun.SessionID)); err != nil {
+ t.Fatalf("expire: %v", err)
+ }
+ if _, err := w.processOne(ctx); err != nil {
+ t.Fatalf("expiry poll: %v", err)
+ }
+ row := loadSession(t, ctx, pool, begun.SessionID)
+ if row.Status != InstallStatusError || row.ErrorReason.String != InstallErrorExpired {
+ t.Fatalf("status=%s reason=%q, want error/expired", row.Status, row.ErrorReason.String)
+ }
+ if row.ScodeEncrypted.Valid || row.QrCodeUrlEncrypted.Valid {
+ t.Fatal("an expired session kept its sealed scode or QR URL")
+ }
+ if provider.queryCall != 0 {
+ t.Fatalf("query_result called %d times for an already-expired QR", provider.queryCall)
+ }
+}
+
+// Purge removes settled sessions past retention and creating rows nobody ever
+// claimed, and leaves everything still live or still within retention.
+func TestInstallDB_PurgeKeepsLiveAndRecentSessions(t *testing.T) {
+ ctx, pool := setupScanDB(t, 0)
+ insert := func(status, age string) string {
+ t.Helper()
+ var id string
+ if err := pool.QueryRow(ctx, `
+INSERT INTO wecom_install_session (request_key_hash, workspace_id, agent_id, initiator_user_id, status, created_at, updated_at)
+VALUES (gen_random_uuid()::text, $1, gen_random_uuid(), $2, $3, now() - $4::interval, now() - $4::interval)
+RETURNING id::text`, wcScanWS, wcScanUser, status, age).Scan(&id); err != nil {
+ t.Fatalf("insert %s/%s: %v", status, age, err)
+ }
+ return id
+ }
+ oldSuccess := insert("success", "1 hour")
+ oldError := insert("error", "1 hour")
+ oldCreating := insert("creating", "10 minutes")
+ recentSuccess := insert("success", "1 minute")
+ recentCreating := insert("creating", "5 seconds")
+ oldPending := insert("pending", "1 hour")
+
+ svc := newDBInstallService(t, pool, &fakeProvider{}, &fakeBotBinder{}, InstallServiceConfig{})
+ w := NewInstallWorker(svc, InstallWorkerConfig{})
+ if err := w.purge(ctx); err != nil {
+ t.Fatalf("purge: %v", err)
+ }
+
+ exists := func(id string) bool {
+ var ok bool
+ if err := pool.QueryRow(ctx, `SELECT EXISTS (SELECT 1 FROM wecom_install_session WHERE id = $1)`, id).Scan(&ok); err != nil {
+ t.Fatalf("exists: %v", err)
+ }
+ return ok
+ }
+ for name, id := range map[string]string{"old success": oldSuccess, "old error": oldError, "old creating": oldCreating} {
+ if exists(id) {
+ t.Errorf("%s session survived the purge", name)
+ }
+ }
+ for name, id := range map[string]string{"recent success": recentSuccess, "recent creating": recentCreating, "old pending": oldPending} {
+ if !exists(id) {
+ t.Errorf("%s session was purged", name)
+ }
+ }
+}
+
+// The status column only takes the four values the code and the frontend
+// switch on.
+func TestInstallDB_StatusIsConstrained(t *testing.T) {
+ ctx, pool := setupScanDB(t, 0)
+ _, err := pool.Exec(ctx, `
+INSERT INTO wecom_install_session (request_key_hash, workspace_id, agent_id, initiator_user_id, status)
+VALUES ('x', $1, gen_random_uuid(), $2, 'scanned')`, wcScanWS, wcScanUser)
+ if err == nil {
+ t.Fatal("a status outside creating/pending/success/error was accepted")
+ }
+}
diff --git a/server/internal/integrations/wecom/install_provider.go b/server/internal/integrations/wecom/install_provider.go
new file mode 100644
index 0000000000..b10f23f1bf
--- /dev/null
+++ b/server/internal/integrations/wecom/install_provider.go
@@ -0,0 +1,214 @@
+package wecom
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "log/slog"
+ "net/http"
+ "net/url"
+ "time"
+)
+
+// Provider abstracts the WeCom scan-code create-bot API. The HTTPProvider
+// implementation talks to work.weixin.qq.com/ai/qc/{generate,query_result};
+// the install worker uses the interface directly so tests can inject a fake
+// with deterministic responses.
+type Provider interface {
+ // Generate creates a fresh QR session. `scode` is the polling handle;
+ // `auth_url` is the URL the frontend renders into a QR image.
+ Generate(ctx context.Context) (GenerateResult, error)
+ // QueryResult polls the QR status for a previously-generated scode.
+ // Two-second minimum interval is enforced by the worker, not here.
+ QueryResult(ctx context.Context, scode string) (QueryResult, error)
+}
+
+// GenerateResult mirrors the /ai/qc/generate payload, which arrives nested
+// under `data` on the wire — see decodeProviderBody.
+type GenerateResult struct {
+ Scode string `json:"scode"`
+ AuthURL string `json:"auth_url"`
+}
+
+// QueryStatus enumerates the /ai/qc/query_result "status" wire values. init
+// and pending are treated identically by the worker — the doc
+// calls out that both mean "unauthorized OR expired", so the worker relies
+// on the DB-side expires_at check for terminal expiry rather than trusting
+// this string to tell them apart.
+type QueryStatus string
+
+const (
+ QueryStatusInit QueryStatus = "init"
+ QueryStatusPending QueryStatus = "pending"
+ QueryStatusSuccess QueryStatus = "success"
+)
+
+// QueryResult is the /ai/qc/query_result payload, nested under `data` on the
+// wire like GenerateResult. BotInfo is only populated when Status is
+// "success".
+type QueryResult struct {
+ Status QueryStatus `json:"status"`
+ BotInfo *BotInfo `json:"bot_info,omitempty"`
+}
+
+// BotInfo carries the credentials WeCom returns on success. `botid` is the
+// wire's `aibotid`; `secret` is the long-connection auth secret.
+// Neither is logged.
+type BotInfo struct {
+ BotID string `json:"botid"`
+ Secret string `json:"secret"`
+}
+
+// HTTPProviderConfig configures the real client. BaseURL defaults to the
+// documented endpoint; tests point it at an httptest server so no real
+// WeCom traffic ever leaves the machine.
+type HTTPProviderConfig struct {
+ BaseURL string
+ SourceID string
+ HTTPClient *http.Client
+ Logger *slog.Logger
+ Timeout time.Duration
+}
+
+// DefaultProviderBaseURL is the documented origin. It is a constant here so
+// a stray env misconfiguration cannot silently point the install path at
+// somebody's private mirror.
+const DefaultProviderBaseURL = "https://work.weixin.qq.com"
+
+// HTTPProvider talks to the real WeCom endpoints. It is safe for concurrent
+// use — every call constructs a fresh request from cfg.
+type HTTPProvider struct {
+ cfg HTTPProviderConfig
+}
+
+// NewHTTPProvider validates the source id and returns a ready client. An
+// empty source id is a hard error; callers gate on Configured() before
+// constructing the provider.
+func NewHTTPProvider(cfg HTTPProviderConfig) (*HTTPProvider, error) {
+ if cfg.SourceID == "" {
+ return nil, errors.New("wecom: HTTPProvider requires SourceID")
+ }
+ if cfg.BaseURL == "" {
+ cfg.BaseURL = DefaultProviderBaseURL
+ }
+ if cfg.HTTPClient == nil {
+ cfg.HTTPClient = &http.Client{Timeout: defaultUpstreamTimeout}
+ }
+ if cfg.Logger == nil {
+ cfg.Logger = slog.Default()
+ }
+ if cfg.Timeout == 0 {
+ cfg.Timeout = defaultUpstreamTimeout
+ }
+ return &HTTPProvider{cfg: cfg}, nil
+}
+
+// Generate hits /ai/qc/generate?source=<source>.
+func (p *HTTPProvider) Generate(ctx context.Context) (GenerateResult, error) {
+ u := p.cfg.BaseURL + "/ai/qc/generate?source=" + url.QueryEscape(p.cfg.SourceID)
+ var out GenerateResult
+ if err := p.getJSON(ctx, u, &out); err != nil {
+ return GenerateResult{}, err
+ }
+ if out.Scode == "" || out.AuthURL == "" {
+ return GenerateResult{}, errors.New("wecom generate: response missing scode / auth_url")
+ }
+ return out, nil
+}
+
+// QueryResult hits /ai/qc/query_result?scode=<scode>&source=<source>. The
+// worker guards the polling cadence.
+func (p *HTTPProvider) QueryResult(ctx context.Context, scode string) (QueryResult, error) {
+ if scode == "" {
+ return QueryResult{}, errors.New("wecom query_result: scode is required")
+ }
+ u := p.cfg.BaseURL + "/ai/qc/query_result?scode=" + url.QueryEscape(scode) +
+ "&source=" + url.QueryEscape(p.cfg.SourceID)
+ var out QueryResult
+ if err := p.getJSON(ctx, u, &out); err != nil {
+ return QueryResult{}, err
+ }
+ switch out.Status {
+ case QueryStatusInit, QueryStatusPending, QueryStatusSuccess:
+ default:
+ return QueryResult{}, fmt.Errorf("wecom query_result: unknown status %q", out.Status)
+ }
+ if out.Status == QueryStatusSuccess {
+ if out.BotInfo == nil || out.BotInfo.BotID == "" || out.BotInfo.Secret == "" {
+ return QueryResult{}, errors.New("wecom query_result: success without bot_info")
+ }
+ }
+ return out, nil
+}
+
+func (p *HTTPProvider) getJSON(ctx context.Context, requestURL string, out any) error {
+ ctx, cancel := context.WithTimeout(ctx, p.cfg.Timeout)
+ defer cancel()
+ req, err := http.NewRequestWithContext(ctx, http.MethodGet, requestURL, nil)
+ if err != nil {
+ return fmt.Errorf("wecom provider: build request: %w", withoutURL(err))
+ }
+ req.Header.Set("Accept", "application/json")
+ resp, err := p.cfg.HTTPClient.Do(req)
+ if err != nil {
+ return fmt.Errorf("wecom provider: http: %w", withoutURL(err))
+ }
+ defer resp.Body.Close()
+ body, err := io.ReadAll(io.LimitReader(resp.Body, 64*1024))
+ if err != nil {
+ return fmt.Errorf("wecom provider: read: %w", withoutURL(err))
+ }
+ if resp.StatusCode < 200 || resp.StatusCode >= 300 {
+ return fmt.Errorf("wecom provider: http %d", resp.StatusCode)
+ }
+ return decodeProviderBody(body, out)
+}
+
+// withoutURL strips the URL out of a *url.Error, keeping host and path.
+//
+// The scode rides in the query string, and *url.Error.Error() prints the URL it
+// failed on in full. The worker logs these errors at Warn from inside the poll
+// loop, so one sustained upstream outage would write a live scode — a bearer
+// credential for "finish creating this bot", per install.go — to the log
+// repeatedly, during exactly the window where it is still redeemable. Every
+// other path treats it as a secret: sealed at rest under the bot-secret key,
+// NULLed by both terminal statements, never returned by any endpoint.
+//
+// Host and path survive because they name which call broke without naming the
+// credential; url.Parse errors carry the raw URL too, so both call sites route
+// through here.
+func withoutURL(err error) error {
+ var uerr *url.Error
+ if !errors.As(err, &uerr) {
+ return err
+ }
+ endpoint := "unknown endpoint"
+ if u, perr := url.Parse(uerr.URL); perr == nil && u.Host+u.Path != "" {
+ endpoint = u.Host + u.Path
+ }
+ return fmt.Errorf("%s %s: %w", uerr.Op, endpoint, uerr.Err)
+}
+
+// decodeProviderBody unwraps the `data` object generate and query_result nest
+// their payload in. The vendored reference doc shows these fields at the top
+// level, which the first implementation trusted; both endpoints in fact wrap.
+// A missing `data` is reported as such rather than decoding into a zero value,
+// so a future shape change surfaces here instead of as an empty-field error
+// further up.
+func decodeProviderBody(body []byte, out any) error {
+ var envelope struct {
+ Data json.RawMessage `json:"data"`
+ }
+ if err := json.Unmarshal(body, &envelope); err != nil {
+ return fmt.Errorf("wecom provider: decode: %w", err)
+ }
+ if len(envelope.Data) == 0 || string(envelope.Data) == "null" {
+ return errors.New("wecom provider: response carries no data object")
+ }
+ if err := json.Unmarshal(envelope.Data, out); err != nil {
+ return fmt.Errorf("wecom provider: decode data: %w", err)
+ }
+ return nil
+}
diff --git a/server/internal/integrations/wecom/install_provider_test.go b/server/internal/integrations/wecom/install_provider_test.go
new file mode 100644
index 0000000000..ba3a533b90
--- /dev/null
+++ b/server/internal/integrations/wecom/install_provider_test.go
@@ -0,0 +1,216 @@
+package wecom
+
+import (
+ "context"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+ "time"
+)
+
+// The vendored reference doc shows generate / query_result fields at the top
+// level of the response body, but live WeCom traffic wraps both in `data`.
+// These tests pin the wrapped shape, which the doc-derived implementation
+// silently failed to decode: Generate returned "missing scode / auth_url" for
+// every real install attempt.
+
+func newTestProvider(t *testing.T, handler http.HandlerFunc) (*HTTPProvider, *httptest.Server) {
+ t.Helper()
+ srv := httptest.NewServer(handler)
+ t.Cleanup(srv.Close)
+ p, err := NewHTTPProvider(HTTPProviderConfig{
+ BaseURL: srv.URL,
+ SourceID: "multica",
+ HTTPClient: srv.Client(),
+ })
+ if err != nil {
+ t.Fatalf("NewHTTPProvider: %v", err)
+ }
+ return p, srv
+}
+
+func TestHTTPProviderGenerateReadsDataEnvelope(t *testing.T) {
+ var gotPath, gotSource string
+ p, _ := newTestProvider(t, func(w http.ResponseWriter, r *http.Request) {
+ gotPath = r.URL.Path
+ gotSource = r.URL.Query().Get("source")
+ w.Header().Set("Content-Type", "application/json")
+ _, _ = w.Write([]byte(`{"data":{"scode":"ie2dSh0INb6YK9YQ",` +
+ `"auth_url":"https://work.weixin.qq.com/ai/qc/c?s=ie2dSh0INb6YK9YQ"}}`))
+ })
+
+ got, err := p.Generate(context.Background())
+ if err != nil {
+ t.Fatalf("Generate: %v", err)
+ }
+ if got.Scode != "ie2dSh0INb6YK9YQ" {
+ t.Errorf("Scode = %q", got.Scode)
+ }
+ if got.AuthURL != "https://work.weixin.qq.com/ai/qc/c?s=ie2dSh0INb6YK9YQ" {
+ t.Errorf("AuthURL = %q", got.AuthURL)
+ }
+ if gotPath != "/ai/qc/generate" {
+ t.Errorf("path = %q", gotPath)
+ }
+ if gotSource != "multica" {
+ t.Errorf("source = %q", gotSource)
+ }
+}
+
+func TestHTTPProviderGenerateRejectsEmptyEnvelope(t *testing.T) {
+ p, _ := newTestProvider(t, func(w http.ResponseWriter, _ *http.Request) {
+ _, _ = w.Write([]byte(`{"data":{}}`))
+ })
+
+ if _, err := p.Generate(context.Background()); err == nil {
+ t.Fatal("expected an error when data carries no scode / auth_url")
+ }
+}
+
+func TestHTTPProviderQueryResultReadsDataEnvelope(t *testing.T) {
+ var gotScode, gotSource string
+ p, _ := newTestProvider(t, func(w http.ResponseWriter, r *http.Request) {
+ gotScode = r.URL.Query().Get("scode")
+ gotSource = r.URL.Query().Get("source")
+ _, _ = w.Write([]byte(`{"data":{"status":"success",` +
+ `"bot_info":{"botid":"bot-1","secret":"sec-1"}}}`))
+ })
+
+ got, err := p.QueryResult(context.Background(), "sc-1")
+ if err != nil {
+ t.Fatalf("QueryResult: %v", err)
+ }
+ if got.Status != QueryStatusSuccess {
+ t.Errorf("Status = %q", got.Status)
+ }
+ if got.BotInfo == nil || got.BotInfo.BotID != "bot-1" || got.BotInfo.Secret != "sec-1" {
+ t.Errorf("BotInfo = %+v", got.BotInfo)
+ }
+ if gotScode != "sc-1" || gotSource != "multica" {
+ t.Errorf("scode = %q, source = %q", gotScode, gotSource)
+ }
+}
+
+func TestHTTPProviderQueryResultPendingInDataEnvelope(t *testing.T) {
+ p, _ := newTestProvider(t, func(w http.ResponseWriter, _ *http.Request) {
+ _, _ = w.Write([]byte(`{"data":{"status":"pending"}}`))
+ })
+
+ got, err := p.QueryResult(context.Background(), "sc-1")
+ if err != nil {
+ t.Fatalf("QueryResult: %v", err)
+ }
+ if got.Status != QueryStatusPending {
+ t.Errorf("Status = %q", got.Status)
+ }
+ if got.BotInfo != nil {
+ t.Errorf("BotInfo = %+v, want nil", got.BotInfo)
+ }
+}
+
+// A body without the envelope is named as such, so the next wire change is
+// diagnosable instead of arriving as "missing scode / auth_url".
+func TestHTTPProviderRejectsBodyWithoutDataObject(t *testing.T) {
+ p, _ := newTestProvider(t, func(w http.ResponseWriter, _ *http.Request) {
+ _, _ = w.Write([]byte(`{"scode":"sc-1","auth_url":"https://example.test/qr"}`))
+ })
+
+ _, err := p.Generate(context.Background())
+ if err == nil {
+ t.Fatal("expected an error when the body carries no data object")
+ }
+ if !strings.Contains(err.Error(), "no data object") {
+ t.Errorf("error = %q, want it to name the missing data object", err)
+ }
+}
+
+func TestHTTPProviderQueryResultSuccessWithoutBotInfo(t *testing.T) {
+ p, _ := newTestProvider(t, func(w http.ResponseWriter, _ *http.Request) {
+ _, _ = w.Write([]byte(`{"data":{"status":"success"}}`))
+ })
+
+ if _, err := p.QueryResult(context.Background(), "sc-1"); err == nil {
+ t.Fatal("expected an error when success carries no bot_info")
+ }
+}
+
+// The scode is a bearer credential: per install.go, whoever holds it can finish
+// creating the bot. It travels in the query string, and *url.Error.Error()
+// prints the URL it failed on — query string included. install_worker.go logs
+// these at Warn from inside the poll loop, so one sustained upstream hiccup
+// wrote a live, redeemable scode to the log over and over. Everything else
+// about this credential is careful: it is sealed at rest, NULLed on both
+// terminal paths, and never returned by any endpoint.
+func TestHTTPProviderTransportErrorsNeverCarryTheScode(t *testing.T) {
+ const scode = "SUPER-SECRET-SCODE-abc123"
+ // Accept the connection and hang up without answering: WeCom hiccuping, an
+ // LB dropping the connection, a DNS blip. net/http surfaces this as
+ // *url.Error{Op: "Get", URL: <full url>, Err: EOF}.
+ hangup := func(w http.ResponseWriter, _ *http.Request) {
+ conn, _, err := w.(http.Hijacker).Hijack()
+ if err != nil {
+ return
+ }
+ _ = conn.Close()
+ }
+
+ t.Run("query_result", func(t *testing.T) {
+ p, _ := newTestProvider(t, hangup)
+ _, err := p.QueryResult(context.Background(), scode)
+ if err == nil {
+ t.Fatal("expected a transport error")
+ }
+ if strings.Contains(err.Error(), scode) {
+ t.Errorf("error leaks the scode: %q", err)
+ }
+ if strings.Contains(err.Error(), "?") {
+ t.Errorf("error carries a query string, so the next credential put there leaks too: %q", err)
+ }
+ // Still has to be diagnosable: which call, against which endpoint, why.
+ if !strings.Contains(err.Error(), "/ai/qc/query_result") {
+ t.Errorf("error = %q, want it to name the endpoint that failed", err)
+ }
+ })
+
+ t.Run("generate", func(t *testing.T) {
+ p, _ := newTestProvider(t, hangup)
+ _, err := p.Generate(context.Background())
+ if err == nil {
+ t.Fatal("expected a transport error")
+ }
+ if strings.Contains(err.Error(), "?") {
+ t.Errorf("error carries a query string: %q", err)
+ }
+ if !strings.Contains(err.Error(), "/ai/qc/generate") {
+ t.Errorf("error = %q, want it to name the endpoint that failed", err)
+ }
+ })
+
+ // A timeout is the likelier trigger than a hangup — a wedged upstream, which
+ // is also the case that repeats every poll interval. net/http reports it as
+ // *url.Error too, so it must be scrubbed by the same path.
+ t.Run("upstream timeout", func(t *testing.T) {
+ srv := httptest.NewServer(http.HandlerFunc(func(_ http.ResponseWriter, r *http.Request) {
+ <-r.Context().Done() // hold until the client gives up
+ }))
+ t.Cleanup(srv.Close)
+ p, err := NewHTTPProvider(HTTPProviderConfig{
+ BaseURL: srv.URL,
+ SourceID: "multica",
+ HTTPClient: srv.Client(),
+ Timeout: 50 * time.Millisecond,
+ })
+ if err != nil {
+ t.Fatalf("NewHTTPProvider: %v", err)
+ }
+
+ _, err = p.QueryResult(context.Background(), scode)
+ if err == nil {
+ t.Fatal("expected a timeout error")
+ }
+ if strings.Contains(err.Error(), scode) {
+ t.Errorf("timeout error leaks the scode: %q", err)
+ }
+ })
+}
diff --git a/server/internal/integrations/wecom/install_test.go b/server/internal/integrations/wecom/install_test.go
new file mode 100644
index 0000000000..6e1b1ae80e
--- /dev/null
+++ b/server/internal/integrations/wecom/install_test.go
@@ -0,0 +1,990 @@
+package wecom
+
+// install_test.go — the scan-install contracts that hold without a live
+// Postgres: which begins are admitted, which are refused and why, and the
+// worker's creating → pending → success walk against a fake WeCom provider.
+//
+// The fakes are deliberately minimal. InstallStore is a broad interface, but the
+// decisions worth pinning touch a small slice of it.
+
+import (
+ "bytes"
+ "context"
+ "errors"
+ "fmt"
+ "log/slog"
+ "strings"
+ "sync/atomic"
+ "testing"
+ "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/util"
+ "github.com/multica-ai/multica/server/internal/util/secretbox"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+ "github.com/multica-ai/multica/server/pkg/protocol"
+)
+
+func testBox(t *testing.T) *secretbox.Box {
+ t.Helper()
+ key := make([]byte, secretbox.KeySize)
+ for i := range key {
+ key[i] = byte(i + 1)
+ }
+ box, err := secretbox.New(key)
+ if err != nil {
+ t.Fatalf("secretbox.New: %v", err)
+ }
+ return box
+}
+
+// installUUID returns a distinct, stable UUID per n. It does not take a
+// *testing.T because the fake store also needs it, outside any test scope.
+func installUUID(n int) pgtype.UUID {
+ u, err := util.ParseUUID(strings.Repeat("0", 7) + string(rune('0'+n)) + "-1111-1111-1111-111111111111")
+ if err != nil {
+ panic("install_test: bad fixture uuid: " + err.Error())
+ }
+ return u
+}
+
+// fakeInstallStore is an in-memory InstallStore.
+type fakeInstallStore struct {
+ sessions map[string]db.WecomInstallSession
+ byRequestHash map[string]db.WecomInstallSession
+ pendingByAgent map[string]db.WecomInstallSession
+ activeByAgent map[string]db.ChannelInstallation
+
+ // Sessions counted in the rate window, by workspace and by
+ // workspace|initiator.
+ windowTotal map[string]int64
+ windowUser map[string]int64
+
+ claimQueue []db.WecomInstallSession
+
+ created []db.CreateWecomInstallSessionParams
+ deferred []db.DeferClaimedWecomInstallSessionParams
+ completed []db.CompleteWecomInstallSessionParams
+ failed []db.FailWecomInstallSessionParams
+ // claimedWith is every lease token the worker claimed under, in order.
+ claimedWith []string
+
+ completeRows int64
+ // locked is every workspace a begin took the advisory lock on.
+ locked []pgtype.UUID
+}
+
+func newFakeInstallStore() *fakeInstallStore {
+ return &fakeInstallStore{
+ sessions: map[string]db.WecomInstallSession{},
+ byRequestHash: map[string]db.WecomInstallSession{},
+ pendingByAgent: map[string]db.WecomInstallSession{},
+ activeByAgent: map[string]db.ChannelInstallation{},
+ windowTotal: map[string]int64{},
+ windowUser: map[string]int64{},
+ completeRows: 1,
+ }
+}
+
+func requestKey(ws, initiator pgtype.UUID, hash string) string {
+ return util.UUIDToString(ws) + "|" + util.UUIDToString(initiator) + "|" + hash
+}
+
+func agentKey(ws, agent pgtype.UUID) string {
+ return util.UUIDToString(ws) + "|" + util.UUIDToString(agent)
+}
+
+func (f *fakeInstallStore) WithTx(pgx.Tx) InstallStore { return f }
+
+func (f *fakeInstallStore) LockWecomInstallBeginWorkspace(_ context.Context, workspaceID pgtype.UUID) error {
+ f.locked = append(f.locked, workspaceID)
+ return nil
+}
+
+func (f *fakeInstallStore) GetWecomInstallSessionByRequestHash(_ context.Context, arg db.GetWecomInstallSessionByRequestHashParams) (db.WecomInstallSession, error) {
+ if row, ok := f.byRequestHash[requestKey(arg.WorkspaceID, arg.InitiatorUserID, arg.RequestKeyHash)]; ok {
+ return row, nil
+ }
+ return db.WecomInstallSession{}, pgx.ErrNoRows
+}
+
+func (f *fakeInstallStore) GetPendingWecomInstallSessionByAgent(_ context.Context, arg db.GetPendingWecomInstallSessionByAgentParams) (db.WecomInstallSession, error) {
+ if row, ok := f.pendingByAgent[agentKey(arg.WorkspaceID, arg.AgentID)]; ok {
+ return row, nil
+ }
+ return db.WecomInstallSession{}, pgx.ErrNoRows
+}
+
+func (f *fakeInstallStore) CountWecomInstallSessionsInWindow(_ context.Context, arg db.CountWecomInstallSessionsInWindowParams) (db.CountWecomInstallSessionsInWindowRow, error) {
+ ws := util.UUIDToString(arg.WorkspaceID)
+ return db.CountWecomInstallSessionsInWindowRow{
+ Total: f.windowTotal[ws],
+ ByUser: f.windowUser[ws+"|"+util.UUIDToString(arg.InitiatorUserID)],
+ }, nil
+}
+
+func (f *fakeInstallStore) GetActiveWecomInstallationForAgent(_ context.Context, arg db.GetActiveWecomInstallationForAgentParams) (db.ChannelInstallation, error) {
+ if row, ok := f.activeByAgent[agentKey(arg.WorkspaceID, arg.AgentID)]; ok {
+ return row, nil
+ }
+ return db.ChannelInstallation{}, pgx.ErrNoRows
+}
+
+func (f *fakeInstallStore) CreateWecomInstallSession(_ context.Context, arg db.CreateWecomInstallSessionParams) (db.WecomInstallSession, error) {
+ f.created = append(f.created, arg)
+ row := db.WecomInstallSession{
+ ID: installUUID(9),
+ WorkspaceID: arg.WorkspaceID,
+ AgentID: arg.AgentID,
+ InitiatorUserID: arg.InitiatorUserID,
+ RequestKeyHash: arg.RequestKeyHash,
+ Status: InstallStatusCreating,
+ CreatedAt: pgtype.Timestamptz{Time: time.Now(), Valid: true},
+ }
+ f.sessions[util.UUIDToString(row.ID)] = row
+ return row, nil
+}
+
+func (f *fakeInstallStore) GetWecomInstallSession(_ context.Context, id pgtype.UUID) (db.WecomInstallSession, error) {
+ if row, ok := f.sessions[util.UUIDToString(id)]; ok {
+ return row, nil
+ }
+ return db.WecomInstallSession{}, pgx.ErrNoRows
+}
+
+func (f *fakeInstallStore) ClaimDueWecomInstallSession(_ context.Context, arg db.ClaimDueWecomInstallSessionParams) (db.WecomInstallSession, error) {
+ if len(f.claimQueue) == 0 {
+ return db.WecomInstallSession{}, pgx.ErrNoRows
+ }
+ // The worker mints the token, so a test cannot predict it; recording it is
+ // what lets one assert a later mutation carried the SAME lease.
+ f.claimedWith = append(f.claimedWith, arg.LeaseToken.String)
+ row := f.claimQueue[0]
+ f.claimQueue = f.claimQueue[1:]
+ return row, nil
+}
+
+func (f *fakeInstallStore) DeferClaimedWecomInstallSession(_ context.Context, arg db.DeferClaimedWecomInstallSessionParams) (int64, error) {
+ f.deferred = append(f.deferred, arg)
+ return 1, nil
+}
+
+func (f *fakeInstallStore) CompleteWecomInstallSession(_ context.Context, arg db.CompleteWecomInstallSessionParams) (int64, error) {
+ f.completed = append(f.completed, arg)
+ return f.completeRows, nil
+}
+
+func (f *fakeInstallStore) FailWecomInstallSession(_ context.Context, arg db.FailWecomInstallSessionParams) (int64, error) {
+ f.failed = append(f.failed, arg)
+ return 1, nil
+}
+
+func (f *fakeInstallStore) PurgeTerminalWecomInstallSessions(_ context.Context, arg db.PurgeTerminalWecomInstallSessionsParams) (int64, error) {
+ var n int64
+ for id, row := range f.sessions {
+ settled := (row.Status == InstallStatusSuccess || row.Status == InstallStatusError) &&
+ row.UpdatedAt.Time.Before(arg.TerminalCutoff.Time)
+ stale := row.Status == InstallStatusCreating && row.CreatedAt.Time.Before(arg.CreatingCutoff.Time)
+ if settled || stale {
+ delete(f.sessions, id)
+ n++
+ }
+ }
+ return n, nil
+}
+
+// noopTx satisfies pgx.Tx for the begin transaction; the fake store ignores it.
+type noopTx struct{ pgx.Tx }
+
+func (noopTx) Commit(context.Context) error { return nil }
+func (noopTx) Rollback(context.Context) error { return nil }
+
+type noopTxStarter struct{}
+
+func (noopTxStarter) Begin(context.Context) (pgx.Tx, error) { return noopTx{}, nil }
+
+// fakeProvider scripts the WeCom QR endpoints.
+type fakeProvider struct {
+ gen GenerateResult
+ genErr error
+ genCalls int
+ query QueryResult
+ queryErr error
+ queryCall int
+}
+
+func (p *fakeProvider) Generate(context.Context) (GenerateResult, error) {
+ p.genCalls++
+ return p.gen, p.genErr
+}
+
+// QueryResult answers only for the scode this provider issued, as WeCom would:
+// a worker that polled with the wrong scode would never see the scan.
+func (p *fakeProvider) QueryResult(_ context.Context, scode string) (QueryResult, error) {
+ p.queryCall++
+ if scode == "" || scode != p.gen.Scode {
+ return QueryResult{}, fmt.Errorf("fake provider: scode %q was never issued", scode)
+ }
+ return p.query, p.queryErr
+}
+
+// issuedScode is the generate result for tests that seal "secret-scode" onto a
+// pending session directly.
+var issuedScode = GenerateResult{Scode: "secret-scode", AuthURL: "https://example.test/qr"}
+
+// fakeBotBinder records the bind and can fail it.
+type fakeBotBinder struct {
+ calls []InstallationParams
+ inst Installation
+ err error
+}
+
+func (b *fakeBotBinder) Upsert(_ context.Context, p InstallationParams) (Installation, error) {
+ b.calls = append(b.calls, p)
+ if b.err != nil {
+ return Installation{}, b.err
+ }
+ return b.inst, nil
+}
+
+func newTestInstallService(t *testing.T, store InstallStore, provider Provider, binder BotBinder) *InstallService {
+ t.Helper()
+ return newInstallService(store, noopTxStarter{}, binder, InstallServiceConfig{
+ Provider: provider,
+ Box: testBox(t),
+ })
+}
+
+func beginParams(t *testing.T, key string) BeginInstallParams {
+ t.Helper()
+ return BeginInstallParams{
+ WorkspaceID: installUUID(1),
+ AgentID: installUUID(2),
+ InitiatorID: installUUID(3),
+ IdempotencyKey: key,
+ }
+}
+
+func TestBeginInstall_CreatesASession(t *testing.T) {
+ t.Parallel()
+ store := newFakeInstallStore()
+ svc := newTestInstallService(t, store, &fakeProvider{}, &fakeBotBinder{})
+
+ res, err := svc.BeginInstall(context.Background(), beginParams(t, "key-1"))
+ if err != nil {
+ t.Fatalf("BeginInstall: %v", err)
+ }
+ if res.SessionID == "" || res.Status != InstallStatusCreating {
+ t.Errorf("result = %+v, want a session id in creating", res)
+ }
+ if len(store.created) != 1 {
+ t.Fatalf("created %d sessions, want 1", len(store.created))
+ }
+ // The raw client key must never be stored; only its hash.
+ if store.created[0].RequestKeyHash == "key-1" {
+ t.Error("the raw idempotency key was persisted")
+ }
+ if store.created[0].RequestKeyHash != hashIdempotencyKey("key-1") {
+ t.Error("request_key_hash is not the hash of the client key")
+ } // The admission decision is serialized on the caller's workspace, not on
+ // some other key that would let two begins for it run side by side.
+ if len(store.locked) != 1 || store.locked[0] != installUUID(1) {
+ t.Errorf("begin locked %v, want exactly the begin's workspace", store.locked)
+ }
+}
+
+// A replayed request with the same key must return the SAME session, not spend a
+// second WeCom generate slot and show the admin a second QR.
+func TestBeginInstall_ReplayReturnsTheSameSession(t *testing.T) {
+ t.Parallel()
+ store := newFakeInstallStore()
+ svc := newTestInstallService(t, store, &fakeProvider{}, &fakeBotBinder{})
+ p := beginParams(t, "key-1")
+
+ existing := db.WecomInstallSession{
+ ID: installUUID(7),
+ WorkspaceID: p.WorkspaceID,
+ AgentID: p.AgentID,
+ InitiatorUserID: p.InitiatorID,
+ Status: InstallStatusPending,
+ }
+ store.byRequestHash[requestKey(p.WorkspaceID, p.InitiatorID, hashIdempotencyKey("key-1"))] = existing
+
+ res, err := svc.BeginInstall(context.Background(), p)
+ if err != nil {
+ t.Fatalf("BeginInstall: %v", err)
+ }
+ if res.SessionID != util.UUIDToString(existing.ID) {
+ t.Errorf("session id = %q, want the existing %q", res.SessionID, util.UUIDToString(existing.ID))
+ }
+ if len(store.created) != 0 {
+ t.Error("a replay must not create a second session")
+ }
+}
+
+// The same key pointed at a different agent is a hard conflict: an HTTP retry
+// must not silently move which agent gets the bot.
+func TestBeginInstall_ReplayAcrossAgentsIsAConflict(t *testing.T) {
+ t.Parallel()
+ store := newFakeInstallStore()
+ svc := newTestInstallService(t, store, &fakeProvider{}, &fakeBotBinder{})
+ p := beginParams(t, "key-1")
+
+ store.byRequestHash[requestKey(p.WorkspaceID, p.InitiatorID, hashIdempotencyKey("key-1"))] = db.WecomInstallSession{
+ ID: installUUID(7),
+ WorkspaceID: p.WorkspaceID,
+ AgentID: installUUID(8), // a different agent
+ InitiatorUserID: p.InitiatorID,
+ Status: InstallStatusPending,
+ }
+
+ if _, err := svc.BeginInstall(context.Background(), p); !errors.Is(err, ErrAgentMismatch) {
+ t.Errorf("err = %v, want ErrAgentMismatch", err)
+ }
+}
+
+func TestBeginInstall_ActiveInstallationIsAConflict(t *testing.T) {
+ t.Parallel()
+ store := newFakeInstallStore()
+ svc := newTestInstallService(t, store, &fakeProvider{}, &fakeBotBinder{})
+ p := beginParams(t, "key-1")
+ store.activeByAgent[agentKey(p.WorkspaceID, p.AgentID)] = db.ChannelInstallation{Status: "active"}
+
+ if _, err := svc.BeginInstall(context.Background(), p); !errors.Is(err, ErrActiveInstallationExists) {
+ t.Errorf("err = %v, want ErrActiveInstallationExists", err)
+ }
+ if len(store.created) != 0 {
+ t.Error("a conflicting begin must not create a session")
+ }
+}
+
+func TestBeginInstall_PendingSessionResumeRules(t *testing.T) {
+ t.Parallel()
+ pendingID := installUUID(7)
+
+ // Only workspace admins reach begin, and any of them may finish a scan a
+ // colleague started: the agent's slot is not left locked until it expires
+ // because whoever began it closed their laptop.
+ cases := []struct {
+ name string
+ initiator pgtype.UUID
+ }{
+ {"same initiator resumes", installUUID(3)},
+ {"another admin resumes someone else's", installUUID(4)},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ t.Parallel()
+ store := newFakeInstallStore()
+ svc := newTestInstallService(t, store, &fakeProvider{}, &fakeBotBinder{})
+ p := beginParams(t, "key-1")
+ p.InitiatorID = tc.initiator
+
+ store.pendingByAgent[agentKey(p.WorkspaceID, p.AgentID)] = db.WecomInstallSession{
+ ID: pendingID,
+ WorkspaceID: p.WorkspaceID,
+ AgentID: p.AgentID,
+ InitiatorUserID: installUUID(3),
+ Status: InstallStatusPending,
+ }
+
+ res, err := svc.BeginInstall(context.Background(), p)
+ if err != nil {
+ t.Fatalf("BeginInstall: %v", err)
+ }
+ if res.SessionID != util.UUIDToString(pendingID) {
+ t.Errorf("session id = %q, want the pending session", res.SessionID)
+ }
+ if len(store.created) != 0 {
+ t.Error("a resume must not create a second session")
+ }
+ })
+ }
+}
+
+func TestBeginInstall_RateLimits(t *testing.T) {
+ t.Parallel()
+ for _, tc := range []struct {
+ name string
+ ws string
+ total, user int64
+ wantLimited bool
+ }{
+ {"per-user cap", util.UUIDToString(installUUID(1)), 0, defaultRatePerUser, true},
+ {"per-workspace cap", util.UUIDToString(installUUID(1)), defaultRatePerWorkspace, 0, true},
+ // The quota is per workspace: another workspace's burst does not count.
+ {"another workspace's sessions", util.UUIDToString(installUUID(5)), defaultRatePerWorkspace, defaultRatePerUser, false},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ t.Parallel()
+ store := newFakeInstallStore()
+ store.windowTotal[tc.ws] = tc.total
+ store.windowUser[tc.ws+"|"+util.UUIDToString(installUUID(3))] = tc.user
+ svc := newTestInstallService(t, store, &fakeProvider{}, &fakeBotBinder{})
+
+ _, err := svc.BeginInstall(context.Background(), beginParams(t, "key-1"))
+ if limited := errors.Is(err, ErrRateLimited); limited != tc.wantLimited {
+ t.Errorf("err = %v, want rate limited = %v", err, tc.wantLimited)
+ }
+ })
+ }
+}
+
+func TestBeginInstall_RejectsBadIdempotencyKeys(t *testing.T) {
+ t.Parallel()
+ store := newFakeInstallStore()
+ svc := newTestInstallService(t, store, &fakeProvider{}, &fakeBotBinder{})
+
+ if _, err := svc.BeginInstall(context.Background(), beginParams(t, " ")); !errors.Is(err, ErrIdempotencyKeyRequired) {
+ t.Errorf("blank key err = %v, want ErrIdempotencyKeyRequired", err)
+ }
+ long := strings.Repeat("k", maxIdempotencyKeyLen+1)
+ if _, err := svc.BeginInstall(context.Background(), beginParams(t, long)); !errors.Is(err, ErrIdempotencyKeyTooLong) {
+ t.Errorf("long key err = %v, want ErrIdempotencyKeyTooLong", err)
+ }
+}
+
+// Without a provider or a box the scan flow cannot run, and begin must say so
+// rather than create a session no worker can drive.
+func TestBeginInstall_UnconfiguredIsRefused(t *testing.T) {
+ t.Parallel()
+ cases := map[string]*InstallService{
+ "no provider": newInstallService(newFakeInstallStore(), noopTxStarter{}, &fakeBotBinder{}, InstallServiceConfig{Box: testBox(t)}),
+ "no box": newInstallService(newFakeInstallStore(), noopTxStarter{}, &fakeBotBinder{}, InstallServiceConfig{Provider: &fakeProvider{}}),
+ "no binder": newInstallService(newFakeInstallStore(), noopTxStarter{}, nil, InstallServiceConfig{Provider: &fakeProvider{}, Box: testBox(t)}),
+ }
+ for name, svc := range cases {
+ t.Run(name, func(t *testing.T) {
+ t.Parallel()
+ if svc.Configured() {
+ t.Fatal("Configured() must be false")
+ }
+ if _, err := svc.BeginInstall(context.Background(), beginParams(t, "key-1")); !errors.Is(err, ErrInstallNotConfigured) {
+ t.Errorf("err = %v, want ErrInstallNotConfigured", err)
+ }
+ })
+ }
+}
+
+func TestGetSession_DecryptsQROnlyWhenAsked(t *testing.T) {
+ t.Parallel()
+ store := newFakeInstallStore()
+ box := testBox(t)
+ svc := newInstallService(store, noopTxStarter{}, &fakeBotBinder{}, InstallServiceConfig{
+ Provider: &fakeProvider{}, Box: box,
+ })
+
+ const qr = "https://work.weixin.qq.com/ai/qc/scan?scode=secret-scode"
+ enc, err := sealAndEncode(box, []byte(qr))
+ if err != nil {
+ t.Fatalf("sealAndEncode: %v", err)
+ }
+ id := installUUID(7)
+ ws := installUUID(1)
+ store.sessions[util.UUIDToString(id)] = db.WecomInstallSession{
+ ID: id,
+ WorkspaceID: ws,
+ AgentID: installUUID(2),
+ InitiatorUserID: installUUID(3),
+ Status: InstallStatusPending,
+ QrCodeUrlEncrypted: pgtype.Text{String: enc, Valid: true},
+ }
+
+ withoutQR, err := svc.GetSession(context.Background(), ws, id, false)
+ if err != nil {
+ t.Fatalf("GetSession: %v", err)
+ }
+ if withoutQR.QRCodeURL != "" {
+ t.Error("decryptQR=false must not return the QR URL")
+ }
+ withQR, err := svc.GetSession(context.Background(), ws, id, true)
+ if err != nil {
+ t.Fatalf("GetSession: %v", err)
+ }
+ if withQR.QRCodeURL != qr {
+ t.Errorf("QRCodeURL = %q, want the decrypted URL", withQR.QRCodeURL)
+ }
+}
+
+// A session id from another workspace must read as not-found, so an id cannot be
+// used to enumerate across tenants.
+func TestGetSession_CrossWorkspaceIsNotFound(t *testing.T) {
+ t.Parallel()
+ store := newFakeInstallStore()
+ svc := newTestInstallService(t, store, &fakeProvider{}, &fakeBotBinder{})
+ id := installUUID(7)
+ store.sessions[util.UUIDToString(id)] = db.WecomInstallSession{
+ ID: id,
+ WorkspaceID: installUUID(1),
+ Status: InstallStatusPending,
+ }
+
+ if _, err := svc.GetSession(context.Background(), installUUID(5), id, false); !errors.Is(err, ErrSessionNotFound) {
+ t.Errorf("err = %v, want ErrSessionNotFound", err)
+ }
+ if _, err := svc.GetSession(context.Background(), installUUID(1), installUUID(6), false); !errors.Is(err, ErrSessionNotFound) {
+ t.Errorf("unknown id err = %v, want ErrSessionNotFound", err)
+ }
+}
+
+func newTestWorker(t *testing.T, svc *InstallService) *InstallWorker {
+ t.Helper()
+ return NewInstallWorker(svc, InstallWorkerConfig{})
+}
+
+// countingNotifier stands in for the channel supervisor.
+type countingNotifier struct{ n atomic.Int32 }
+
+func (c *countingNotifier) Notify() { c.n.Add(1) }
+
+// createdEvents counts installation-created events published on bus.
+func createdEvents(bus *events.Bus) *[]events.Event {
+ var got []events.Event
+ bus.Subscribe(protocol.EventWecomInstallationCreated, func(e events.Event) { got = append(got, e) })
+ return &got
+}
+
+// creating → pending: the worker fetches the QR, seals it, and schedules the
+// next poll. The plaintext scode and QR URL must not reach the row.
+func TestInstallWorker_CreatingFetchesAndSealsTheQR(t *testing.T) {
+ t.Parallel()
+ store := newFakeInstallStore()
+ box := testBox(t)
+ provider := &fakeProvider{gen: GenerateResult{
+ Scode: "secret-scode",
+ AuthURL: "https://work.weixin.qq.com/ai/qc/scan?scode=secret-scode",
+ }}
+ svc := newInstallService(store, noopTxStarter{}, &fakeBotBinder{}, InstallServiceConfig{
+ Provider: provider, Box: box,
+ })
+ w := newTestWorker(t, svc)
+
+ store.claimQueue = []db.WecomInstallSession{{
+ ID: installUUID(7),
+ WorkspaceID: installUUID(1),
+ AgentID: installUUID(2),
+ Status: InstallStatusCreating,
+ CreatedAt: pgtype.Timestamptz{Time: time.Now(), Valid: true},
+ }}
+
+ worked, err := w.processOne(context.Background())
+ if err != nil {
+ t.Fatalf("processOne: %v", err)
+ }
+ if !worked {
+ t.Error("processOne reported no work despite a claimed row")
+ }
+ if provider.genCalls != 1 {
+ t.Errorf("Generate calls = %d, want 1", provider.genCalls)
+ }
+ if len(store.deferred) != 1 {
+ t.Fatalf("deferred %d times, want 1", len(store.deferred))
+ }
+ d := store.deferred[0]
+ if d.Status != InstallStatusPending {
+ t.Errorf("status = %q, want pending", d.Status)
+ }
+ if !d.ExpiresAt.Valid || !d.ExpiresAt.Time.After(time.Now()) {
+ t.Error("pending must carry a future expires_at")
+ }
+ // Both columns are ciphertext: together they let anyone finish creating the
+ // bot, so the plaintext must not be readable off the row.
+ for name, col := range map[string]pgtype.Text{"scode": d.ScodeEncrypted, "qr_code_url": d.QrCodeUrlEncrypted} {
+ if !col.Valid || col.String == "" {
+ t.Fatalf("%s was not written", name)
+ }
+ if strings.Contains(col.String, "secret-scode") {
+ t.Errorf("%s stored plaintext", name)
+ }
+ }
+ if plain, err := decodeAndOpen(box, d.QrCodeUrlEncrypted.String); err != nil || !strings.Contains(string(plain), "secret-scode") {
+ t.Errorf("sealed qr_code_url did not round-trip: %v", err)
+ }
+}
+
+// A generate failure retries rather than terminating: the deadline guard, not the
+// first error, is what ends the session.
+func TestInstallWorker_GenerateFailureRetriesUntilTheDeadline(t *testing.T) {
+ t.Parallel()
+ store := newFakeInstallStore()
+ svc := newInstallService(store, noopTxStarter{}, &fakeBotBinder{}, InstallServiceConfig{
+ Provider: &fakeProvider{genErr: errors.New("wecom down")}, Box: testBox(t),
+ })
+ w := newTestWorker(t, svc)
+
+ store.claimQueue = []db.WecomInstallSession{{
+ ID: installUUID(7),
+ WorkspaceID: installUUID(1),
+ Status: InstallStatusCreating,
+ CreatedAt: pgtype.Timestamptz{Time: time.Now(), Valid: true},
+ }}
+ if _, err := w.processOne(context.Background()); err != nil {
+ t.Fatalf("processOne: %v", err)
+ }
+ if len(store.failed) != 0 {
+ t.Error("a single generate failure must not terminate the session")
+ }
+ if len(store.deferred) != 1 || store.deferred[0].Status != InstallStatusCreating {
+ t.Error("a generate failure must defer, still in creating")
+ }
+
+ // Past the deadline, the same failure is terminal.
+ store.deferred = nil
+ store.claimQueue = []db.WecomInstallSession{{
+ ID: installUUID(7),
+ WorkspaceID: installUUID(1),
+ Status: InstallStatusCreating,
+ CreatedAt: pgtype.Timestamptz{Time: time.Now().Add(-2 * defaultGenerateDeadline), Valid: true},
+ }}
+ if _, err := w.processOne(context.Background()); err != nil {
+ t.Fatalf("processOne: %v", err)
+ }
+ if len(store.failed) != 1 || store.failed[0].ErrorReason.String != InstallErrorGenerateFailed {
+ t.Errorf("failed = %+v, want one generate_failed", store.failed)
+ }
+}
+
+// pending + success: the bot is bound through BotBinder and the session settles.
+func TestInstallWorker_SuccessBindsTheBotAndCompletes(t *testing.T) {
+ t.Parallel()
+ store := newFakeInstallStore()
+ box := testBox(t)
+ scodeEnc, err := sealAndEncode(box, []byte("secret-scode"))
+ if err != nil {
+ t.Fatalf("sealAndEncode: %v", err)
+ }
+ binder := &fakeBotBinder{inst: Installation{ID: installUUID(8)}}
+ svc := newInstallService(store, noopTxStarter{}, binder, InstallServiceConfig{
+ Provider: &fakeProvider{gen: issuedScode, query: QueryResult{
+ Status: QueryStatusSuccess,
+ BotInfo: &BotInfo{BotID: "bot-1", Secret: "sekrit"},
+ }},
+ Box: box,
+ })
+ bus, sup := events.New(), &countingNotifier{}
+ published := createdEvents(bus)
+ w := NewInstallWorker(svc, InstallWorkerConfig{Bus: bus, Supervisor: sup})
+
+ store.claimQueue = []db.WecomInstallSession{{
+ ID: installUUID(7),
+ WorkspaceID: installUUID(1),
+ AgentID: installUUID(2),
+ InitiatorUserID: installUUID(3),
+ Status: InstallStatusPending,
+ ScodeEncrypted: pgtype.Text{String: scodeEnc, Valid: true},
+ ExpiresAt: pgtype.Timestamptz{Time: time.Now().Add(time.Minute), Valid: true},
+ }}
+
+ if _, err := w.processOne(context.Background()); err != nil {
+ t.Fatalf("processOne: %v", err)
+ }
+ if len(binder.calls) != 1 {
+ t.Fatalf("bind calls = %d, want 1", len(binder.calls))
+ }
+ bind := binder.calls[0]
+ if bind.BotID != "bot-1" || bind.Secret != "sekrit" {
+ t.Errorf("bind params = %+v, want the credentials WeCom returned", bind)
+ }
+ // The installer is the person who started the session, not whoever polled.
+ if bind.InstallerUserID != installUUID(3) {
+ t.Error("bind must attribute the install to the session initiator")
+ }
+ if len(store.completed) != 1 || store.completed[0].InstallationID != installUUID(8) {
+ t.Errorf("completed = %+v, want the bound installation id", store.completed)
+ }
+ if len(store.failed) != 0 {
+ t.Error("a successful bind must not fail the session")
+ }
+ // The open settings page learns of the bot, and its connection comes up now
+ // rather than on the supervisor's next sweep.
+ if len(*published) != 1 || (*published)[0].Payload.(map[string]any)["installation_id"] != util.UUIDToString(installUUID(8)) {
+ t.Errorf("installation-created events = %+v, want one for the bound installation", *published)
+ }
+ if got := sup.n.Load(); got != 1 {
+ t.Errorf("supervisor nudged %d times, want 1", got)
+ }
+}
+
+// A failed bind is terminal: the bot exists on WeCom's side either way, so
+// retrying into the same failure helps nobody. Only a bot whose routing slot is
+// held elsewhere is a conflict; a probe or database failure is a bot that was
+// created and could not be connected, and the dialog says so.
+//
+// REVERSE VERIFICATION: report every bind failure as installation_conflict
+// again, and the probe, network and database cases fail.
+func TestInstallWorker_BindFailureReasons(t *testing.T) {
+ t.Parallel()
+ for _, tc := range []struct {
+ name string
+ err error
+ want string
+ }{
+ {"bot held in this workspace", ErrBotOwnedBySameWorkspace, InstallErrorInstallationConflict},
+ {"bot held by an archived agent", ErrBotOwnedByArchivedAgent, InstallErrorInstallationConflict},
+ {"bot held in another workspace", ErrBotOwnedByAnotherWorkspace, InstallErrorInstallationConflict},
+ {"conflict wrapped", fmt.Errorf("bind: %w", ErrBotOwnedBySameWorkspace), InstallErrorInstallationConflict},
+ {"credential probe timed out", fmt.Errorf("wecom: credential probe: %w", context.DeadlineExceeded), InstallErrorBindFailed},
+ {"network down", errors.New("wecom: credential probe: dial tcp: lookup openws.work.weixin.qq.com: no such host"), InstallErrorBindFailed},
+ {"database down", errors.New("wecom: lock bot routing slot: dial tcp 10.0.0.5:5432: connect: connection refused"), InstallErrorBindFailed},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ t.Parallel()
+ store := newFakeInstallStore()
+ box := testBox(t)
+ scodeEnc, _ := sealAndEncode(box, []byte("secret-scode"))
+ svc := newInstallService(store, noopTxStarter{}, &fakeBotBinder{err: tc.err}, InstallServiceConfig{
+ Provider: &fakeProvider{gen: issuedScode, query: QueryResult{
+ Status: QueryStatusSuccess,
+ BotInfo: &BotInfo{BotID: "bot-1", Secret: "sekrit"},
+ }},
+ Box: box,
+ })
+ w := newTestWorker(t, svc)
+
+ store.claimQueue = []db.WecomInstallSession{{
+ ID: installUUID(7),
+ WorkspaceID: installUUID(1),
+ Status: InstallStatusPending,
+ ScodeEncrypted: pgtype.Text{String: scodeEnc, Valid: true},
+ ExpiresAt: pgtype.Timestamptz{Time: time.Now().Add(time.Minute), Valid: true},
+ }}
+
+ if _, err := w.processOne(context.Background()); err != nil {
+ t.Fatalf("processOne: %v", err)
+ }
+ if len(store.failed) != 1 || store.failed[0].ErrorReason.String != tc.want {
+ t.Errorf("failed = %+v, want one %s", store.failed, tc.want)
+ }
+ if len(store.completed) != 0 {
+ t.Error("a failed bind must not complete the session")
+ }
+ })
+ }
+}
+
+// A success WeCom reports without credentials is a protocol error, not a bind.
+func TestInstallWorker_SuccessWithoutCredentialsIsAProtocolError(t *testing.T) {
+ t.Parallel()
+ store := newFakeInstallStore()
+ box := testBox(t)
+ scodeEnc, _ := sealAndEncode(box, []byte("secret-scode"))
+ binder := &fakeBotBinder{}
+ svc := newInstallService(store, noopTxStarter{}, binder, InstallServiceConfig{
+ Provider: &fakeProvider{gen: issuedScode, query: QueryResult{Status: QueryStatusSuccess}},
+ Box: box,
+ })
+ w := newTestWorker(t, svc)
+
+ store.claimQueue = []db.WecomInstallSession{{
+ ID: installUUID(7),
+ WorkspaceID: installUUID(1),
+ Status: InstallStatusPending,
+ ScodeEncrypted: pgtype.Text{String: scodeEnc, Valid: true},
+ ExpiresAt: pgtype.Timestamptz{Time: time.Now().Add(time.Minute), Valid: true},
+ }}
+
+ if _, err := w.processOne(context.Background()); err != nil {
+ t.Fatalf("processOne: %v", err)
+ }
+ if len(binder.calls) != 0 {
+ t.Error("no credentials means nothing to bind")
+ }
+ if len(store.failed) != 1 || store.failed[0].ErrorReason.String != InstallErrorWecomProtocolError {
+ t.Errorf("failed = %+v, want one wecom_protocol_error", store.failed)
+ }
+}
+
+// An expired QR terminates rather than polling a scode WeCom will never accept.
+func TestInstallWorker_ExpiredSessionTerminates(t *testing.T) {
+ t.Parallel()
+ store := newFakeInstallStore()
+ box := testBox(t)
+ scodeEnc, _ := sealAndEncode(box, []byte("secret-scode"))
+ provider := &fakeProvider{gen: issuedScode, query: QueryResult{Status: QueryStatusPending}}
+ svc := newInstallService(store, noopTxStarter{}, &fakeBotBinder{}, InstallServiceConfig{
+ Provider: provider, Box: box,
+ })
+ w := newTestWorker(t, svc)
+
+ store.claimQueue = []db.WecomInstallSession{{
+ ID: installUUID(7),
+ WorkspaceID: installUUID(1),
+ Status: InstallStatusPending,
+ ScodeEncrypted: pgtype.Text{String: scodeEnc, Valid: true},
+ ExpiresAt: pgtype.Timestamptz{Time: time.Now().Add(-time.Second), Valid: true},
+ }}
+
+ if _, err := w.processOne(context.Background()); err != nil {
+ t.Fatalf("processOne: %v", err)
+ }
+ if provider.queryCall != 0 {
+ t.Error("an expired session must not be polled upstream")
+ }
+ if len(store.failed) != 1 || store.failed[0].ErrorReason.String != InstallErrorExpired {
+ t.Errorf("failed = %+v, want one expired", store.failed)
+ }
+}
+
+// Maintenance mode: with the integration unconfigured, a claimed session must
+// still terminate so the admin's dialog shows an error instead of spinning.
+func TestInstallWorker_MaintenanceModeTerminatesSessions(t *testing.T) {
+ t.Parallel()
+ store := newFakeInstallStore()
+ // No provider: Configured() is false.
+ svc := newInstallService(store, noopTxStarter{}, &fakeBotBinder{}, InstallServiceConfig{
+ Box: testBox(t),
+ })
+ w := newTestWorker(t, svc)
+
+ store.claimQueue = []db.WecomInstallSession{{
+ ID: installUUID(7),
+ WorkspaceID: installUUID(1),
+ Status: InstallStatusCreating,
+ CreatedAt: pgtype.Timestamptz{Time: time.Now(), Valid: true},
+ }}
+ if _, err := w.processOne(context.Background()); err != nil {
+ t.Fatalf("processOne: %v", err)
+ }
+ if len(store.failed) != 1 || store.failed[0].ErrorReason.String != InstallErrorIntegrationUnconfigured {
+ t.Errorf("failed = %+v, want one integration_unconfigured", store.failed)
+ }
+}
+
+// Losing the lease mid-finalize must not complete the session: another worker
+// owns it. The bind is idempotent, so nothing is left over.
+func TestInstallWorker_LostLeaseDoesNotComplete(t *testing.T) {
+ t.Parallel()
+ store := newFakeInstallStore()
+ store.completeRows = 0 // the lease-token predicate matched no row
+ box := testBox(t)
+ scodeEnc, _ := sealAndEncode(box, []byte("secret-scode"))
+ binder := &fakeBotBinder{inst: Installation{ID: installUUID(8)}}
+ svc := newInstallService(store, noopTxStarter{}, binder, InstallServiceConfig{
+ Provider: &fakeProvider{gen: issuedScode, query: QueryResult{
+ Status: QueryStatusSuccess,
+ BotInfo: &BotInfo{BotID: "bot-1", Secret: "sekrit"},
+ }},
+ Box: box,
+ })
+ bus, sup := events.New(), &countingNotifier{}
+ published := createdEvents(bus)
+ w := NewInstallWorker(svc, InstallWorkerConfig{Bus: bus, Supervisor: sup})
+
+ store.claimQueue = []db.WecomInstallSession{{
+ ID: installUUID(7),
+ WorkspaceID: installUUID(1),
+ Status: InstallStatusPending,
+ ScodeEncrypted: pgtype.Text{String: scodeEnc, Valid: true},
+ ExpiresAt: pgtype.Timestamptz{Time: time.Now().Add(time.Minute), Valid: true},
+ }}
+
+ if _, err := w.processOne(context.Background()); err != nil {
+ t.Fatalf("processOne: %v", err)
+ }
+ if len(store.failed) != 0 {
+ t.Error("losing the lease is not a failure of the session")
+ }
+ // The worker that now owns the session announces it when it completes;
+ // this one announcing too would show the admin the bot twice.
+ if len(*published) != 0 || sup.n.Load() != 0 {
+ t.Errorf("a completion that matched no row still announced the install: events=%d nudges=%d", len(*published), sup.n.Load())
+ }
+}
+
+func TestInstallWorker_EmptyQueueReportsNoWork(t *testing.T) {
+ t.Parallel()
+ store := newFakeInstallStore()
+ svc := newTestInstallService(t, store, &fakeProvider{}, &fakeBotBinder{})
+ worked, err := newTestWorker(t, svc).processOne(context.Background())
+ if err != nil {
+ t.Fatalf("processOne: %v", err)
+ }
+ if worked {
+ t.Error("an empty queue must report no work")
+ }
+}
+
+// Every mutation in this worker matches on the current lease token — the
+// invariant stated at the top of install_worker.go, which is what keeps a stale
+// replica from clobbering a new owner. FailWecomInstallSession was the one that
+// did not, so a worker whose lease had already expired could mark a session
+// error out from under the replica that was mid-way through creating the bot.
+func TestInstallWorker_FailingASessionCarriesTheLease(t *testing.T) {
+ store := newFakeInstallStore()
+ // An unconfigured service: processOne claims, then fails the row in
+ // maintenance mode. That is the shortest path to a failSession, and it is
+ // also the one call site outside handleCreating / handlePending — so it
+ // proves the lease reaches every one of them.
+ svc := newInstallService(store, noopTxStarter{}, &fakeBotBinder{}, InstallServiceConfig{
+ Box: testBox(t),
+ })
+ w := newTestWorker(t, svc)
+ store.claimQueue = []db.WecomInstallSession{{
+ ID: mustTestUUID(t),
+ Status: InstallStatusCreating,
+ }}
+
+ if _, err := w.processOne(context.Background()); err != nil {
+ t.Fatalf("processOne: %v", err)
+ }
+
+ if len(store.failed) != 1 {
+ t.Fatalf("failed %d sessions, want 1", len(store.failed))
+ }
+ if len(store.claimedWith) != 1 {
+ t.Fatalf("claimed %d times, want 1", len(store.claimedWith))
+ }
+ got := store.failed[0].LeaseToken
+ if !got.Valid || got.String == "" {
+ t.Fatal("the terminal failure carried no lease token, so a stale worker could clobber a new owner")
+ }
+ if got.String != store.claimedWith[0] {
+ t.Errorf("failed under lease %q, want the one it claimed with (%q)", got.String, store.claimedWith[0])
+ }
+}
+
+// The service is built before the worker that consumes its wake-ups, so the
+// worker's constructor is what points a begin at it. A begin that does not wake
+// the worker leaves the admin watching "preparing" for a full poll tick.
+func TestNewInstallWorker_BeginWakesTheWorker(t *testing.T) {
+ t.Parallel()
+ svc := newTestInstallService(t, newFakeInstallStore(), &fakeProvider{}, &fakeBotBinder{})
+ w := NewInstallWorker(svc, InstallWorkerConfig{Bus: events.New(), Supervisor: &countingNotifier{}})
+
+ if _, err := svc.BeginInstall(context.Background(), beginParams(t, "wake")); err != nil {
+ t.Fatalf("BeginInstall: %v", err)
+ }
+ select {
+ case <-w.wake:
+ default:
+ t.Fatal("a begin did not wake the worker built on its service")
+ }
+}
+
+// Both of the worker's collaborators are optional and fail silently when
+// missing, so the constructor says so: a settings page that never shows the new
+// bot, and a bot that connects a sweep late, have no other symptom.
+func TestNewInstallWorker_WarnsAboutMissingCollaborators(t *testing.T) {
+ t.Parallel()
+ build := func(cfg InstallWorkerConfig) string {
+ var logged bytes.Buffer
+ svc := newInstallService(newFakeInstallStore(), noopTxStarter{}, &fakeBotBinder{}, InstallServiceConfig{
+ Logger: slog.New(slog.NewTextHandler(&logged, nil)),
+ })
+ NewInstallWorker(svc, cfg)
+ return logged.String()
+ }
+
+ if got := build(InstallWorkerConfig{Bus: events.New(), Supervisor: &countingNotifier{}}); got != "" {
+ t.Errorf("fully wired worker logged:\n%s", got)
+ }
+ got := build(InstallWorkerConfig{})
+ for _, want := range []string{"no event bus wired", "no channel supervisor wired"} {
+ if !strings.Contains(got, want) {
+ t.Errorf("worker built without its collaborators did not warn %q; log:\n%s", want, got)
+ }
+ }
+}
diff --git a/server/internal/integrations/wecom/install_worker.go b/server/internal/integrations/wecom/install_worker.go
new file mode 100644
index 0000000000..c3a7c92995
--- /dev/null
+++ b/server/internal/integrations/wecom/install_worker.go
@@ -0,0 +1,427 @@
+package wecom
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "strings"
+ "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/util"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+ "github.com/multica-ai/multica/server/pkg/protocol"
+)
+
+// InstallWorker drives the install state machine independently of any HTTP
+// request. It is always constructed. When the service is not fully wired
+// (missing secret key / source id / provider) it runs in maintenance mode:
+// existing creating/pending rows are marked error/integration_unconfigured
+// so no session hangs forever, GC still runs, but no upstream WeCom call
+// is issued.
+//
+// The worker is safe to run across replicas — every mutation matches on
+// the current lease token so a stale worker cannot clobber a new owner.
+type InstallWorker struct {
+ svc *InstallService
+ supervisor Notifier
+ bus *events.Bus
+ pollInterval time.Duration
+ purgeInterval time.Duration
+ wake chan struct{}
+}
+
+// Notifier is the narrow surface the worker needs on engine.Supervisor —
+// exactly Supervisor.Notify. Kept as an interface so tests don't need to
+// spin up a real Supervisor.
+type Notifier interface {
+ Notify()
+}
+
+// InstallWorkerConfig configures the worker. Zero intervals take defaults.
+type InstallWorkerConfig struct {
+ PollInterval time.Duration
+ PurgeInterval time.Duration
+ // Bus carries the installation-created event to the settings page. Nil
+ // means an open settings tab does not see a scanned bot until it refetches.
+ Bus *events.Bus
+ // Supervisor is nudged when a bot lands. Nil means the bot's connection
+ // waits for the supervisor's next scheduled sweep.
+ Supervisor Notifier
+}
+
+// NewInstallWorker binds the worker to a service, and points the service's
+// begin wake-up at this worker. Both maintenance mode (svc.Configured() ==
+// false) and fully-wired mode use the same worker; the service's Configured
+// flag gates upstream calls.
+func NewInstallWorker(svc *InstallService, cfg InstallWorkerConfig) *InstallWorker {
+ if cfg.PollInterval == 0 {
+ cfg.PollInterval = time.Second
+ }
+ if cfg.PurgeInterval == 0 {
+ cfg.PurgeInterval = time.Minute
+ }
+ w := &InstallWorker{
+ svc: svc,
+ supervisor: cfg.Supervisor,
+ bus: cfg.Bus,
+ pollInterval: cfg.PollInterval,
+ purgeInterval: cfg.PurgeInterval,
+ wake: make(chan struct{}, 1),
+ }
+ if svc != nil {
+ svc.notify = w.Notify
+ if cfg.Bus == nil {
+ svc.cfg.Logger.Warn("wecom install worker: no event bus wired; a scanned bot will not appear on an open settings page until it reloads")
+ }
+ if cfg.Supervisor == nil {
+ svc.cfg.Logger.Warn("wecom install worker: no channel supervisor wired; a scanned bot connects only on the supervisor's next sweep")
+ }
+ }
+ return w
+}
+
+// Notify wakes the worker for an immediate sweep. Safe to call any time —
+// a pending wake coalesces.
+func (w *InstallWorker) Notify() {
+ if w == nil {
+ return
+ }
+ select {
+ case w.wake <- struct{}{}:
+ default:
+ }
+}
+
+// Run is the worker's main loop. Cancelling ctx stops it after the current
+// iteration. Shutdown does not wait for it: a session interrupted mid-step keeps
+// its lease until the lease expires, and then any replica claims it again.
+func (w *InstallWorker) Run(ctx context.Context) {
+ if w == nil {
+ return
+ }
+ if w.svc == nil {
+ return
+ }
+ pollT := time.NewTicker(w.pollInterval)
+ defer pollT.Stop()
+ purgeT := time.NewTicker(w.purgeInterval)
+ defer purgeT.Stop()
+
+ // Immediately drain on start.
+ w.drain(ctx)
+
+ for {
+ select {
+ case <-ctx.Done():
+ return
+ case <-purgeT.C:
+ if err := w.purge(ctx); err != nil && !errors.Is(err, context.Canceled) {
+ w.svc.cfg.Logger.Warn("wecom install worker: purge", "error", err)
+ }
+ case <-pollT.C:
+ w.drain(ctx)
+ case <-w.wake:
+ w.drain(ctx)
+ }
+ }
+}
+
+// drain processes as many due rows as it can find, one at a time. Empty
+// result stops the loop until the next tick / wake.
+func (w *InstallWorker) drain(ctx context.Context) {
+ for {
+ worked, err := w.processOne(ctx)
+ if err != nil && !errors.Is(err, context.Canceled) {
+ w.svc.cfg.Logger.Warn("wecom install worker: process", "error", err)
+ return
+ }
+ if !worked {
+ return
+ }
+ }
+}
+
+// processOne claims one due row and progresses it. Returns worked=true when
+// a claim happened (successful or not); false when there was nothing to do.
+func (w *InstallWorker) processOne(ctx context.Context) (bool, error) {
+ leaseToken, err := mintLeaseToken()
+ if err != nil {
+ return false, fmt.Errorf("mint lease token: %w", err)
+ }
+ leaseExpires := w.svc.cfg.Now().Add(w.svc.cfg.LeaseTTL)
+ row, err := w.svc.store.ClaimDueWecomInstallSession(ctx, db.ClaimDueWecomInstallSessionParams{
+ LeaseToken: pgtype.Text{String: leaseToken, Valid: true},
+ LeaseExpiresAt: pgtype.Timestamptz{Time: leaseExpires, Valid: true},
+ })
+ if err != nil {
+ if errors.Is(err, pgx.ErrNoRows) {
+ return false, nil
+ }
+ return false, fmt.Errorf("claim due session: %w", err)
+ }
+ // Maintenance mode: the whole integration is unconfigured. Mark the
+ // row terminal so the frontend gets a clean error rather than a
+ // forever-creating dialog, and clear the ciphertext columns.
+ if !w.svc.Configured() {
+ w.failSession(ctx, row.ID, leaseToken, InstallErrorIntegrationUnconfigured,
+ "WeCom install is not enabled on this server")
+ return true, nil
+ }
+ switch row.Status {
+ case InstallStatusCreating:
+ return true, w.handleCreating(ctx, row, leaseToken)
+ case InstallStatusPending:
+ return true, w.handlePending(ctx, row, leaseToken)
+ default:
+ return true, nil
+ }
+}
+
+func (w *InstallWorker) handleCreating(ctx context.Context, row db.WecomInstallSession, leaseToken string) error {
+ // Deadline guard: if the row has sat in creating past GenerateDeadline
+ // without a QR, give up.
+ now := w.svc.cfg.Now()
+ if row.CreatedAt.Valid && now.Sub(row.CreatedAt.Time) > w.svc.cfg.GenerateDeadline {
+ w.failSession(ctx, row.ID, leaseToken, InstallErrorGenerateFailed,
+ "Failed to generate WeCom QR code in time")
+ return nil
+ }
+ upstreamCtx, cancel := context.WithTimeout(ctx, w.svc.cfg.UpstreamTimeout)
+ defer cancel()
+ gen, err := w.svc.cfg.Provider.Generate(upstreamCtx)
+ if err != nil {
+ w.svc.cfg.Logger.Warn("wecom install: generate failed",
+ "session_id", util.UUIDToString(row.ID), "err", err)
+ // Retry until the deadline: defer with a short poll_after so the
+ // next tick tries again. On the next attempt the deadline guard
+ // above will terminate the session if we've run out of time.
+ nextPoll := now.Add(w.svc.cfg.CreatingPollInterval)
+ _, err := w.svc.store.DeferClaimedWecomInstallSession(ctx, db.DeferClaimedWecomInstallSessionParams{
+ ID: row.ID,
+ LeaseToken: pgtype.Text{String: leaseToken, Valid: true},
+ PollAfter: pgtype.Timestamptz{Time: nextPoll, Valid: true},
+ Status: InstallStatusCreating,
+ })
+ return err
+ }
+ scodeEnc, err := sealAndEncode(w.svc.cfg.Box, []byte(gen.Scode))
+ if err != nil {
+ return fmt.Errorf("seal scode: %w", err)
+ }
+ urlEnc, err := sealAndEncode(w.svc.cfg.Box, []byte(gen.AuthURL))
+ if err != nil {
+ return fmt.Errorf("seal auth_url: %w", err)
+ }
+ expires := now.Add(w.svc.cfg.QRTTL)
+ nextPoll := now.Add(w.svc.cfg.PendingPollInterval)
+ if _, err := w.svc.store.DeferClaimedWecomInstallSession(ctx, db.DeferClaimedWecomInstallSessionParams{
+ ID: row.ID,
+ LeaseToken: pgtype.Text{String: leaseToken, Valid: true},
+ PollAfter: pgtype.Timestamptz{Time: nextPoll, Valid: true},
+ Status: InstallStatusPending,
+ ScodeEncrypted: pgtype.Text{String: scodeEnc, Valid: true},
+ QrCodeUrlEncrypted: pgtype.Text{String: urlEnc, Valid: true},
+ ExpiresAt: pgtype.Timestamptz{Time: expires, Valid: true},
+ }); err != nil {
+ return fmt.Errorf("defer to pending: %w", err)
+ }
+ return nil
+}
+
+func (w *InstallWorker) handlePending(ctx context.Context, row db.WecomInstallSession, leaseToken string) error {
+ now := w.svc.cfg.Now()
+ if row.ExpiresAt.Valid && !row.ExpiresAt.Time.After(now) {
+ w.failSession(ctx, row.ID, leaseToken, InstallErrorExpired,
+ "The WeCom QR code has expired")
+ return nil
+ }
+ if !row.ScodeEncrypted.Valid || w.svc.cfg.Box == nil {
+ w.failSession(ctx, row.ID, leaseToken, InstallErrorInternalError,
+ "Install session is missing state")
+ return nil
+ }
+ scode, err := decodeAndOpen(w.svc.cfg.Box, row.ScodeEncrypted.String)
+ if err != nil {
+ w.failSession(ctx, row.ID, leaseToken, InstallErrorInternalError,
+ "Install session state could not be decrypted")
+ return nil
+ }
+ upstreamCtx, cancel := context.WithTimeout(ctx, w.svc.cfg.UpstreamTimeout)
+ defer cancel()
+ res, err := w.svc.cfg.Provider.QueryResult(upstreamCtx, string(scode))
+ if err != nil {
+ w.svc.cfg.Logger.Warn("wecom install: query_result failed",
+ "session_id", util.UUIDToString(row.ID), "err", err)
+ nextPoll := now.Add(w.svc.cfg.PendingPollInterval)
+ _, deferErr := w.svc.store.DeferClaimedWecomInstallSession(ctx, db.DeferClaimedWecomInstallSessionParams{
+ ID: row.ID,
+ LeaseToken: pgtype.Text{String: leaseToken, Valid: true},
+ PollAfter: pgtype.Timestamptz{Time: nextPoll, Valid: true},
+ Status: InstallStatusPending,
+ })
+ return deferErr
+ }
+ switch res.Status {
+ case QueryStatusInit, QueryStatusPending:
+ // The QR may have expired while query_result was in flight.
+ if row.ExpiresAt.Valid && !row.ExpiresAt.Time.After(w.svc.cfg.Now()) {
+ w.failSession(ctx, row.ID, leaseToken, InstallErrorExpired,
+ "The WeCom QR code has expired")
+ return nil
+ }
+ nextPoll := now.Add(w.svc.cfg.PendingPollInterval)
+ _, err := w.svc.store.DeferClaimedWecomInstallSession(ctx, db.DeferClaimedWecomInstallSessionParams{
+ ID: row.ID,
+ LeaseToken: pgtype.Text{String: leaseToken, Valid: true},
+ PollAfter: pgtype.Timestamptz{Time: nextPoll, Valid: true},
+ Status: InstallStatusPending,
+ })
+ return err
+ case QueryStatusSuccess:
+ return w.finalizeSuccess(ctx, row, leaseToken, res.BotInfo)
+ }
+ return nil
+}
+
+// bindConflict reports whether a failed bind was the bot's routing slot being
+// held by another installation: the ErrBotOwnedBy* refusals Upsert returns.
+func bindConflict(err error) bool {
+ return errors.Is(err, ErrBotOwnedBySameWorkspace) ||
+ errors.Is(err, ErrBotOwnedByArchivedAgent) ||
+ errors.Is(err, ErrBotOwnedByAnotherWorkspace)
+}
+
+// finalizeSuccess binds the scanned bot and settles the session.
+//
+// The bind goes through InstallationService.Upsert — the same path the manual
+// bot_id + secret form uses — so reclaim-then-upsert, the (channel_type, app_id)
+// routing slot, and the owner-conflict message all behave identically however a
+// bot arrived.
+//
+// The bind and the session completion are two writes, not one transaction, and
+// that is safe because Upsert is idempotent on (workspace, agent, wecom): if the
+// completion fails after a successful bind, the next poll re-upserts the same
+// row and completes again. A single transaction would instead have to hold
+// Upsert's own transaction open across this function.
+func (w *InstallWorker) finalizeSuccess(ctx context.Context, row db.WecomInstallSession, leaseToken string, bot *BotInfo) error {
+ if bot == nil || strings.TrimSpace(bot.BotID) == "" || strings.TrimSpace(bot.Secret) == "" {
+ w.failSession(ctx, row.ID, leaseToken, InstallErrorWecomProtocolError,
+ "WeCom returned success without bot credentials")
+ return nil
+ }
+
+ inst, err := w.svc.installations.Upsert(ctx, InstallationParams{
+ WorkspaceID: row.WorkspaceID,
+ AgentID: row.AgentID,
+ InstallerUserID: row.InitiatorUserID,
+ BotID: bot.BotID,
+ Secret: bot.Secret,
+ })
+ if err != nil {
+ // The bot exists on WeCom's side either way, so the session ends with a
+ // reason the dialog can act on rather than retrying into the same
+ // failure. Only a bot whose routing slot is held elsewhere is a
+ // conflict. Anything else — the credential probe timing out, the
+ // network, the database — is a bot that was created and could not be
+ // connected, and calling it a conflict would send the admin looking
+ // for a connection that does not exist.
+ reason := InstallErrorBindFailed
+ if bindConflict(err) {
+ reason = InstallErrorInstallationConflict
+ }
+ w.svc.cfg.Logger.WarnContext(ctx, "wecom install: bind failed",
+ "session_id", util.UUIDToString(row.ID), "reason", reason, "error", err)
+ w.failSession(ctx, row.ID, leaseToken, reason,
+ "Could not finalize the WeCom install: "+err.Error())
+ return nil
+ }
+
+ rows, err := w.svc.store.CompleteWecomInstallSession(ctx, db.CompleteWecomInstallSessionParams{
+ InstallationID: inst.ID,
+ ID: row.ID,
+ LeaseToken: pgtype.Text{String: leaseToken, Valid: true},
+ })
+ if err != nil {
+ return fmt.Errorf("finalize: complete session: %w", err)
+ }
+ if rows == 0 {
+ // Lost the lease mid-finalize: another worker owns this session and will
+ // complete it. The Upsert above was idempotent, so nothing is left over.
+ return nil
+ }
+
+ // Published only after the session is durably complete, so a failed
+ // completion cannot fire a phantom installation-created event.
+ if w.bus != nil {
+ w.bus.Publish(events.Event{
+ Type: protocol.EventWecomInstallationCreated,
+ WorkspaceID: util.UUIDToString(row.WorkspaceID),
+ ActorType: "system",
+ ActorID: util.UUIDToString(row.InitiatorUserID),
+ Payload: map[string]any{
+ "installation_id": util.UUIDToString(inst.ID),
+ "agent_id": util.UUIDToString(row.AgentID),
+ },
+ })
+ }
+ // Nudge the supervisor so the new bot's connection comes up now rather than
+ // on the next installation scan.
+ if w.supervisor != nil {
+ w.supervisor.Notify()
+ }
+ w.svc.cfg.Logger.InfoContext(ctx, "wecom install: complete",
+ "session_id", util.UUIDToString(row.ID),
+ "installation_id", util.UUIDToString(inst.ID),
+ "workspace_id", util.UUIDToString(row.WorkspaceID),
+ "agent_id", util.UUIDToString(row.AgentID))
+ return nil
+}
+
+// failSession is the idempotent terminal marker. Logs infra errors but never
+// returns them — the worker's loop must move on regardless.
+//
+// The message is for the operator: it is stored on the row and logged here, and
+// never returned to the browser, which shows its own translated line for the
+// reason.
+//
+// Takes the lease it was claimed under, like every other mutation here: a worker
+// whose lease has already expired must not be able to mark a session error out
+// from under the replica that now owns it (see this file's header).
+func (w *InstallWorker) failSession(ctx context.Context, id pgtype.UUID, leaseToken, reason, message string) {
+ rows, err := w.svc.store.FailWecomInstallSession(ctx, db.FailWecomInstallSessionParams{
+ ID: id,
+ LeaseToken: pgtype.Text{String: leaseToken, Valid: leaseToken != ""},
+ ErrorReason: pgtype.Text{String: strings.TrimSpace(reason), Valid: reason != ""},
+ ErrorMessage: pgtype.Text{String: message, Valid: message != ""},
+ })
+ if err != nil {
+ if !errors.Is(err, context.Canceled) {
+ w.svc.cfg.Logger.Warn("wecom install: fail session",
+ "session_id", util.UUIDToString(id), "err", err)
+ }
+ return
+ }
+ if rows == 0 {
+ // Another worker owns the session now; its outcome is the one to log.
+ return
+ }
+ w.svc.cfg.Logger.Info("wecom install: session ended",
+ "session_id", util.UUIDToString(id), "reason", reason, "detail", message)
+}
+
+func (w *InstallWorker) purge(ctx context.Context) error {
+ now := w.svc.cfg.Now()
+ terminalCutoff := now.Add(-w.svc.cfg.TerminalRetention)
+ // Sessions that never got claimed should not live forever either: the
+ // generate deadline plus a little slack is the reasonable ceiling.
+ creatingCutoff := now.Add(-2 * w.svc.cfg.GenerateDeadline)
+ _, err := w.svc.store.PurgeTerminalWecomInstallSessions(ctx, db.PurgeTerminalWecomInstallSessionsParams{
+ TerminalCutoff: pgtype.Timestamptz{Time: terminalCutoff, Valid: true},
+ CreatingCutoff: pgtype.Timestamptz{Time: creatingCutoff, Valid: true},
+ })
+ return err
+}
diff --git a/server/migrations/600_wecom_install_session.down.sql b/server/migrations/600_wecom_install_session.down.sql
new file mode 100644
index 0000000000..1dac592ba8
--- /dev/null
+++ b/server/migrations/600_wecom_install_session.down.sql
@@ -0,0 +1 @@
+DROP TABLE IF EXISTS wecom_install_session;
diff --git a/server/migrations/600_wecom_install_session.up.sql b/server/migrations/600_wecom_install_session.up.sql
new file mode 100644
index 0000000000..88dc06eb6f
--- /dev/null
+++ b/server/migrations/600_wecom_install_session.up.sql
@@ -0,0 +1,47 @@
+-- Scan-code install sessions for the WeCom smart bot.
+--
+-- The QR install is a multi-minute, multi-request conversation with WeCom:
+-- generate a QR, then poll until an admin scans it and the bot's credentials
+-- come back. None of that can live in the request that started it, so the
+-- session is a row and a background worker drives it.
+--
+-- Why the encrypted columns: scode is the polling handle and qr_code_url embeds
+-- it, so together they are a bearer credential for "finish creating this bot".
+-- They are sealed with the same MULTICA_WECOM_SECRET_KEY that seals the bot
+-- secret, which is also why a deployment without that key cannot run the scan
+-- flow at all.
+--
+-- lease_token + lease_expires_at make the poll single-writer across replicas:
+-- WeCom rate-limits query_result, and two replicas polling one scode burn that
+-- budget twice as fast for no benefit.
+--
+-- No foreign keys (repo rule): the workspace teardown path deletes these rows
+-- explicitly, and installation_id is a plain reference to the row the session
+-- produced on success.
+CREATE TABLE wecom_install_session (
+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
+ -- request_key_hash is the SHA-256 of the client's idempotency key. Hashed
+ -- rather than stored raw so a DB dump does not carry client-chosen strings.
+ request_key_hash TEXT NOT NULL,
+ workspace_id UUID NOT NULL,
+ agent_id UUID NOT NULL,
+ initiator_user_id UUID NOT NULL,
+ scode_encrypted TEXT,
+ qr_code_url_encrypted TEXT,
+ status TEXT NOT NULL DEFAULT 'creating'
+ CHECK (status IN ('creating', 'pending', 'success', 'error')),
+ -- poll_after is the earliest next poll. WeCom requires a minimum interval
+ -- between query_result calls, so the schedule lives on the row instead of
+ -- in a worker's memory, where a restart would lose it.
+ poll_after TIMESTAMPTZ NOT NULL DEFAULT now(),
+ expires_at TIMESTAMPTZ,
+ lease_token TEXT,
+ lease_expires_at TIMESTAMPTZ,
+ installation_id UUID,
+ -- error_reason is a stable machine code the frontend switches on;
+ -- error_message is operator-facing detail and is never shown as-is.
+ error_reason TEXT,
+ error_message TEXT,
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
+);
diff --git a/server/migrations/601_wecom_install_session_due_idx.down.sql b/server/migrations/601_wecom_install_session_due_idx.down.sql
new file mode 100644
index 0000000000..5725ee60db
--- /dev/null
+++ b/server/migrations/601_wecom_install_session_due_idx.down.sql
@@ -0,0 +1 @@
+DROP INDEX CONCURRENTLY IF EXISTS idx_wecom_install_session_due;
diff --git a/server/migrations/601_wecom_install_session_due_idx.up.sql b/server/migrations/601_wecom_install_session_due_idx.up.sql
new file mode 100644
index 0000000000..361bb2229d
--- /dev/null
+++ b/server/migrations/601_wecom_install_session_due_idx.up.sql
@@ -0,0 +1,6 @@
+-- Drives the worker's claim scan: the oldest due session still being driven.
+-- Partial on the two live states because settled sessions accumulate until the
+-- retention purge and must not bloat the index the poll loop walks.
+CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_wecom_install_session_due
+ ON wecom_install_session (poll_after, created_at)
+ WHERE status IN ('creating', 'pending');
diff --git a/server/migrations/602_wecom_install_session_request_idx.down.sql b/server/migrations/602_wecom_install_session_request_idx.down.sql
new file mode 100644
index 0000000000..7993df998c
--- /dev/null
+++ b/server/migrations/602_wecom_install_session_request_idx.down.sql
@@ -0,0 +1 @@
+DROP INDEX CONCURRENTLY IF EXISTS idx_wecom_install_session_request;
diff --git a/server/migrations/602_wecom_install_session_request_idx.up.sql b/server/migrations/602_wecom_install_session_request_idx.up.sql
new file mode 100644
index 0000000000..9085584dde
--- /dev/null
+++ b/server/migrations/602_wecom_install_session_request_idx.up.sql
@@ -0,0 +1,5 @@
+-- Makes begin idempotent per (workspace, initiator, idempotency key), so a
+-- double-clicked button or a retried request reuses one session instead of
+-- burning a second WeCom generate call and showing the admin a second QR.
+CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS idx_wecom_install_session_request
+ ON wecom_install_session (workspace_id, initiator_user_id, request_key_hash);
diff --git a/server/migrations/603_wecom_install_session_agent_pending_idx.down.sql b/server/migrations/603_wecom_install_session_agent_pending_idx.down.sql
new file mode 100644
index 0000000000..9ed62e6c1d
--- /dev/null
+++ b/server/migrations/603_wecom_install_session_agent_pending_idx.down.sql
@@ -0,0 +1 @@
+DROP INDEX CONCURRENTLY IF EXISTS idx_wecom_install_session_agent_pending;
diff --git a/server/migrations/603_wecom_install_session_agent_pending_idx.up.sql b/server/migrations/603_wecom_install_session_agent_pending_idx.up.sql
new file mode 100644
index 0000000000..4ffdc868bd
--- /dev/null
+++ b/server/migrations/603_wecom_install_session_agent_pending_idx.up.sql
@@ -0,0 +1,8 @@
+-- At most one live scan session per agent. Two concurrent QRs for one agent
+-- would race to bind it, and the loser's bot would be created on WeCom's side
+-- and then silently owned by nobody.
+--
+-- Partial on the live states so a settled session never blocks a retry.
+CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS idx_wecom_install_session_agent_pending
+ ON wecom_install_session (workspace_id, agent_id)
+ WHERE status IN ('creating', 'pending');
diff --git a/server/migrations/604_wecom_install_session_begin_rate_idx.down.sql b/server/migrations/604_wecom_install_session_begin_rate_idx.down.sql
new file mode 100644
index 0000000000..456f22c9a6
--- /dev/null
+++ b/server/migrations/604_wecom_install_session_begin_rate_idx.down.sql
@@ -0,0 +1 @@
+DROP INDEX CONCURRENTLY IF EXISTS idx_wecom_install_session_begin_rate;
diff --git a/server/migrations/604_wecom_install_session_begin_rate_idx.up.sql b/server/migrations/604_wecom_install_session_begin_rate_idx.up.sql
new file mode 100644
index 0000000000..9267bbab54
--- /dev/null
+++ b/server/migrations/604_wecom_install_session_begin_rate_idx.up.sql
@@ -0,0 +1,4 @@
+-- Serves the per-workspace begin rate check, which counts recent sessions to
+-- stop one workspace from spending the deployment's shared WeCom generate quota.
+CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_wecom_install_session_begin_rate
+ ON wecom_install_session (workspace_id, created_at, initiator_user_id);
diff --git a/server/pkg/db/generated/models.go b/server/pkg/db/generated/models.go
index d1217d63b1..464bf0ed09 100644
--- a/server/pkg/db/generated/models.go
+++ b/server/pkg/db/generated/models.go
@@ -1767,6 +1767,26 @@ type WebhookDelivery struct {
ReplayIdempotencyKey pgtype.Text `json:"replay_idempotency_key"`
}
+type WecomInstallSession struct {
+ ID pgtype.UUID `json:"id"`
+ RequestKeyHash string `json:"request_key_hash"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ AgentID pgtype.UUID `json:"agent_id"`
+ InitiatorUserID pgtype.UUID `json:"initiator_user_id"`
+ ScodeEncrypted pgtype.Text `json:"scode_encrypted"`
+ QrCodeUrlEncrypted pgtype.Text `json:"qr_code_url_encrypted"`
+ Status string `json:"status"`
+ PollAfter pgtype.Timestamptz `json:"poll_after"`
+ ExpiresAt pgtype.Timestamptz `json:"expires_at"`
+ LeaseToken pgtype.Text `json:"lease_token"`
+ LeaseExpiresAt pgtype.Timestamptz `json:"lease_expires_at"`
+ InstallationID pgtype.UUID `json:"installation_id"`
+ ErrorReason pgtype.Text `json:"error_reason"`
+ ErrorMessage pgtype.Text `json:"error_message"`
+ CreatedAt pgtype.Timestamptz `json:"created_at"`
+ UpdatedAt pgtype.Timestamptz `json:"updated_at"`
+}
+
type Workspace struct {
ID pgtype.UUID `json:"id"`
Name string `json:"name"`
diff --git a/server/pkg/db/generated/wecom_install_session.sql.go b/server/pkg/db/generated/wecom_install_session.sql.go
new file mode 100644
index 0000000000..973bbd1780
--- /dev/null
+++ b/server/pkg/db/generated/wecom_install_session.sql.go
@@ -0,0 +1,477 @@
+// Code generated by sqlc. DO NOT EDIT.
+// versions:
+// sqlc v1.31.1
+// source: wecom_install_session.sql
+
+package db
+
+import (
+ "context"
+
+ "github.com/jackc/pgx/v5/pgtype"
+)
+
+const claimDueWecomInstallSession = `-- name: ClaimDueWecomInstallSession :one
+UPDATE wecom_install_session
+SET lease_token = $1,
+ lease_expires_at = $2,
+ updated_at = now()
+WHERE id = (
+ SELECT id FROM wecom_install_session
+ WHERE status IN ('creating', 'pending')
+ AND poll_after <= now()
+ AND (lease_expires_at IS NULL OR lease_expires_at <= now())
+ ORDER BY poll_after, created_at
+ LIMIT 1
+ FOR UPDATE SKIP LOCKED
+)
+RETURNING id, request_key_hash, workspace_id, agent_id, initiator_user_id, scode_encrypted, qr_code_url_encrypted, status, poll_after, expires_at, lease_token, lease_expires_at, installation_id, error_reason, error_message, created_at, updated_at
+`
+
+type ClaimDueWecomInstallSessionParams struct {
+ LeaseToken pgtype.Text `json:"lease_token"`
+ LeaseExpiresAt pgtype.Timestamptz `json:"lease_expires_at"`
+}
+
+// Install worker's claim primitive. Picks the earliest due `creating` or
+// `pending` row whose lease is absent or expired, and rewrites the lease
+// atomically. Backed by idx_wecom_install_session_due (partial index on
+// status IN ('creating','pending') ordered by poll_after, created_at).
+// FOR UPDATE SKIP LOCKED lets multiple replicas share the workload without
+// blocking each other on hot rows.
+func (q *Queries) ClaimDueWecomInstallSession(ctx context.Context, arg ClaimDueWecomInstallSessionParams) (WecomInstallSession, error) {
+ row := q.db.QueryRow(ctx, claimDueWecomInstallSession, arg.LeaseToken, arg.LeaseExpiresAt)
+ var i WecomInstallSession
+ err := row.Scan(
+ &i.ID,
+ &i.RequestKeyHash,
+ &i.WorkspaceID,
+ &i.AgentID,
+ &i.InitiatorUserID,
+ &i.ScodeEncrypted,
+ &i.QrCodeUrlEncrypted,
+ &i.Status,
+ &i.PollAfter,
+ &i.ExpiresAt,
+ &i.LeaseToken,
+ &i.LeaseExpiresAt,
+ &i.InstallationID,
+ &i.ErrorReason,
+ &i.ErrorMessage,
+ &i.CreatedAt,
+ &i.UpdatedAt,
+ )
+ return i, err
+}
+
+const completeWecomInstallSession = `-- name: CompleteWecomInstallSession :execrows
+UPDATE wecom_install_session
+SET status = 'success',
+ installation_id = $1,
+ scode_encrypted = NULL,
+ qr_code_url_encrypted = NULL,
+ lease_token = NULL,
+ lease_expires_at = NULL,
+ updated_at = now()
+WHERE id = $2
+ AND lease_token = $3
+ AND status = 'pending'
+`
+
+type CompleteWecomInstallSessionParams struct {
+ InstallationID pgtype.UUID `json:"installation_id"`
+ ID pgtype.UUID `json:"id"`
+ LeaseToken pgtype.Text `json:"lease_token"`
+}
+
+// Finalize-success terminator. Wipes short-lived ciphertext, records the
+// installation id, flips status to 'success'. Fenced on lease_token AND
+// status='pending' so a stale worker cannot override the owner's success.
+func (q *Queries) CompleteWecomInstallSession(ctx context.Context, arg CompleteWecomInstallSessionParams) (int64, error) {
+ result, err := q.db.Exec(ctx, completeWecomInstallSession, arg.InstallationID, arg.ID, arg.LeaseToken)
+ if err != nil {
+ return 0, err
+ }
+ return result.RowsAffected(), nil
+}
+
+const countWecomInstallSessionsInWindow = `-- name: CountWecomInstallSessionsInWindow :one
+SELECT
+ count(*) AS total,
+ count(*) FILTER (WHERE initiator_user_id = $1) AS by_user
+FROM wecom_install_session
+WHERE workspace_id = $2
+ AND created_at >= $3::timestamptz
+`
+
+type CountWecomInstallSessionsInWindowParams struct {
+ InitiatorUserID pgtype.UUID `json:"initiator_user_id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ Since pgtype.Timestamptz `json:"since"`
+}
+
+type CountWecomInstallSessionsInWindowRow struct {
+ Total int64 `json:"total"`
+ ByUser int64 `json:"by_user"`
+}
+
+// Rate-window count for the (workspace, initiator) 10-minute budget. Called
+// under the LockWecomInstallBeginWorkspace advisory lock so a burst of
+// concurrent begins from the same user cannot slip past the cap. Includes
+// every status — failed and terminated sessions still consumed a quota slot
+// via generate.
+func (q *Queries) CountWecomInstallSessionsInWindow(ctx context.Context, arg CountWecomInstallSessionsInWindowParams) (CountWecomInstallSessionsInWindowRow, error) {
+ row := q.db.QueryRow(ctx, countWecomInstallSessionsInWindow, arg.InitiatorUserID, arg.WorkspaceID, arg.Since)
+ var i CountWecomInstallSessionsInWindowRow
+ err := row.Scan(&i.Total, &i.ByUser)
+ return i, err
+}
+
+const createWecomInstallSession = `-- name: CreateWecomInstallSession :one
+INSERT INTO wecom_install_session (
+ workspace_id, agent_id, initiator_user_id, request_key_hash, status, poll_after
+) VALUES (
+ $1,
+ $2,
+ $3,
+ $4,
+ 'creating',
+ now()
+)
+RETURNING id, request_key_hash, workspace_id, agent_id, initiator_user_id, scode_encrypted, qr_code_url_encrypted, status, poll_after, expires_at, lease_token, lease_expires_at, installation_id, error_reason, error_message, created_at, updated_at
+`
+
+type CreateWecomInstallSessionParams struct {
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ AgentID pgtype.UUID `json:"agent_id"`
+ InitiatorUserID pgtype.UUID `json:"initiator_user_id"`
+ RequestKeyHash string `json:"request_key_hash"`
+}
+
+// Inserts the fresh `creating` row after LockWecomInstallBeginWorkspace has
+// ruled out replay/pending/active/rate-limit. `poll_after=now()` explicitly
+// so ClaimDueWecomInstallSession picks it up on the very next sweep — the
+// claim predicate is `poll_after <= now()`, not "NULL means due", and this
+// avoids that ambiguity.
+func (q *Queries) CreateWecomInstallSession(ctx context.Context, arg CreateWecomInstallSessionParams) (WecomInstallSession, error) {
+ row := q.db.QueryRow(ctx, createWecomInstallSession,
+ arg.WorkspaceID,
+ arg.AgentID,
+ arg.InitiatorUserID,
+ arg.RequestKeyHash,
+ )
+ var i WecomInstallSession
+ err := row.Scan(
+ &i.ID,
+ &i.RequestKeyHash,
+ &i.WorkspaceID,
+ &i.AgentID,
+ &i.InitiatorUserID,
+ &i.ScodeEncrypted,
+ &i.QrCodeUrlEncrypted,
+ &i.Status,
+ &i.PollAfter,
+ &i.ExpiresAt,
+ &i.LeaseToken,
+ &i.LeaseExpiresAt,
+ &i.InstallationID,
+ &i.ErrorReason,
+ &i.ErrorMessage,
+ &i.CreatedAt,
+ &i.UpdatedAt,
+ )
+ return i, err
+}
+
+const deferClaimedWecomInstallSession = `-- name: DeferClaimedWecomInstallSession :execrows
+UPDATE wecom_install_session
+SET lease_token = NULL,
+ lease_expires_at = NULL,
+ poll_after = $1,
+ status = $2,
+ scode_encrypted = COALESCE($3,
+ wecom_install_session.scode_encrypted),
+ qr_code_url_encrypted = COALESCE($4,
+ wecom_install_session.qr_code_url_encrypted),
+ expires_at = COALESCE($5, wecom_install_session.expires_at),
+ updated_at = now()
+WHERE id = $6
+ AND lease_token = $7
+ AND status IN ('creating', 'pending')
+`
+
+type DeferClaimedWecomInstallSessionParams struct {
+ PollAfter pgtype.Timestamptz `json:"poll_after"`
+ Status string `json:"status"`
+ ScodeEncrypted pgtype.Text `json:"scode_encrypted"`
+ QrCodeUrlEncrypted pgtype.Text `json:"qr_code_url_encrypted"`
+ ExpiresAt pgtype.Timestamptz `json:"expires_at"`
+ ID pgtype.UUID `json:"id"`
+ LeaseToken pgtype.Text `json:"lease_token"`
+}
+
+// Releases the current lease and schedules the next poll. Used when the
+// upstream generate/query call yielded init/pending (not terminal) — worker
+// steps back so any replica can pick up when poll_after arrives.
+// Match-on-lease so a stale worker whose lease already expired cannot
+// clobber a new owner's claim.
+func (q *Queries) DeferClaimedWecomInstallSession(ctx context.Context, arg DeferClaimedWecomInstallSessionParams) (int64, error) {
+ result, err := q.db.Exec(ctx, deferClaimedWecomInstallSession,
+ arg.PollAfter,
+ arg.Status,
+ arg.ScodeEncrypted,
+ arg.QrCodeUrlEncrypted,
+ arg.ExpiresAt,
+ arg.ID,
+ arg.LeaseToken,
+ )
+ if err != nil {
+ return 0, err
+ }
+ return result.RowsAffected(), nil
+}
+
+const failWecomInstallSession = `-- name: FailWecomInstallSession :execrows
+UPDATE wecom_install_session
+SET status = 'error',
+ error_reason = $1,
+ error_message = $2,
+ scode_encrypted = NULL,
+ qr_code_url_encrypted = NULL,
+ lease_token = NULL,
+ lease_expires_at = NULL,
+ updated_at = now()
+WHERE id = $3
+ AND lease_token = $4
+ AND status IN ('creating', 'pending')
+`
+
+type FailWecomInstallSessionParams struct {
+ ErrorReason pgtype.Text `json:"error_reason"`
+ ErrorMessage pgtype.Text `json:"error_message"`
+ ID pgtype.UUID `json:"id"`
+ LeaseToken pgtype.Text `json:"lease_token"`
+}
+
+// Terminal failure. Idempotent: only mutates a still-active session. Wipes
+// short-lived ciphertext so a leaked DB dump cannot resurrect the QR after
+// the fact. Lease is dropped so the row is not re-claimed.
+// Match-on-lease like every other mutation here: without it a worker whose
+// lease had already expired could mark a session error out from under the new
+// owner that is mid-way through creating the bot.
+func (q *Queries) FailWecomInstallSession(ctx context.Context, arg FailWecomInstallSessionParams) (int64, error) {
+ result, err := q.db.Exec(ctx, failWecomInstallSession,
+ arg.ErrorReason,
+ arg.ErrorMessage,
+ arg.ID,
+ arg.LeaseToken,
+ )
+ if err != nil {
+ return 0, err
+ }
+ return result.RowsAffected(), nil
+}
+
+const getActiveWecomInstallationForAgent = `-- name: GetActiveWecomInstallationForAgent :one
+SELECT id, workspace_id, agent_id, channel_type, config, status, ws_lease_token, ws_lease_expires_at, installer_user_id, installed_at, created_at, updated_at FROM channel_installation
+WHERE workspace_id = $1
+ AND agent_id = $2
+ AND channel_type = 'wecom'
+ AND status = 'active'
+`
+
+type GetActiveWecomInstallationForAgentParams struct {
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ AgentID pgtype.UUID `json:"agent_id"`
+}
+
+// Existing active WeCom installation guard for begin. One row per
+// (workspace, agent, channel_type='wecom') can be active at a time; the
+// handler returns 409 wecom_agent_already_connected here rather than starting an
+// install that would fail at finalize.
+func (q *Queries) GetActiveWecomInstallationForAgent(ctx context.Context, arg GetActiveWecomInstallationForAgentParams) (ChannelInstallation, error) {
+ row := q.db.QueryRow(ctx, getActiveWecomInstallationForAgent, arg.WorkspaceID, arg.AgentID)
+ var i ChannelInstallation
+ err := row.Scan(
+ &i.ID,
+ &i.WorkspaceID,
+ &i.AgentID,
+ &i.ChannelType,
+ &i.Config,
+ &i.Status,
+ &i.WsLeaseToken,
+ &i.WsLeaseExpiresAt,
+ &i.InstallerUserID,
+ &i.InstalledAt,
+ &i.CreatedAt,
+ &i.UpdatedAt,
+ )
+ return i, err
+}
+
+const getPendingWecomInstallSessionByAgent = `-- name: GetPendingWecomInstallSessionByAgent :one
+SELECT id, request_key_hash, workspace_id, agent_id, initiator_user_id, scode_encrypted, qr_code_url_encrypted, status, poll_after, expires_at, lease_token, lease_expires_at, installation_id, error_reason, error_message, created_at, updated_at FROM wecom_install_session
+WHERE workspace_id = $1
+ AND agent_id = $2
+ AND status IN ('creating', 'pending')
+`
+
+type GetPendingWecomInstallSessionByAgentParams struct {
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ AgentID pgtype.UUID `json:"agent_id"`
+}
+
+// Recovery lookup for the (workspace, agent) pending slot. At most one row
+// per (workspace, agent) has status IN ('creating', 'pending') (indexed by
+// idx_wecom_install_session_agent_pending UNIQUE); a begin with a different
+// Idempotency-Key returns the existing session.
+func (q *Queries) GetPendingWecomInstallSessionByAgent(ctx context.Context, arg GetPendingWecomInstallSessionByAgentParams) (WecomInstallSession, error) {
+ row := q.db.QueryRow(ctx, getPendingWecomInstallSessionByAgent, arg.WorkspaceID, arg.AgentID)
+ var i WecomInstallSession
+ err := row.Scan(
+ &i.ID,
+ &i.RequestKeyHash,
+ &i.WorkspaceID,
+ &i.AgentID,
+ &i.InitiatorUserID,
+ &i.ScodeEncrypted,
+ &i.QrCodeUrlEncrypted,
+ &i.Status,
+ &i.PollAfter,
+ &i.ExpiresAt,
+ &i.LeaseToken,
+ &i.LeaseExpiresAt,
+ &i.InstallationID,
+ &i.ErrorReason,
+ &i.ErrorMessage,
+ &i.CreatedAt,
+ &i.UpdatedAt,
+ )
+ return i, err
+}
+
+const getWecomInstallSession = `-- name: GetWecomInstallSession :one
+SELECT id, request_key_hash, workspace_id, agent_id, initiator_user_id, scode_encrypted, qr_code_url_encrypted, status, poll_after, expires_at, lease_token, lease_expires_at, installation_id, error_reason, error_message, created_at, updated_at FROM wecom_install_session WHERE id = $1
+`
+
+func (q *Queries) GetWecomInstallSession(ctx context.Context, id pgtype.UUID) (WecomInstallSession, error) {
+ row := q.db.QueryRow(ctx, getWecomInstallSession, id)
+ var i WecomInstallSession
+ err := row.Scan(
+ &i.ID,
+ &i.RequestKeyHash,
+ &i.WorkspaceID,
+ &i.AgentID,
+ &i.InitiatorUserID,
+ &i.ScodeEncrypted,
+ &i.QrCodeUrlEncrypted,
+ &i.Status,
+ &i.PollAfter,
+ &i.ExpiresAt,
+ &i.LeaseToken,
+ &i.LeaseExpiresAt,
+ &i.InstallationID,
+ &i.ErrorReason,
+ &i.ErrorMessage,
+ &i.CreatedAt,
+ &i.UpdatedAt,
+ )
+ return i, err
+}
+
+const getWecomInstallSessionByRequestHash = `-- name: GetWecomInstallSessionByRequestHash :one
+SELECT id, request_key_hash, workspace_id, agent_id, initiator_user_id, scode_encrypted, qr_code_url_encrypted, status, poll_after, expires_at, lease_token, lease_expires_at, installation_id, error_reason, error_message, created_at, updated_at FROM wecom_install_session
+WHERE workspace_id = $1
+ AND initiator_user_id = $2
+ AND request_key_hash = $3
+`
+
+type GetWecomInstallSessionByRequestHashParams struct {
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ InitiatorUserID pgtype.UUID `json:"initiator_user_id"`
+ RequestKeyHash string `json:"request_key_hash"`
+}
+
+// Idempotent replay lookup for the Idempotency-Key header. Same
+// (workspace, initiator, request_key_hash) always returns the same session
+// (indexed by idx_wecom_install_session_request UNIQUE). Cross-agent replay
+// is caught by the caller comparing the session's agent_id.
+func (q *Queries) GetWecomInstallSessionByRequestHash(ctx context.Context, arg GetWecomInstallSessionByRequestHashParams) (WecomInstallSession, error) {
+ row := q.db.QueryRow(ctx, getWecomInstallSessionByRequestHash, arg.WorkspaceID, arg.InitiatorUserID, arg.RequestKeyHash)
+ var i WecomInstallSession
+ err := row.Scan(
+ &i.ID,
+ &i.RequestKeyHash,
+ &i.WorkspaceID,
+ &i.AgentID,
+ &i.InitiatorUserID,
+ &i.ScodeEncrypted,
+ &i.QrCodeUrlEncrypted,
+ &i.Status,
+ &i.PollAfter,
+ &i.ExpiresAt,
+ &i.LeaseToken,
+ &i.LeaseExpiresAt,
+ &i.InstallationID,
+ &i.ErrorReason,
+ &i.ErrorMessage,
+ &i.CreatedAt,
+ &i.UpdatedAt,
+ )
+ return i, err
+}
+
+const lockWecomInstallBeginWorkspace = `-- name: LockWecomInstallBeginWorkspace :exec
+
+SELECT pg_advisory_xact_lock(
+ hashtext('wecom_install_begin'),
+ hashtext(($1::uuid)::text)
+)
+`
+
+// WeCom scan-code install session queries.
+//
+// The session survives across replicas: the HTTP handler inserts a `creating`
+// row via LockWecomInstallBeginWorkspace + insert; the install worker on any
+// replica claims due `creating` / `pending` rows via ClaimDueWecomInstallSession
+// using an expiring lease so a crashed worker cannot indefinitely hold the row.
+//
+// No FK / no CASCADE (repo hard rule). workspace_id-scoped rows are cleaned up
+// inside DeleteWorkspaceLeafData; the install worker also purges terminal rows
+// via PurgeTerminalWecomInstallSessions every minute.
+// Serializes the read-then-insert admission decision (request-hash dedupe,
+// pending-session recovery, active-installation guard, and 10-minute rate
+// window count) across replicas for one (workspace) key. Inline hashtext
+// avoids a table-locking pg_advisory_xact_lock namespace collision — the
+// 'wecom_install_begin' string keys this namespace apart from any other
+// workspace-scoped advisory lock we may add later.
+func (q *Queries) LockWecomInstallBeginWorkspace(ctx context.Context, workspaceID pgtype.UUID) error {
+ _, err := q.db.Exec(ctx, lockWecomInstallBeginWorkspace, workspaceID)
+ return err
+}
+
+const purgeTerminalWecomInstallSessions = `-- name: PurgeTerminalWecomInstallSessions :execrows
+DELETE FROM wecom_install_session
+WHERE (status IN ('success', 'error')
+ AND updated_at < $1::timestamptz)
+ OR (status = 'creating'
+ AND created_at < $2::timestamptz)
+`
+
+type PurgeTerminalWecomInstallSessionsParams struct {
+ TerminalCutoff pgtype.Timestamptz `json:"terminal_cutoff"`
+ CreatingCutoff pgtype.Timestamptz `json:"creating_cutoff"`
+}
+
+// GC for terminated sessions older than the retention window (terminal
+// sessions preserved for 30 minutes so the frontend can read
+// final status after the dialog closes). Also sweeps out `creating` rows
+// older than twice the generate deadline, as a defence-in-depth
+// for the worker being fully offline.
+func (q *Queries) PurgeTerminalWecomInstallSessions(ctx context.Context, arg PurgeTerminalWecomInstallSessionsParams) (int64, error) {
+ result, err := q.db.Exec(ctx, purgeTerminalWecomInstallSessions, arg.TerminalCutoff, arg.CreatingCutoff)
+ if err != nil {
+ return 0, err
+ }
+ return result.RowsAffected(), nil
+}
diff --git a/server/pkg/db/generated/workspace_delete.sql.go b/server/pkg/db/generated/workspace_delete.sql.go
index 622bc421de..adf9b0e7b6 100644
--- a/server/pkg/db/generated/workspace_delete.sql.go
+++ b/server/pkg/db/generated/workspace_delete.sql.go
@@ -480,6 +480,9 @@ deleted_channel_user_bindings AS (
deleted_channel_binding_tokens AS (
DELETE FROM channel_binding_token WHERE workspace_id = $1
),
+deleted_wecom_install_sessions AS (
+ DELETE FROM wecom_install_session WHERE workspace_id = $1
+),
deleted_lark_chat_bindings AS (
DELETE FROM lark_chat_session_binding
WHERE installation_id IN (SELECT id FROM ws_lark_installations)
diff --git a/server/pkg/db/queries/wecom_install_session.sql b/server/pkg/db/queries/wecom_install_session.sql
new file mode 100644
index 0000000000..5a81b81e13
--- /dev/null
+++ b/server/pkg/db/queries/wecom_install_session.sql
@@ -0,0 +1,178 @@
+-- WeCom scan-code install session queries.
+--
+-- The session survives across replicas: the HTTP handler inserts a `creating`
+-- row via LockWecomInstallBeginWorkspace + insert; the install worker on any
+-- replica claims due `creating` / `pending` rows via ClaimDueWecomInstallSession
+-- using an expiring lease so a crashed worker cannot indefinitely hold the row.
+--
+-- No FK / no CASCADE (repo hard rule). workspace_id-scoped rows are cleaned up
+-- inside DeleteWorkspaceLeafData; the install worker also purges terminal rows
+-- via PurgeTerminalWecomInstallSessions every minute.
+
+-- name: LockWecomInstallBeginWorkspace :exec
+-- Serializes the read-then-insert admission decision (request-hash dedupe,
+-- pending-session recovery, active-installation guard, and 10-minute rate
+-- window count) across replicas for one (workspace) key. Inline hashtext
+-- avoids a table-locking pg_advisory_xact_lock namespace collision — the
+-- 'wecom_install_begin' string keys this namespace apart from any other
+-- workspace-scoped advisory lock we may add later.
+SELECT pg_advisory_xact_lock(
+ hashtext('wecom_install_begin'),
+ hashtext((sqlc.arg(workspace_id)::uuid)::text)
+);
+
+-- name: GetWecomInstallSessionByRequestHash :one
+-- Idempotent replay lookup for the Idempotency-Key header. Same
+-- (workspace, initiator, request_key_hash) always returns the same session
+-- (indexed by idx_wecom_install_session_request UNIQUE). Cross-agent replay
+-- is caught by the caller comparing the session's agent_id.
+SELECT * FROM wecom_install_session
+WHERE workspace_id = sqlc.arg('workspace_id')
+ AND initiator_user_id = sqlc.arg('initiator_user_id')
+ AND request_key_hash = sqlc.arg('request_key_hash');
+
+-- name: GetPendingWecomInstallSessionByAgent :one
+-- Recovery lookup for the (workspace, agent) pending slot. At most one row
+-- per (workspace, agent) has status IN ('creating', 'pending') (indexed by
+-- idx_wecom_install_session_agent_pending UNIQUE); a begin with a different
+-- Idempotency-Key returns the existing session.
+SELECT * FROM wecom_install_session
+WHERE workspace_id = sqlc.arg('workspace_id')
+ AND agent_id = sqlc.arg('agent_id')
+ AND status IN ('creating', 'pending');
+
+-- name: CountWecomInstallSessionsInWindow :one
+-- Rate-window count for the (workspace, initiator) 10-minute budget. Called
+-- under the LockWecomInstallBeginWorkspace advisory lock so a burst of
+-- concurrent begins from the same user cannot slip past the cap. Includes
+-- every status — failed and terminated sessions still consumed a quota slot
+-- via generate.
+SELECT
+ count(*) AS total,
+ count(*) FILTER (WHERE initiator_user_id = sqlc.arg('initiator_user_id')) AS by_user
+FROM wecom_install_session
+WHERE workspace_id = sqlc.arg('workspace_id')
+ AND created_at >= sqlc.arg('since')::timestamptz;
+
+-- name: GetActiveWecomInstallationForAgent :one
+-- Existing active WeCom installation guard for begin. One row per
+-- (workspace, agent, channel_type='wecom') can be active at a time; the
+-- handler returns 409 wecom_agent_already_connected here rather than starting an
+-- install that would fail at finalize.
+SELECT * FROM channel_installation
+WHERE workspace_id = sqlc.arg('workspace_id')
+ AND agent_id = sqlc.arg('agent_id')
+ AND channel_type = 'wecom'
+ AND status = 'active';
+
+-- name: CreateWecomInstallSession :one
+-- Inserts the fresh `creating` row after LockWecomInstallBeginWorkspace has
+-- ruled out replay/pending/active/rate-limit. `poll_after=now()` explicitly
+-- so ClaimDueWecomInstallSession picks it up on the very next sweep — the
+-- claim predicate is `poll_after <= now()`, not "NULL means due", and this
+-- avoids that ambiguity.
+INSERT INTO wecom_install_session (
+ workspace_id, agent_id, initiator_user_id, request_key_hash, status, poll_after
+) VALUES (
+ sqlc.arg('workspace_id'),
+ sqlc.arg('agent_id'),
+ sqlc.arg('initiator_user_id'),
+ sqlc.arg('request_key_hash'),
+ 'creating',
+ now()
+)
+RETURNING *;
+
+-- name: GetWecomInstallSession :one
+SELECT * FROM wecom_install_session WHERE id = sqlc.arg('id');
+
+-- name: ClaimDueWecomInstallSession :one
+-- Install worker's claim primitive. Picks the earliest due `creating` or
+-- `pending` row whose lease is absent or expired, and rewrites the lease
+-- atomically. Backed by idx_wecom_install_session_due (partial index on
+-- status IN ('creating','pending') ordered by poll_after, created_at).
+-- FOR UPDATE SKIP LOCKED lets multiple replicas share the workload without
+-- blocking each other on hot rows.
+UPDATE wecom_install_session
+SET lease_token = sqlc.arg('lease_token'),
+ lease_expires_at = sqlc.arg('lease_expires_at'),
+ updated_at = now()
+WHERE id = (
+ SELECT id FROM wecom_install_session
+ WHERE status IN ('creating', 'pending')
+ AND poll_after <= now()
+ AND (lease_expires_at IS NULL OR lease_expires_at <= now())
+ ORDER BY poll_after, created_at
+ LIMIT 1
+ FOR UPDATE SKIP LOCKED
+)
+RETURNING *;
+
+-- name: DeferClaimedWecomInstallSession :execrows
+-- Releases the current lease and schedules the next poll. Used when the
+-- upstream generate/query call yielded init/pending (not terminal) — worker
+-- steps back so any replica can pick up when poll_after arrives.
+-- Match-on-lease so a stale worker whose lease already expired cannot
+-- clobber a new owner's claim.
+UPDATE wecom_install_session
+SET lease_token = NULL,
+ lease_expires_at = NULL,
+ poll_after = sqlc.arg('poll_after'),
+ status = sqlc.arg('status'),
+ scode_encrypted = COALESCE(sqlc.narg('scode_encrypted'),
+ wecom_install_session.scode_encrypted),
+ qr_code_url_encrypted = COALESCE(sqlc.narg('qr_code_url_encrypted'),
+ wecom_install_session.qr_code_url_encrypted),
+ expires_at = COALESCE(sqlc.narg('expires_at'), wecom_install_session.expires_at),
+ updated_at = now()
+WHERE id = sqlc.arg('id')
+ AND lease_token = sqlc.arg('lease_token')
+ AND status IN ('creating', 'pending');
+
+-- name: CompleteWecomInstallSession :execrows
+-- Finalize-success terminator. Wipes short-lived ciphertext, records the
+-- installation id, flips status to 'success'. Fenced on lease_token AND
+-- status='pending' so a stale worker cannot override the owner's success.
+UPDATE wecom_install_session
+SET status = 'success',
+ installation_id = sqlc.arg('installation_id'),
+ scode_encrypted = NULL,
+ qr_code_url_encrypted = NULL,
+ lease_token = NULL,
+ lease_expires_at = NULL,
+ updated_at = now()
+WHERE id = sqlc.arg('id')
+ AND lease_token = sqlc.arg('lease_token')
+ AND status = 'pending';
+
+-- name: FailWecomInstallSession :execrows
+-- Terminal failure. Idempotent: only mutates a still-active session. Wipes
+-- short-lived ciphertext so a leaked DB dump cannot resurrect the QR after
+-- the fact. Lease is dropped so the row is not re-claimed.
+-- Match-on-lease like every other mutation here: without it a worker whose
+-- lease had already expired could mark a session error out from under the new
+-- owner that is mid-way through creating the bot.
+UPDATE wecom_install_session
+SET status = 'error',
+ error_reason = sqlc.arg('error_reason'),
+ error_message = sqlc.arg('error_message'),
+ scode_encrypted = NULL,
+ qr_code_url_encrypted = NULL,
+ lease_token = NULL,
+ lease_expires_at = NULL,
+ updated_at = now()
+WHERE id = sqlc.arg('id')
+ AND lease_token = sqlc.arg('lease_token')
+ AND status IN ('creating', 'pending');
+
+-- name: PurgeTerminalWecomInstallSessions :execrows
+-- GC for terminated sessions older than the retention window (terminal
+-- sessions preserved for 30 minutes so the frontend can read
+-- final status after the dialog closes). Also sweeps out `creating` rows
+-- older than twice the generate deadline, as a defence-in-depth
+-- for the worker being fully offline.
+DELETE FROM wecom_install_session
+WHERE (status IN ('success', 'error')
+ AND updated_at < sqlc.arg('terminal_cutoff')::timestamptz)
+ OR (status = 'creating'
+ AND created_at < sqlc.arg('creating_cutoff')::timestamptz);
diff --git a/server/pkg/db/queries/workspace_delete.sql b/server/pkg/db/queries/workspace_delete.sql
index 14b9ef8dd9..d32e2c6b4f 100644
--- a/server/pkg/db/queries/workspace_delete.sql
+++ b/server/pkg/db/queries/workspace_delete.sql
@@ -490,6 +490,9 @@ deleted_channel_user_bindings AS (
deleted_channel_binding_tokens AS (
DELETE FROM channel_binding_token WHERE workspace_id = $1
),
+deleted_wecom_install_sessions AS (
+ DELETE FROM wecom_install_session WHERE workspace_id = $1
+),
deleted_lark_chat_bindings AS (
DELETE FROM lark_chat_session_binding
WHERE installation_id IN (SELECT id FROM ws_lark_installations)