Skip to content

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

Go

MUL-8395 fix(lark): distinguish bound bots from verified message reception (#9709)

Jiahao53c4bbe5cdee
diff --git a/apps/docs/content/docs/lark-bot-integration.mdx b/apps/docs/content/docs/lark-bot-integration.mdx
index fa9d726647..68a377a71b 100644
--- a/apps/docs/content/docs/lark-bot-integration.mdx
+++ b/apps/docs/content/docs/lark-bot-integration.mdx
@@ -25,7 +25,7 @@ Go to **Integrations** and click **Bind to Feishu**.
Scan the QR code with Feishu and confirm the authorization. The QR code works only once; if it expires, generate a new one.
</Step>
<Step>
-Return to Multica. Once the page shows **Connected to Feishu**, the Bot is ready.
+Return to Multica. After binding, Multica shows **Bound — awaiting message verification**. Send the bot a message in Feishu/Lark. **Message reception verified** means a valid message reached this binding; it does not guarantee ongoing connectivity, agent execution, or replies. During rollout, legacy bindings with qualifying conversation history from the current binding can retain their reception evidence. Bindings without that evidence wait for a new message. Rebinding clears the record.
</Step>
</Steps>
@@ -108,7 +108,7 @@ Restart the API server, then connect the Bot from the agent's **Integrations** p
- **QR code expired**: close the dialog and start the connection again.
- **The Bot asks for account binding**: open the binding link and sign in with the Multica account for that workspace.
- **The Bot doesn't run**: check whether the agent is archived and whether the [runtime](/daemon-runtimes) it uses is online.
-- **The Bot never replies at all**: the app must push events over a long connection; Multica has no webhook endpoint. In the Feishu/Lark developer console, open **Events & Callbacks → Event Configuration** and confirm that the subscription method is the long connection rather than a request URL, that `im.message.receive_v1` is subscribed, and that the app version carrying that configuration is published (and approved, where the tenant reviews releases). An app set to a request URL still binds, still shows Connected, and silently receives nothing.
+- **The Bot never replies at all**: the app must push events over a long connection; Multica has no webhook endpoint. In the Feishu/Lark developer console, open **Events & Callbacks → Event Configuration** and confirm that the subscription method is the long connection rather than a request URL, that `im.message.receive_v1` is subscribed, and that the app version carrying that configuration is published (and approved, where the tenant reviews releases). An app set to a request URL still binds, shows as bound but awaiting message verification, and silently receives nothing.
## Next steps
diff --git a/apps/docs/content/docs/lark-bot-integration.zh.mdx b/apps/docs/content/docs/lark-bot-integration.zh.mdx
index 0748e03745..fe65d03e29 100644
--- a/apps/docs/content/docs/lark-bot-integration.zh.mdx
+++ b/apps/docs/content/docs/lark-bot-integration.zh.mdx
@@ -25,7 +25,7 @@ import { Step, Steps } from "fumadocs-ui/components/steps";
用飞书扫描二维码并确认授权。二维码只能用一次,过期后重新生成即可。
</Step>
<Step>
-回到 Multica。页面显示 **已连接到飞书** 后即可使用。
+回到 Multica。绑定后页面显示 **已绑定,等待消息验证**。请在飞书/Lark 中给机器人发送消息。**消息接收已验证** 只表示本次绑定收到过有效消息,不保证持续在线、智能体执行成功或回复成功。升级时,旧绑定可以依据本次绑定之后的有效会话历史保留接收证明;没有这类证据的绑定仍需等待新消息。重新绑定会清空记录。
</Step>
</Steps>
@@ -108,7 +108,7 @@ openssl rand -base64 32
- **二维码失效**:关闭弹窗后重新发起连接。
- **Bot 要求绑定账号**:打开绑定链接并使用该工作区的 Multica 账号登录。
- **Bot 不执行**:检查智能体是否已归档,以及它使用的[运行时](/daemon-runtimes)是否在线。
-- **Bot 完全不回复**:应用必须通过长连接推送事件,Multica 没有 webhook 接收地址。打开飞书开发者后台的 **事件与回调 → 事件配置**,确认订阅方式是使用长连接接收事件而不是请求地址,`im.message.receive_v1` 已订阅,并且包含该配置的版本已发布(企业需要审核时还要通过审核)。配成请求地址的应用照样能绑定、照样显示"已连接",但一条消息都收不到。
+- **Bot 完全不回复**:应用必须通过长连接推送事件,Multica 没有 webhook 接收地址。打开飞书开发者后台的 **事件与回调 → 事件配置**,确认订阅方式是使用长连接接收事件而不是请求地址,`im.message.receive_v1` 已订阅,并且包含该配置的版本已发布(企业需要审核时还要通过审核)。配成请求地址的应用照样能绑定、显示“已绑定,等待消息验证”,但一条消息都收不到。
## 接下来
diff --git a/packages/core/api/client.ts b/packages/core/api/client.ts
index 2648e8bf09..befbed1eca 100644
--- a/packages/core/api/client.ts
+++ b/packages/core/api/client.ts
@@ -385,6 +385,8 @@ import {
RedeemWecomBindingTokenResponseSchema,
EMPTY_WECOM_INSTALLATION,
EMPTY_LIST_WECOM_INSTALLATIONS_RESPONSE,
+ ListLarkInstallationsResponseSchema,
+ EMPTY_LIST_LARK_INSTALLATIONS_RESPONSE,
EMPTY_REDEEM_WECOM_BINDING_TOKEN_RESPONSE,
TelegramInstallationSchema,
ListTelegramInstallationsResponseSchema,
@@ -5094,7 +5096,13 @@ export class ApiClient {
// Lark integration
async listLarkInstallations(workspaceId: string): Promise<ListLarkInstallationsResponse> {
- return this.fetch(`/api/workspaces/${workspaceId}/lark/installations`);
+ const endpoint = `/api/workspaces/${workspaceId}/lark/installations`;
+ return parseWithFallback(
+ await this.fetch(endpoint),
+ ListLarkInstallationsResponseSchema,
+ EMPTY_LIST_LARK_INSTALLATIONS_RESPONSE,
+ { endpoint },
+ );
}
async beginLarkInstall(
diff --git a/packages/core/api/lark-verification.test.ts b/packages/core/api/lark-verification.test.ts
new file mode 100644
index 0000000000..85f0db21b6
--- /dev/null
+++ b/packages/core/api/lark-verification.test.ts
@@ -0,0 +1,33 @@
+// @vitest-environment node
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { ApiClient } from "./client";
+import { parseWithFallback } from "./schema";
+import { LarkInstallationSchema, ListLarkInstallationsResponseSchema, EMPTY_LIST_LARK_INSTALLATIONS_RESPONSE } from "./schemas";
+
+const installation = { id: "inst", status: "active" };
+describe("Lark receipt response compatibility", () => {
+ it("keeps an older response pending verification", () => {
+ expect(LarkInstallationSchema.parse(installation).first_message_received_at).toBeUndefined();
+ });
+ it("accepts a recorded timestamp and future fields/enums", () => {
+ const parsed = LarkInstallationSchema.parse({ ...installation, status: "future", future: true, first_message_received_at: "2026-10-29T12:00:00+00:00" });
+ expect(parsed.first_message_received_at).toBe("2026-10-29T12:00:00+00:00");
+ expect(parsed.status).toBe("future");
+ });
+ it.each([null, false, 123, "yesterday", "", "2026-99-99T00:00:00Z"])("does not treat %s as verification", (value) => {
+ expect(LarkInstallationSchema.parse({ ...installation, first_message_received_at: value }).first_message_received_at).toBeFalsy();
+ });
+ it("defaults missing status to revoked and malformed lists safely", () => {
+ expect(LarkInstallationSchema.parse({ id: "inst" }).status).toBe("revoked");
+ expect(parseWithFallback({ installations: "bad" }, ListLarkInstallationsResponseSchema, EMPTY_LIST_LARK_INSTALLATIONS_RESPONSE, { endpoint: "lark" })).toEqual(EMPTY_LIST_LARK_INSTALLATIONS_RESPONSE);
+ });
+});
+
+
+afterEach(() => vi.unstubAllGlobals());
+it("parses receipt evidence at the API boundary", async () => {
+ vi.stubGlobal("fetch", vi.fn().mockResolvedValue(new Response(JSON.stringify({ configured: true, installations: [{ ...installation, first_message_received_at: "invalid" }] }), { status: 200 })));
+ const response = await new ApiClient("https://api.example.test").listLarkInstallations("ws");
+ expect(response.installations[0]?.first_message_received_at).toBeUndefined();
+ expect(response.installations[0]?.status).toBe("active");
+});
diff --git a/packages/core/api/schemas.ts b/packages/core/api/schemas.ts
index 4ca8ec31d9..cc5b028778 100644
--- a/packages/core/api/schemas.ts
+++ b/packages/core/api/schemas.ts
@@ -44,6 +44,7 @@ import type {
ListDingTalkGroupsResponse,
RedeemDingTalkBindingTokenResponse,
WecomInstallation,
+ ListLarkInstallationsResponse,
ListWecomInstallationsResponse,
RedeemWecomBindingTokenResponse,
TelegramInstallation,
@@ -3832,3 +3833,32 @@ export const RuntimeProfileSchema = z
runtime_type: profile.runtime_type || profile.protocol_family,
}));
export const RuntimeProfileListSchema = z.array(RuntimeProfileSchema);
+
+// Receipt evidence is optional across mixed server/desktop versions. A malformed
+// timestamp must never render the binding as verified.
+export const LarkInstallationSchema = z.object({
+ id: z.string(),
+ workspace_id: z.string().default(""),
+ agent_id: z.string().default(""),
+ app_id: z.string().default(""),
+ bot_open_id: z.string().default(""),
+ installer_user_id: z.string().default(""),
+ tenant_key: z.string().nullable().optional(),
+ status: z.string().default("revoked"),
+ region: z.string().optional(),
+ installed_at: z.string().default(""),
+ created_at: z.string().default(""),
+ updated_at: z.string().default(""),
+ first_message_received_at: z.iso.datetime({ offset: true }).nullable().optional().catch(undefined),
+}).loose();
+
+export const ListLarkInstallationsResponseSchema = z.object({
+ installations: z.array(LarkInstallationSchema).default([]),
+ configured: z.boolean().default(false),
+ install_supported: z.boolean().optional(),
+}).loose();
+
+export const EMPTY_LIST_LARK_INSTALLATIONS_RESPONSE: ListLarkInstallationsResponse = {
+ installations: [],
+ configured: false,
+};
diff --git a/packages/core/lark/queries.test.ts b/packages/core/lark/queries.test.ts
new file mode 100644
index 0000000000..7af715968d
--- /dev/null
+++ b/packages/core/lark/queries.test.ts
@@ -0,0 +1,31 @@
+// @vitest-environment node
+import { expect, it, vi } from "vitest";
+import { QueryClient, QueryObserver } from "@tanstack/react-query";
+import { larkInstallationsOptions, larkKeys } from "./queries";
+import { api } from "../api";
+import type { ListLarkInstallationsResponse } from "../types";
+vi.mock("../api", () => ({ api: { listLarkInstallations: vi.fn() } }));
+
+it("refreshes mounted pending evidence and stops polling after verification", async () => {
+ vi.useFakeTimers();
+ const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
+ const pending: ListLarkInstallationsResponse = { configured: true, installations: [{ id: "inst", workspace_id: "ws", agent_id: "a", app_id: "app", bot_open_id: "bot", installer_user_id: "user", status: "active", installed_at: "", created_at: "", updated_at: "" }] };
+ vi.mocked(api.listLarkInstallations).mockResolvedValueOnce(pending).mockResolvedValue({ ...pending, installations: [{ ...pending.installations[0]!, first_message_received_at: "2026-10-29T00:00:00Z" }] });
+ // QueryObserver timers do not run on the server. Inspect the actual query's
+ // interval policy while verifying that a refetch updates the shared cache.
+ const opts = larkInstallationsOptions("ws");
+ const observer = new QueryObserver(client, opts);
+ const unsubscribe = observer.subscribe(() => {});
+ try {
+ await client.fetchQuery(opts);
+ const query = observer.getCurrentQuery();
+ expect(typeof opts.refetchInterval).toBe("function");
+ if (typeof opts.refetchInterval !== "function") throw new Error("missing pending refresh policy");
+ expect(opts.refetchInterval(query)).toBe(5000);
+ await observer.refetch();
+ expect(client.getQueryData<ListLarkInstallationsResponse>(larkKeys.installations("ws"))?.installations[0]?.first_message_received_at).toBeTruthy();
+ expect(opts.refetchInterval(query)).toBe(false);
+ client.setQueryData(larkKeys.installations("ws"), { ...pending, installations: [{ ...pending.installations[0]!, status: "revoked" }] });
+ expect(opts.refetchInterval(query)).toBe(false);
+ } finally { unsubscribe(); client.clear(); vi.useRealTimers(); }
+});
diff --git a/packages/core/lark/queries.ts b/packages/core/lark/queries.ts
index 62c6de9ca2..e8d824cab3 100644
--- a/packages/core/lark/queries.ts
+++ b/packages/core/lark/queries.ts
@@ -14,4 +14,9 @@ export const larkInstallationsOptions = (wsId: string) =>
queryKey: larkKeys.installations(wsId),
queryFn: () => api.listLarkInstallations(wsId),
enabled: !!wsId,
+ // Poll only while mounted and awaiting proof; silence never becomes failure.
+ refetchInterval: (query) =>
+ query.state.data?.installations.some(
+ (inst) => inst.status === "active" && !inst.first_message_received_at,
+ ) ? 5000 : false,
});
diff --git a/packages/core/types/lark.ts b/packages/core/types/lark.ts
index 86245e5581..f7d127c852 100644
--- a/packages/core/types/lark.ts
+++ b/packages/core/types/lark.ts
@@ -19,6 +19,8 @@ export interface LarkInstallation {
* server that predates the field — defaults to Feishu in the UI
* (see CLAUDE.md → API Response Compatibility). */
region?: "feishu" | "lark" | string;
+ /** First valid message observed for this binding; absence means no recorded proof. */
+ first_message_received_at?: string | null;
installed_at: string;
created_at: string;
updated_at: string;
diff --git a/packages/views/locales/en/settings.json b/packages/views/locales/en/settings.json
index 4d933a3b6e..a6d23a2b56 100644
--- a/packages/views/locales/en/settings.json
+++ b/packages/views/locales/en/settings.json
@@ -882,7 +882,7 @@
"not_enabled_self_host_hint": "Self-hosters: see the project README for details.",
"preview_title": "Lark Bot installation coming soon",
"preview_description": "Lark connections aren't enabled on this deployment. Contact your administrator.",
- "connected_bots": "Connected bots",
+ "connected_bots": "Bots",
"loading": "Loading…",
"empty_title": "No bots connected yet",
"empty_description_prefix": "Open an Agent in this workspace and click",
@@ -929,7 +929,7 @@
"install_starting": "Preparing QR code…",
"install_scan_hint": "Lark → Scan → authorize the new PersonalAgent.",
"install_open_link_fallback": "Or tap here to open in Lark",
- "install_success": "Install complete — your Bot is online.",
+ "install_success": "Bot bound. Send it a message in Feishu/Lark to verify reception.",
"install_success_toast": "Lark Bot installed",
"install_open_link_fallback_feishu": "Or tap here to open in Feishu",
"install_open_link_fallback_lark": "Or tap here to open in Lark",
@@ -946,7 +946,12 @@
"install_error_installer_bind": "Installed the bot, but could not bind your Lark identity. Try again or contact support.",
"install_error_session_lost": "Install session expired or was lost. Scan again to start over.",
"install_error_forbidden": "You no longer have permission to install Lark Bots in this workspace. Ask a workspace admin to continue.",
- "install_error_generic": "Install failed. Try again."
+ "install_error_generic": "Install failed. Try again.",
+ "bound_label": "Bound",
+ "inbound_pending": "Bound — awaiting message verification",
+ "inbound_verified": "Message reception verified",
+ "inbound_pending_hint": "Send this bot a message in Feishu/Lark to verify reception. If it does not arrive, check long connection mode, the im.message.receive_v1 subscription, and app publication/approval. Existing bindings may have no recorded verification yet.",
+ "inbound_verified_hint": "This binding received a valid message. This does not confirm ongoing connectivity, agent execution, or replies."
},
"composio": {
"page_description": "Connect apps your agents can use.",
diff --git a/packages/views/locales/fr/settings.json b/packages/views/locales/fr/settings.json
index 39ccb75e42..9e5d7347ac 100644
--- a/packages/views/locales/fr/settings.json
+++ b/packages/views/locales/fr/settings.json
@@ -882,7 +882,7 @@
"not_enabled_self_host_hint": "Auto-hébergement : voir le README du projet pour les détails.",
"preview_title": "Installation de bot Lark bientôt disponible",
"preview_description": "Les connexions Lark ne sont pas activées sur ce déploiement. Contactez votre administrateur.",
- "connected_bots": "Bots connectés",
+ "connected_bots": "Bots",
"loading": "Chargement…",
"empty_title": "Aucun bot connecté pour l'instant",
"empty_description_prefix": "Ouvrez un agent de cet espace de travail et cliquez sur",
@@ -929,7 +929,7 @@
"install_starting": "Préparation du QR code…",
"install_scan_hint": "Lark → Scanner → autorisez le nouveau PersonalAgent.",
"install_open_link_fallback": "Ou touchez ici pour ouvrir dans Lark",
- "install_success": "Installation terminée — votre bot est en ligne.",
+ "install_success": "Bot associé. Envoyez-lui un message dans Feishu/Lark pour vérifier la réception.",
"install_success_toast": "Bot Lark installé",
"install_open_link_fallback_feishu": "Ou touchez ici pour ouvrir dans Feishu",
"install_open_link_fallback_lark": "Ou touchez ici pour ouvrir dans Lark",
@@ -946,7 +946,12 @@
"install_error_installer_bind": "Le bot a été installé, mais votre identité Lark n'a pas pu être associée. Réessayez ou contactez le support.",
"install_error_session_lost": "La session d'installation a expiré ou a été perdue. Scannez à nouveau pour recommencer.",
"install_error_forbidden": "Vous n'avez plus la permission d'installer des bots Lark dans cet espace de travail. Demandez à un administrateur de l'espace de travail pour continuer.",
- "install_error_generic": "Échec de l'installation. Réessayez."
+ "install_error_generic": "Échec de l'installation. Réessayez.",
+ "bound_label": "Associé",
+ "inbound_pending": "Associé — en attente de vérification",
+ "inbound_verified": "Réception des messages vérifiée",
+ "inbound_pending_hint": "Envoyez un message à ce bot dans Feishu/Lark pour vérifier la réception. Si rien n’arrive, vérifiez la connexion persistante, l’abonnement im.message.receive_v1 et la publication/approbation de l’application. Les associations existantes peuvent ne pas encore avoir de vérification enregistrée.",
+ "inbound_verified_hint": "Cette association a reçu un message valide. Cela ne confirme ni la connexion continue, ni l’exécution de l’agent, ni ses réponses."
},
"composio": {
"page_description": "Connectez des applications que vos agents peuvent utiliser.",
diff --git a/packages/views/locales/ja/settings.json b/packages/views/locales/ja/settings.json
index 0b2d22d1fc..4469345628 100644
--- a/packages/views/locales/ja/settings.json
+++ b/packages/views/locales/ja/settings.json
@@ -877,7 +877,7 @@
"not_enabled_self_host_hint": "セルフホスト運用者の方は、詳細はプロジェクトの README を参照してください。",
"preview_title": "Lark ボットの設置はまもなく利用可能になります",
"preview_description": "この環境では Lark 接続が有効ではありません。管理者に連絡してください。",
- "connected_bots": "接続済みのボット",
+ "connected_bots": "ボット",
"loading": "読み込み中…",
"empty_title": "まだボットが接続されていません",
"empty_description_prefix": "このワークスペースのエージェントを開いて",
@@ -924,7 +924,7 @@
"install_starting": "QR コードを準備しています…",
"install_scan_hint": "Lark → スキャン → 新しい PersonalAgent を承認してください。",
"install_open_link_fallback": "ここをタップして Lark で開く",
- "install_success": "設置が完了しました — ボットはオンラインです。",
+ "install_success": "ボットを連携しました。Feishu/Lark でメッセージを送り、受信を確認してください。",
"install_success_toast": "Lark ボットを設置しました",
"install_open_link_fallback_feishu": "ここをタップして Feishu で開く",
"install_open_link_fallback_lark": "ここをタップして Lark で開く",
@@ -941,7 +941,12 @@
"install_error_installer_bind": "ボットは設置されましたが、Lark の身元情報を連携できませんでした。もう一度お試しいただくか、サポートにお問い合わせください。",
"install_error_session_lost": "設置セッションが期限切れまたは失われました。もう一度スキャンしてやり直してください。",
"install_error_forbidden": "このワークスペースに Lark ボットを設置する権限がなくなりました。ワークスペース管理者にお問い合わせください。",
- "install_error_generic": "設置に失敗しました。もう一度お試しください。"
+ "install_error_generic": "設置に失敗しました。もう一度お試しください。",
+ "bound_label": "連携済み",
+ "inbound_pending": "連携済み・メッセージ確認待ち",
+ "inbound_verified": "メッセージ受信確認済み",
+ "inbound_pending_hint": "Feishu/Lark でこのボットにメッセージを送り、受信を確認してください。届かない場合は長時間接続、im.message.receive_v1 の購読、アプリの公開・承認状態を確認してください。既存の連携には確認記録がない場合があります。",
+ "inbound_verified_hint": "今回の連携で有効なメッセージを受信しました。継続的な接続、エージェントの実行、返信の成功を保証するものではありません。"
},
"composio": {
"page_description": "エージェントが使えるアプリに接続します。",
diff --git a/packages/views/locales/ko/settings.json b/packages/views/locales/ko/settings.json
index c5f897c493..1f652ae2ce 100644
--- a/packages/views/locales/ko/settings.json
+++ b/packages/views/locales/ko/settings.json
@@ -1146,7 +1146,7 @@
"not_enabled_self_host_hint": "셀프 호스트 운영자: 자세한 내용은 프로젝트 README를 참고하세요.",
"preview_title": "Lark 봇 설치 곧 출시 예정",
"preview_description": "이 배포 환경에서는 Lark 연결이 활성화되지 않았습니다. 관리자에게 문의하세요.",
- "connected_bots": "연결된 봇",
+ "connected_bots": "봇",
"loading": "불러오는 중…",
"empty_title": "아직 연결된 봇이 없어요",
"empty_description_prefix": "이 워크스페이스의 에이전트를 열고",
@@ -1193,7 +1193,7 @@
"install_starting": "QR 코드를 준비하는 중…",
"install_scan_hint": "Lark → 스캔 → 새 PersonalAgent를 승인하세요.",
"install_open_link_fallback": "또는 여기를 눌러 Lark에서 열기",
- "install_success": "설치 완료 — 봇이 온라인 상태입니다.",
+ "install_success": "봇이 등록되었습니다. Feishu/Lark에서 메시지를 보내 수신을 확인하세요.",
"install_success_toast": "Lark 봇이 설치되었어요",
"install_open_link_fallback_feishu": "또는 여기를 눌러 Feishu에서 열기",
"install_open_link_fallback_lark": "또는 여기를 눌러 Lark에서 열기",
@@ -1210,7 +1210,12 @@
"install_error_installer_bind": "봇은 설치되었지만 Lark 신원을 연결하지 못했어요. 다시 시도하거나 지원팀에 문의하세요.",
"install_error_session_lost": "설치 세션이 만료되었거나 유실되었어요. 다시 스캔해 처음부터 진행하세요.",
"install_error_forbidden": "이 워크스페이스에 Lark 봇을 설치할 권한이 더 이상 없어요. 워크스페이스 관리자에게 문의하세요.",
- "install_error_generic": "설치에 실패했어요. 다시 시도하세요."
+ "install_error_generic": "설치에 실패했어요. 다시 시도하세요.",
+ "bound_label": "연결 등록됨",
+ "inbound_pending": "등록됨 · 메시지 확인 대기",
+ "inbound_verified": "메시지 수신 확인됨",
+ "inbound_pending_hint": "Feishu/Lark에서 이 봇에 메시지를 보내 수신을 확인하세요. 도착하지 않으면 지속 연결 모드, im.message.receive_v1 구독, 앱 게시 및 승인 상태를 확인하세요. 기존 연결에는 확인 기록이 없을 수 있습니다.",
+ "inbound_verified_hint": "이번 연결에서 유효한 메시지를 받았습니다. 지속적인 연결, 에이전트 실행 또는 답장 성공을 의미하지는 않습니다."
},
"composio": {
"page_description": "에이전트가 사용할 앱을 연결하세요.",
diff --git a/packages/views/locales/zh-Hans/settings.json b/packages/views/locales/zh-Hans/settings.json
index 500354273d..816a935b56 100644
--- a/packages/views/locales/zh-Hans/settings.json
+++ b/packages/views/locales/zh-Hans/settings.json
@@ -877,7 +877,7 @@
"not_enabled_self_host_hint": "自托管用户:详见项目 README。",
"preview_title": "飞书 Bot 安装即将上线",
"preview_description": "此部署尚未启用飞书连接,请联系管理员。",
- "connected_bots": "已连接的 Bot",
+ "connected_bots": "机器人",
"loading": "加载中…",
"empty_title": "尚未连接 Bot",
"empty_description_prefix": "在本工作区打开一个智能体,点击",
@@ -924,7 +924,7 @@
"install_starting": "正在准备二维码…",
"install_scan_hint": "飞书 → 扫一扫 → 授权新 PersonalAgent。",
"install_open_link_fallback": "或点这里直接在飞书中打开",
- "install_success": "安装完成,Bot 已上线。",
+ "install_success": "机器人已绑定。请在飞书/Lark 中发送消息以验证接收。",
"install_success_toast": "飞书 Bot 已安装",
"install_open_link_fallback_feishu": "或点这里直接在飞书中打开",
"install_open_link_fallback_lark": "或点这里直接在 Lark 中打开",
@@ -941,7 +941,12 @@
"install_error_installer_bind": "已安装 Bot,但未能绑定你的飞书身份。请重试或联系管理员。",
"install_error_session_lost": "安装会话已失效或丢失,请重新扫码。",
"install_error_forbidden": "你已没有在此工作区安装飞书 Bot 的权限,请联系工作区管理员。",
- "install_error_generic": "安装失败,请重试。"
+ "install_error_generic": "安装失败,请重试。",
+ "bound_label": "已绑定",
+ "inbound_pending": "已绑定,等待消息验证",
+ "inbound_verified": "消息接收已验证",
+ "inbound_pending_hint": "请在飞书/Lark 中给此机器人发送消息以验证接收。若未收到,请检查长连接模式、im.message.receive_v1 事件订阅以及应用发布和审批状态。已有绑定可能尚无验证记录。",
+ "inbound_verified_hint": "本次绑定已收到有效消息;这不代表持续在线、智能体执行成功或回复成功。"
},
"composio": {
"page_description": "连接智能体可使用的应用。",
diff --git a/packages/views/locales/zh-Hant/settings.json b/packages/views/locales/zh-Hant/settings.json
index c39a849ea8..87837d1d2e 100644
--- a/packages/views/locales/zh-Hant/settings.json
+++ b/packages/views/locales/zh-Hant/settings.json
@@ -877,7 +877,7 @@
"not_enabled_self_host_hint": "自託管使用者:詳見專案 README。",
"preview_title": "飛書 Bot 安裝即將上線",
"preview_description": "此部署尚未啟用飛書連線,請聯絡管理員。",
- "connected_bots": "已連線的 Bot",
+ "connected_bots": "機器人",
"loading": "載入中…",
"empty_title": "尚未連線 Bot",
"empty_description_prefix": "在本工作區開啟一個智慧體,點選",
@@ -924,7 +924,7 @@
"install_starting": "正在準備二維碼…",
"install_scan_hint": "飛書 → 掃一掃 → 授權新 PersonalAgent。",
"install_open_link_fallback": "或點這裡直接在飛書中開啟",
- "install_success": "安裝完成,Bot 已上線。",
+ "install_success": "機器人已綁定。請在飛書/Lark 中傳送訊息以驗證接收。",
"install_success_toast": "飛書 Bot 已安裝",
"install_open_link_fallback_feishu": "或點這裡直接在飛書中開啟",
"install_open_link_fallback_lark": "或點這裡直接在 Lark 中開啟",
@@ -941,7 +941,12 @@
"install_error_installer_bind": "已安裝 Bot,但未能繫結你的飛書身份。請重試或聯絡管理員。",
"install_error_session_lost": "安裝會話已失效或丟失,請重新掃碼。",
"install_error_forbidden": "你已沒有在此工作區安裝飛書 Bot 的權限,請聯絡工作區管理員。",
- "install_error_generic": "安裝失敗,請重試。"
+ "install_error_generic": "安裝失敗,請重試。",
+ "bound_label": "已綁定",
+ "inbound_pending": "已綁定,等待訊息驗證",
+ "inbound_verified": "訊息接收已驗證",
+ "inbound_pending_hint": "請在飛書/Lark 中傳送訊息給此機器人以驗證接收。若未收到,請檢查長連線模式、im.message.receive_v1 事件訂閱,以及應用程式發布和審核狀態。既有綁定可能尚無驗證紀錄。",
+ "inbound_verified_hint": "本次綁定已收到有效訊息;這不代表持續連線、智慧體執行成功或回覆成功。"
},
"composio": {
"page_description": "連線智慧體可使用的應用。",
diff --git a/packages/views/settings/components/channels-tab.test.tsx b/packages/views/settings/components/channels-tab.test.tsx
index f323babcd9..da338fdda0 100644
--- a/packages/views/settings/components/channels-tab.test.tsx
+++ b/packages/views/settings/components/channels-tab.test.tsx
@@ -9,6 +9,7 @@ const state = vi.hoisted(() => ({
// The IM channels keep revoked rows for audit, so the fixture carries a real
// status — a row without one is not evidence of a live connection (#8496).
installationStatus: "active" as string,
+ larkInstallations: null as { status: string; first_message_received_at?: string }[] | null,
push: vi.fn(),
}));
vi.mock("../../navigation/context", async (importOriginal) => ({
@@ -28,9 +29,11 @@ vi.mock("@multica/core/permissions", () => ({
}));
vi.mock("@tanstack/react-query", () => ({
queryOptions: <T,>(opts: T) => opts,
- useQuery: (opts: { select?: (data: unknown) => unknown }) => ({
+ useQuery: (opts: { queryKey?: readonly unknown[]; select?: (data: unknown) => unknown }) => ({
data: opts.select?.({
- installations: [{ id: "one", status: state.installationStatus }],
+ installations: opts.queryKey?.[0] === "lark" && state.larkInstallations
+ ? state.larkInstallations
+ : [{ id: "one", status: state.installationStatus }],
}),
isPending: state.pending,
isError: state.connectionError,
@@ -49,6 +52,7 @@ beforeEach(() => {
state.connectionError = false;
state.pending = false;
state.installationStatus = "active";
+ state.larkInstallations = null;
state.push.mockClear();
});
@@ -103,3 +107,40 @@ describe("ChannelsTab", () => {
expect(screen.getByText("Lark detail")).toBeInTheDocument();
});
});
+
+
+it("labels an installed Feishu bot as bound without claiming connectivity", () => {
+ renderWithI18n(<ChannelsTab />);
+ expect(screen.getByRole("link", { name: /Lark Bound/ })).toBeInTheDocument();
+ expect(screen.queryByRole("link", { name: /Lark Connected/ })).toBeNull();
+});
+
+
+it("updates the Lark overview from pending to verified and back on rebind/revoke", () => {
+ state.larkInstallations = [{ status: "active" }];
+ const { rerender } = renderWithI18n(<ChannelsTab />);
+ const status = () => screen.getByRole("link", { name: /^Lark / });
+ expect(status()).toHaveTextContent("Bound");
+ expect(status().querySelector(".bg-success")).toBeNull();
+
+ state.larkInstallations = [{ status: "active" }, { status: "active", first_message_received_at: "2026-10-30T00:00:00Z" }];
+ rerender(<ChannelsTab />);
+ expect(status()).toHaveTextContent("Message reception verified");
+ expect(status().querySelector(".bg-success")).not.toBeNull();
+
+ state.larkInstallations[1]!.first_message_received_at = undefined;
+ rerender(<ChannelsTab />);
+ expect(status()).toHaveTextContent("Bound");
+ expect(status().querySelector(".bg-success")).toBeNull();
+
+ state.larkInstallations[1]!.first_message_received_at = "2026-10-30T00:00:00Z";
+ state.larkInstallations[1]!.status = "revoked";
+ rerender(<ChannelsTab />);
+ expect(status()).toHaveTextContent("Bound");
+ expect(status().querySelector(".bg-success")).toBeNull();
+
+ state.larkInstallations = [{ status: "revoked", first_message_received_at: "2026-10-30T00:00:00Z" }];
+ rerender(<ChannelsTab />);
+ expect(status()).toHaveTextContent("Not connected");
+ expect(status().querySelector(".bg-success")).toBeNull();
+});
diff --git a/packages/views/settings/components/channels-tab.tsx b/packages/views/settings/components/channels-tab.tsx
index f717490cd3..3e781ac36e 100644
--- a/packages/views/settings/components/channels-tab.tsx
+++ b/packages/views/settings/components/channels-tab.tsx
@@ -38,6 +38,8 @@ interface ChannelEntry {
description: string;
content: ReactNode;
state: ConnectionState;
+ boundLabel?: string;
+ connectedLabel?: string;
}
// The IM channels soft-revoke: the row survives with status 'revoked', so a row
@@ -64,7 +66,13 @@ export function ChannelsTab() {
const lark = useQuery({
...larkInstallationsOptions(wsId),
enabled: canView,
- select: hasActiveInstallation,
+ select: (data) => {
+ const active = data.installations.filter((inst) => inst.status === "active");
+ return {
+ active: active.length > 0,
+ verified: active.some((inst) => !!inst.first_message_received_at),
+ };
+ },
});
const slack = useQuery({
...slackInstallationsOptions(wsId),
@@ -92,7 +100,9 @@ export function ChannelsTab() {
label: t(($) => $.lark.section_title),
description: t(($) => $.lark.page_description),
content: <LarkTab />,
- state: lark,
+ state: { ...lark, data: lark.data?.active },
+ boundLabel: lark.data?.verified ? undefined : t(($) => $.lark.bound_label),
+ connectedLabel: t(($) => $.lark.inbound_verified),
},
{
id: "slack",
@@ -179,7 +189,7 @@ export function ChannelsTab() {
<span className="text-body font-medium text-foreground">
{channel.label}
</span>{" "}
- <ConnectionBadge state={channel.state} />
+ <ConnectionBadge state={channel.state} boundLabel={channel.boundLabel} connectedLabel={channel.connectedLabel} />
</span>
<span className="mt-1 block text-caption leading-5 text-muted-foreground">
{channel.description}
@@ -196,7 +206,11 @@ export function ChannelsTab() {
);
}
-export function ConnectionBadge({ state }: { state: ConnectionState }) {
+export function ConnectionBadge({ state, boundLabel, connectedLabel }: {
+ state: ConnectionState;
+ boundLabel?: string;
+ connectedLabel?: string;
+}) {
const { t } = useT("settings");
const connected = !state.isError && !state.isPending && state.data === true;
const label = state.isError
@@ -204,16 +218,16 @@ export function ConnectionBadge({ state }: { state: ConnectionState }) {
: state.isPending
? t(($) => $.integrations.status_loading)
: connected
- ? t(($) => $.integrations.status_connected)
+ ? (boundLabel ?? connectedLabel ?? t(($) => $.integrations.status_connected))
: t(($) => $.integrations.status_not_connected);
return (
<span
className={cn(
"inline-flex items-center gap-1.5 text-caption",
- connected ? "text-success" : "text-muted-foreground",
+ connected && !boundLabel ? "text-success" : "text-muted-foreground",
)}
>
- {connected && (
+ {connected && !boundLabel && (
<span aria-hidden="true" className="size-1.5 rounded-full bg-success" />
)}
{label}
diff --git a/packages/views/settings/components/lark-tab.test.tsx b/packages/views/settings/components/lark-tab.test.tsx
index 1425582aff..cef9193f94 100644
--- a/packages/views/settings/components/lark-tab.test.tsx
+++ b/packages/views/settings/components/lark-tab.test.tsx
@@ -325,6 +325,7 @@ describe("LarkAgentBindButton (CTA gate)", () => {
// Disconnect action appears; the region-aware Manage link still points
// at the mainland host.
expect(screen.getByText("Feishu")).toBeTruthy();
+ expect(screen.getByText("Bound — awaiting message verification")).toBeTruthy();
expect(screen.getByTestId("lark-agent-bot-disconnect")).toBeTruthy();
const link = screen.getByRole("link", { name: /Manage in Feishu/i }) as HTMLAnchorElement;
expect(link.href).toBe("https://open.feishu.cn/app/cli_existing_app");
@@ -357,7 +358,7 @@ describe("LarkAgentBindButton (CTA gate)", () => {
render(<LarkAgentBindButton agentId="agent-1" agentName="Bot" />, {
wrapper: I18nWrapper,
});
- expect(screen.getByText(/Connected to Lark/i)).toBeTruthy();
+ expect(screen.getByText("Bound — awaiting message verification")).toBeTruthy();
const link = screen.getByRole("link", { name: /Manage in Lark/i }) as HTMLAnchorElement;
expect(link.href).toBe("https://open.larksuite.com/app/cli_lark_app");
});
@@ -790,3 +791,19 @@ describe("LarkTab connected bots list (agent identity rendering)", () => {
expect(screen.getByRole("button", { name: /Disconnect/i })).toBeTruthy();
});
});
+
+
+describe("Lark inbound verification display", () => {
+ it("updates the bound status when refreshed evidence arrives", () => {
+ const installation = { id: "proof", workspace_id: "workspace-1", agent_id: "agent-1", app_id: "app", bot_open_id: "bot", installer_user_id: "user-1", status: "active", installed_at: "2026-10-29T00:00:00Z", created_at: "2026-10-29T00:00:00Z", updated_at: "2026-10-29T00:00:00Z", first_message_received_at: null as string | null };
+ installationsRef.current.installations = [installation];
+ const { rerender } = render(<LarkAgentBindButton agentId="agent-1" agentName="Bot" />, { wrapper: I18nWrapper });
+ expect(screen.getByText("Bound — awaiting message verification")).toBeTruthy();
+ expect(screen.getByText(/Existing bindings may have no recorded verification yet/)).toBeTruthy();
+ installation.first_message_received_at = "2026-10-29T01:00:00Z";
+ rerender(<LarkAgentBindButton agentId="agent-1" agentName="Bot" />);
+ expect(screen.getByText("Message reception verified")).toBeTruthy();
+ expect(screen.getByText(/does not confirm ongoing connectivity/)).toBeTruthy();
+ expect(screen.queryByText("Bound — awaiting message verification")).toBeNull();
+ });
+});
diff --git a/packages/views/settings/components/lark-tab.tsx b/packages/views/settings/components/lark-tab.tsx
index db77b6888f..e0d24bfbab 100644
--- a/packages/views/settings/components/lark-tab.tsx
+++ b/packages/views/settings/components/lark-tab.tsx
@@ -206,6 +206,25 @@ export function LarkTab() {
);
}
+function LarkReceiptGuidance({
+ installation,
+ showStatus = true,
+}: {
+ installation: LarkInstallation;
+ showStatus?: boolean;
+}) {
+ const { t } = useT("settings");
+ const verified = !!installation.first_message_received_at;
+ return (
+ <div className="space-y-1 text-caption text-muted-foreground">
+ {showStatus && (
+ <p>{verified ? t(($) => $.lark.inbound_verified) : t(($) => $.lark.inbound_pending)}</p>
+ )}
+ <p>{verified ? t(($) => $.lark.inbound_verified_hint) : t(($) => $.lark.inbound_pending_hint)}</p>
+ </div>
+ );
+}
+
function InstallationRow({
installation,
canManage,
@@ -250,6 +269,7 @@ function InstallationRow({
</span>
)}
</p>
+ {isActive && <LarkReceiptGuidance installation={installation} />}
<p className="text-micro text-muted-foreground">
{t(($) => $.lark.installed_at_label, {
when: new Date(installation.installed_at).toLocaleString(locale),
@@ -452,7 +472,7 @@ export function LarkAgentBindButton({
// LarkAgentBotStatusRow is the compact, read-only connected affordance the
// agent inspector (left column) renders instead of the full badge. It shows
-// only the status — green dot, Feishu/Lark region chip, "Connected to Lark"
+// only the receipt status and Feishu/Lark region chip
// — and is a single full-width button that deep-links into the Integrations
// tab, where Manage / Disconnect live. Keeping the destructive action out of
// the always-visible sidebar means it exists in exactly one place.
@@ -476,13 +496,18 @@ function LarkAgentBotStatusRow({
)}
data-testid="lark-agent-bot-status"
>
- <span className="inline-block h-1.5 w-1.5 shrink-0 rounded-full bg-emerald-500" />
+ <span className={cn(
+ "inline-block h-1.5 w-1.5 shrink-0 rounded-full",
+ installation.first_message_received_at ? "bg-success" : "bg-muted-foreground",
+ )} />
<span className="rounded-xs bg-muted px-1.5 py-0.5 text-micro text-muted-foreground">
{installation.region === "lark"
? t(($) => $.lark.region_lark)
: t(($) => $.lark.region_feishu)}
</span>
- <span className="truncate">{t(($) => $.lark.agent_bot_connected_label)}</span>
+ <span className="truncate">{installation.first_message_received_at
+ ? t(($) => $.lark.inbound_verified)
+ : t(($) => $.lark.inbound_pending)}</span>
<ChevronRight className="ml-auto h-3.5 w-3.5 shrink-0" />
</button>
);
@@ -573,13 +598,18 @@ function LarkAgentBotConnectedBadge({
and stops message delivery. */}
<div className="flex items-center justify-between gap-3">
<span className="inline-flex min-w-0 items-center gap-2 text-caption text-muted-foreground">
- <span className="inline-block h-1.5 w-1.5 shrink-0 rounded-full bg-emerald-500" />
+ <span className={cn(
+ "inline-block h-1.5 w-1.5 shrink-0 rounded-full",
+ installation.first_message_received_at ? "bg-success" : "bg-muted-foreground",
+ )} />
<span className="rounded-xs bg-muted px-1.5 py-0.5 text-micro text-muted-foreground">
{installation.region === "lark"
? t(($) => $.lark.region_lark)
: t(($) => $.lark.region_feishu)}
</span>
- <span className="truncate">{t(($) => $.lark.agent_bot_connected_label)}</span>
+ <span className="truncate">{installation.first_message_received_at
+ ? t(($) => $.lark.inbound_verified)
+ : t(($) => $.lark.inbound_pending)}</span>
</span>
<TooltipHint label={t(($) => $.lark.agent_bot_disconnect_tooltip)}>
<Button
@@ -598,6 +628,8 @@ function LarkAgentBotConnectedBadge({
</TooltipHint>
</div>
+ <LarkReceiptGuidance installation={installation} showStatus={false} />
+
{/* Row 2: secondary "Manage in Lark" link to the Bot's dev-console
app page. Demoted below the status row so it no longer competes
with the primary connect/disconnect intents. Region-aware tooltip
@@ -619,13 +651,8 @@ function LarkAgentBotConnectedBadge({
: t(($) => $.lark.agent_bot_manage_link_feishu)}
</a>
- {/* Row 3: the check a silent Bot almost always needs (#8496). An app
- whose events go to a request URL instead of the long connection
- binds fine and shows exactly this badge while receiving nothing,
- and this row is where someone looks when the Bot stays quiet —
- the install dialog closes itself a beat after success. */}
+ {/* Keep troubleshooting reachable after the install dialog closes. */}
<p className="text-caption text-muted-foreground">
- {t(($) => $.lark.agent_bot_silent_hint)}{" "}
<a
href={larkDocsUrl(i18n.language)}
target="_blank"
diff --git a/server/cmd/server/router.go b/server/cmd/server/router.go
index 83f310cfe0..054d925fb1 100644
--- a/server/cmd/server/router.go
+++ b/server/cmd/server/router.go
@@ -702,6 +702,7 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus
// is bridge code — it will simply find no rows to update
// on a fresh deployment and exit. MUL-2671.
go lark.BackfillBotUnionIDs(context.Background(), cs, larkClient, installSvc, slog.Default())
+ go lark.BackfillLegacyInboundReceipts(context.Background(), cs, slog.Default())
// Upgrade repair for deployments that ran the whole
// integration against Lark international via the deployment-
@@ -2587,6 +2588,7 @@ func buildLarkConnector(installSvc *lark.InstallationService, apiClient lark.API
FrameDecoder: decoder,
Enricher: enricher,
CredentialsProvider: credsProvider,
+ InboundVerifier: installSvc,
Logger: slog.Default(),
})
if err != nil {
diff --git a/server/internal/handler/lark.go b/server/internal/handler/lark.go
index 2ee134be32..9930c13972 100644
--- a/server/internal/handler/lark.go
+++ b/server/internal/handler/lark.go
@@ -20,14 +20,15 @@ import (
// InstallationService.DecryptAppSecret server-side). Likewise, the WS
// lease columns are omitted; they are runtime state, not API surface.
type LarkInstallationResponse struct {
- ID string `json:"id"`
- WorkspaceID string `json:"workspace_id"`
- AgentID string `json:"agent_id"`
- AppID string `json:"app_id"`
- TenantKey *string `json:"tenant_key,omitempty"`
- BotOpenID string `json:"bot_open_id"`
- InstallerUserID string `json:"installer_user_id"`
- Status string `json:"status"`
+ ID string `json:"id"`
+ WorkspaceID string `json:"workspace_id"`
+ AgentID string `json:"agent_id"`
+ AppID string `json:"app_id"`
+ TenantKey *string `json:"tenant_key,omitempty"`
+ BotOpenID string `json:"bot_open_id"`
+ InstallerUserID string `json:"installer_user_id"`
+ Status string `json:"status"`
+ FirstMessageReceivedAt *time.Time `json:"first_message_received_at,omitempty"`
// Region is the Lark cloud this installation lives on: "feishu"
// (mainland) or "lark" (international). The UI uses it to render a
// badge and to build the correct "Manage in Lark" dev-console host.
@@ -39,17 +40,18 @@ type LarkInstallationResponse struct {
func larkInstallationToResponse(row lark.Installation) LarkInstallationResponse {
resp := LarkInstallationResponse{
- ID: uuidToString(row.ID),
- WorkspaceID: uuidToString(row.WorkspaceID),
- AgentID: uuidToString(row.AgentID),
- AppID: row.AppID,
- BotOpenID: row.BotOpenID,
- InstallerUserID: uuidToString(row.InstallerUserID),
- Status: row.Status,
- Region: row.Region,
- InstalledAt: row.InstalledAt.Time.UTC().Format(time.RFC3339),
- CreatedAt: row.CreatedAt.Time.UTC().Format(time.RFC3339),
- UpdatedAt: row.UpdatedAt.Time.UTC().Format(time.RFC3339),
+ FirstMessageReceivedAt: row.FirstMessageReceivedAt,
+ ID: uuidToString(row.ID),
+ WorkspaceID: uuidToString(row.WorkspaceID),
+ AgentID: uuidToString(row.AgentID),
+ AppID: row.AppID,
+ BotOpenID: row.BotOpenID,
+ InstallerUserID: uuidToString(row.InstallerUserID),
+ Status: row.Status,
+ Region: row.Region,
+ InstalledAt: row.InstalledAt.Time.UTC().Format(time.RFC3339),
+ CreatedAt: row.CreatedAt.Time.UTC().Format(time.RFC3339),
+ UpdatedAt: row.UpdatedAt.Time.UTC().Format(time.RFC3339),
}
if row.TenantKey.Valid {
tk := row.TenantKey.String
diff --git a/server/internal/handler/lark_test.go b/server/internal/handler/lark_test.go
index f537b74b5e..cd39fcd2bb 100644
--- a/server/internal/handler/lark_test.go
+++ b/server/internal/handler/lark_test.go
@@ -8,6 +8,7 @@ import (
"net/http/httptest"
"strings"
"testing"
+ "time"
"github.com/multica-ai/multica/server/internal/integrations/lark"
"github.com/multica-ai/multica/server/internal/util/secretbox"
@@ -469,3 +470,29 @@ RETURNING id
t.Fatalf("orphan revoke as workspace owner: want 204, got %d", code)
}
}
+
+func TestLarkInstallationReceiptWireShape(t *testing.T) {
+ now := time.Date(2026, 10, 29, 0, 0, 0, 123000000, time.UTC)
+ row := lark.Installation{AppSecretEncrypted: []byte("never expose"), BindingGeneration: "private-generation"}
+ check := func(want bool) {
+ t.Helper()
+ raw, err := json.Marshal(larkInstallationToResponse(row))
+ if err != nil {
+ t.Fatal(err)
+ }
+ var body map[string]any
+ if err := json.Unmarshal(raw, &body); err != nil {
+ t.Fatal(err)
+ }
+ _, present := body["first_message_received_at"]
+ if present != want {
+ t.Fatalf("receipt present=%v want %v", present, want)
+ }
+ if strings.Contains(string(raw), "private-generation") || strings.Contains(string(raw), "never expose") {
+ t.Fatal("installation internals exposed")
+ }
+ }
+ check(false)
+ row.FirstMessageReceivedAt = &now
+ check(true)
+}
diff --git a/server/internal/integrations/channel/channel.go b/server/internal/integrations/channel/channel.go
index 70c3d0f8bd..9e158ee4f1 100644
--- a/server/internal/integrations/channel/channel.go
+++ b/server/internal/integrations/channel/channel.go
@@ -91,7 +91,7 @@ type Config struct {
// in-tree does today, but Factory implementations should tolerate it
// rather than assume Valid). WeCom uses it to key its per-connection
// wsSender into a shared registry the OutboundReplier looks up by;
- // Feishu and Slack don't currently read it.
+ // Feishu also uses it to scope inbound receipt verification.
ID pgtype.UUID
// Handler is the shared inbound entry point the engine injects so the
diff --git a/server/internal/integrations/lark/channel_store.go b/server/internal/integrations/lark/channel_store.go
index 6012418ce7..50c7bc6ed3 100644
--- a/server/internal/integrations/lark/channel_store.go
+++ b/server/internal/integrations/lark/channel_store.go
@@ -17,6 +17,7 @@ import (
"context"
"errors"
+ "github.com/google/uuid"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgtype"
@@ -120,6 +121,7 @@ func (s *ChannelStore) ListActiveLarkInstallations(ctx context.Context) ([]Insta
func (s *ChannelStore) UpsertLarkInstallation(ctx context.Context, arg UpsertInstallationParams) (Installation, error) {
cfg, err := encodeInstallConfig(Installation{
+ BindingGeneration: uuid.NewString(),
AppID: arg.AppID,
AppSecretEncrypted: arg.AppSecretEncrypted,
TenantKey: arg.TenantKey,
@@ -185,31 +187,12 @@ func (s *ChannelStore) SetLarkInstallationStatus(ctx context.Context, arg SetIns
})
}
-// SetLarkInstallationBotUnionID folds bot_union_id into the JSONB config via a
-// read-modify-write through SetChannelInstallationConfig (channel_installation
-// has no dedicated union_id column). This is the operator union_id backfill,
-// keyed by id and effectively single-writer, so the non-atomic RMW is safe —
-// the same shape the channel.sql comment documents for this query.
+// SetLarkInstallationBotUnionID patches only identity metadata so a concurrent
+// inbound receipt or rebind cannot be overwritten with a stale config snapshot.
func (s *ChannelStore) SetLarkInstallationBotUnionID(ctx context.Context, arg SetInstallationBotUnionIDParams) error {
- row, err := s.Queries.GetChannelInstallation(ctx, db.GetChannelInstallationParams{
- ID: arg.ID,
- ChannelType: channelTypeFeishu,
- })
- if err != nil {
- return err
- }
- inst, err := installationFromRow(row)
- if err != nil {
- return err
- }
- inst.BotUnionID = arg.BotUnionID
- cfg, err := encodeInstallConfig(inst)
- if err != nil {
- return err
- }
- return s.Queries.SetChannelInstallationConfig(ctx, db.SetChannelInstallationConfigParams{
- ID: arg.ID,
- Config: cfg,
+ return s.Queries.SetFeishuInstallationBotUnionID(ctx, db.SetFeishuInstallationBotUnionIDParams{
+ ID: arg.ID,
+ BotUnionID: arg.BotUnionID.String,
})
}
diff --git a/server/internal/integrations/lark/feishu_channel.go b/server/internal/integrations/lark/feishu_channel.go
index 7b4ffa70ab..593ad93d2a 100644
--- a/server/internal/integrations/lark/feishu_channel.go
+++ b/server/internal/integrations/lark/feishu_channel.go
@@ -212,8 +212,9 @@ func newFeishuFactory(deps FeishuChannelDeps) channel.Factory {
// cfg.Raw is the per-installation config blob (the channel_installation
// .config JSONB): app_id, encrypted app_secret, tenant_key, region, ….
// We build a credentials-only Installation from it; the workspace /
- // agent identity is resolved per message by the Router, not needed here.
+ // agent identity is resolved per message by the Router; ID also scopes receipt verification.
inst, err := installationFromRow(db.ChannelInstallation{
+ ID: cfg.ID,
ChannelType: channelTypeFeishu,
Config: cfg.Raw,
})
@@ -317,12 +318,22 @@ var _ engine.LeaseStore = (*channelInstallationStore)(nil)
// channel_installation row into an opaque string. Any change to the platform
// config (Feishu rotates app_id / app_secret / region on re-install) flips the
// fingerprint and the Supervisor restarts the connection. The config JSONB
-// carries only the secret ciphertext (never plaintext), so hashing it is safe
-// and channel-agnostic — no platform field is read directly.
+// carries only the secret ciphertext (never plaintext). Feishu receipt
+// evidence is excluded because it does not change
+// credentials or routing.
func rowFingerprint(row db.ChannelInstallation) string {
h := sha256.New()
_, _ = h.Write([]byte(row.ChannelType))
_, _ = h.Write([]byte{0})
- _, _ = h.Write(row.Config)
+ config := row.Config
+ // Receipt evidence must not rotate an otherwise healthy connection.
+ if row.ChannelType == channelTypeFeishu {
+ var fields map[string]json.RawMessage
+ if json.Unmarshal(config, &fields) == nil {
+ delete(fields, "first_message_received_at")
+ config, _ = json.Marshal(fields)
+ }
+ }
+ _, _ = h.Write(config)
return hex.EncodeToString(h.Sum(nil))
}
diff --git a/server/internal/integrations/lark/feishu_channel_test.go b/server/internal/integrations/lark/feishu_channel_test.go
index 2cfd8dbc2a..d302598664 100644
--- a/server/internal/integrations/lark/feishu_channel_test.go
+++ b/server/internal/integrations/lark/feishu_channel_test.go
@@ -173,9 +173,12 @@ func buildFeishuChannel(t *testing.T, deps FeishuChannelDeps, cfg channel.Config
}
func TestFeishuFactory_DecodesConfigCredentials(t *testing.T) {
- cfg := channel.Config{Type: channel.TypeFeishu, Raw: feishuConfigJSON(t, "cli_app", "lark")}
+ cfg := channel.Config{ID: uuidFromString(t, "a1000000-0000-4000-8000-000000000001"), Type: channel.TypeFeishu, Raw: feishuConfigJSON(t, "cli_app", "lark")}
fc := buildFeishuChannel(t, FeishuChannelDeps{Connector: NewNoopConnector(nil)}, cfg)
+ if fc.inst.ID != cfg.ID {
+ t.Fatal("factory lost installation identity for receipt verification")
+ }
if fc.inst.AppID != "cli_app" {
t.Fatalf("app_id = %q, want cli_app", fc.inst.AppID)
}
diff --git a/server/internal/integrations/lark/inbound_verification.go b/server/internal/integrations/lark/inbound_verification.go
new file mode 100644
index 0000000000..9101cee975
--- /dev/null
+++ b/server/internal/integrations/lark/inbound_verification.go
@@ -0,0 +1,53 @@
+package lark
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+
+ "github.com/jackc/pgx/v5"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+)
+
+// InboundVerifier persists evidence that this binding received a message over WS.
+// It says nothing about ongoing liveness, routing, execution, or reply delivery.
+type InboundVerifier interface {
+ RecordInboundReceipt(context.Context, Installation, InboundMessage) error
+}
+
+func validReceiptMessage(inst Installation, msg InboundMessage) bool {
+ if msg.EventType != "im.message.receive_v1" || msg.EventID == "" ||
+ inst.AppID == "" || msg.AppID != inst.AppID || msg.MessageID == "" ||
+ msg.ChatID == "" || msg.SenderOpenID == "" || msg.MessageType == "" ||
+ (msg.ChatType != ChatTypeP2P && msg.ChatType != ChatTypeGroup) {
+ return false
+ }
+ var content map[string]json.RawMessage
+ return json.Unmarshal([]byte(msg.Content), &content) == nil && content != nil
+}
+
+func (s *InstallationService) RecordInboundReceipt(ctx context.Context, snapshot Installation, msg InboundMessage) error {
+ if !snapshot.ID.Valid || !validReceiptMessage(snapshot, msg) {
+ return nil
+ }
+ // The factory holds the installation ID and config snapshot, but workspace
+ // identity is resolved by the router. Resolve it here as well, then fence the
+ // write atomically against a rebind/revoke racing this read.
+ current, err := s.queries.GetLarkInstallation(ctx, snapshot.ID)
+ if errors.Is(err, pgx.ErrNoRows) {
+ return nil
+ }
+ if err != nil {
+ return err
+ }
+ if current.AppID != snapshot.AppID || current.BindingGeneration != snapshot.BindingGeneration ||
+ current.Status != string(InstallationActive) || current.FirstMessageReceivedAt != nil {
+ return nil
+ }
+ return s.queries.Queries.RecordFeishuInboundReceipt(ctx, db.RecordFeishuInboundReceiptParams{
+ ID: snapshot.ID,
+ WorkspaceID: current.WorkspaceID,
+ AppID: snapshot.AppID,
+ BindingGeneration: snapshot.BindingGeneration,
+ })
+}
diff --git a/server/internal/integrations/lark/inbound_verification_backfill.go b/server/internal/integrations/lark/inbound_verification_backfill.go
new file mode 100644
index 0000000000..a7a758f536
--- /dev/null
+++ b/server/internal/integrations/lark/inbound_verification_backfill.go
@@ -0,0 +1,54 @@
+package lark
+
+import (
+ "context"
+ "log/slog"
+ "time"
+)
+
+const (
+ legacyReceiptBatchSize = 100
+ legacyReceiptMaxBatches = 100
+ legacyReceiptTimeout = 30 * time.Second
+)
+
+type legacyReceiptBackfillStore interface {
+ BackfillLegacyFeishuInboundReceipts(context.Context, int32) (int64, error)
+}
+
+// BackfillLegacyInboundReceipts preserves positive evidence for old bindings at
+// rollout. Session routes are created on inbound contact. Only routes created
+// since the current install count; new generations always require live receipt.
+// At most 10,000 rows and 30 seconds are spent per boot. Remaining eligible rows
+// can be picked up on the next boot without overwriting existing evidence.
+func BackfillLegacyInboundReceipts(ctx context.Context, store *ChannelStore, log *slog.Logger) {
+ if log == nil {
+ log = slog.Default()
+ }
+ ctx, cancel := context.WithTimeout(ctx, legacyReceiptTimeout)
+ defer cancel()
+ rows, err := backfillLegacyInboundReceipts(ctx, store.Queries)
+ if err != nil {
+ log.Warn("lark receipt backfill incomplete", "rows", rows, "error", err)
+ return
+ }
+ log.Info("lark receipt backfill finished", "rows", rows, "batch_limit_reached", rows == legacyReceiptBatchSize*legacyReceiptMaxBatches)
+}
+
+func backfillLegacyInboundReceipts(ctx context.Context, store legacyReceiptBackfillStore) (int64, error) {
+ var rows int64
+ for batch := 0; batch < legacyReceiptMaxBatches; batch++ {
+ if err := ctx.Err(); err != nil {
+ return rows, err
+ }
+ n, err := store.BackfillLegacyFeishuInboundReceipts(ctx, legacyReceiptBatchSize)
+ if err != nil {
+ return rows, err
+ }
+ rows += n
+ if n < legacyReceiptBatchSize {
+ break
+ }
+ }
+ return rows, nil
+}
diff --git a/server/internal/integrations/lark/inbound_verification_backfill_test.go b/server/internal/integrations/lark/inbound_verification_backfill_test.go
new file mode 100644
index 0000000000..e3c494a3fd
--- /dev/null
+++ b/server/internal/integrations/lark/inbound_verification_backfill_test.go
@@ -0,0 +1,269 @@
+package lark
+
+import (
+ "context"
+ "encoding/json"
+ "os"
+ "testing"
+ "time"
+
+ "github.com/google/uuid"
+ "github.com/jackc/pgx/v5/pgxpool"
+ "github.com/multica-ai/multica/server/internal/testutil"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+)
+
+func legacyReceiptFixture(t *testing.T) (*pgxpool.Pool, *testutil.Fixture) {
+ t.Helper()
+ if os.Getenv("DATABASE_URL") == "" {
+ t.Skip("explicit disposable DATABASE_URL required")
+ }
+ pool := channelScopeTestDB(t)
+ return pool, testutil.New(pool, uuid.NewString(), uuid.NewString())
+}
+
+func receiptInstallation(t *testing.T, fx *testutil.Fixture, status, channel string, installed time.Time, config map[string]any) string {
+ t.Helper()
+ raw, err := json.Marshal(config)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return fx.Insert(t, "channel_installation", testutil.Cols{"workspace_id": fx.WorkspaceID, "agent_id": uuid.NewString(), "installer_user_id": fx.UserID, "channel_type": channel, "status": status, "installed_at": installed, "config": raw})
+}
+
+func receiptHistory(t *testing.T, fx *testutil.Fixture, id, channel string, at time.Time) {
+ t.Helper()
+ fx.Insert(t, "channel_chat_session_binding", testutil.Cols{"installation_id": id, "chat_session_id": uuid.NewString(), "channel_type": channel, "channel_chat_id": uuid.NewString(), "chat_type": "p2p", "created_at": at})
+}
+
+func receiptConfig(t *testing.T, pool *pgxpool.Pool, id string) map[string]any {
+ t.Helper()
+ var raw []byte
+ if err := pool.QueryRow(context.Background(), "SELECT config FROM channel_installation WHERE id=$1", id).Scan(&raw); err != nil {
+ t.Fatal(err)
+ }
+ var config map[string]any
+ if err := json.Unmarshal(raw, &config); err != nil {
+ t.Fatal(err)
+ }
+ return config
+}
+
+func TestLegacyReceiptBackfillEvidenceAndIdempotence(t *testing.T) {
+ pool, fx := legacyReceiptFixture(t)
+ q := db.New(pool)
+ installed := time.Date(2026, 10, 30, 0, 0, 0, 123456000, time.UTC)
+ for _, tc := range []struct {
+ name, status, channel, generation, receipt string
+ history []time.Time
+ historyChannel string
+ verified bool
+ }{
+ {name: "qualifying history", history: []time.Time{installed.Add(time.Minute), installed.Add(2 * time.Minute)}, verified: true},
+ {name: "exact install boundary", history: []time.Time{installed}, verified: true},
+ {name: "no history"},
+ {name: "history predates rebind", history: []time.Time{installed.Add(-time.Microsecond)}},
+ {name: "wrong channel history", history: []time.Time{installed}, historyChannel: "slack"},
+ {name: "revoked", status: "revoked", history: []time.Time{installed}},
+ {name: "other channel", channel: "slack", history: []time.Time{installed}},
+ {name: "new binding", generation: uuid.NewString(), history: []time.Time{installed}},
+ {name: "existing receipt", receipt: "2026-10-30T00:00:00Z", history: []time.Time{installed}},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ status, channel := tc.status, tc.channel
+ if status == "" {
+ status = "active"
+ }
+ if channel == "" {
+ channel = "feishu"
+ }
+ config := map[string]any{"app_id": "cli_" + uuid.NewString(), "region": "feishu", "unrelated": map[string]any{"preserve": true}}
+ if tc.generation != "" {
+ config["binding_generation"] = tc.generation
+ }
+ if tc.receipt != "" {
+ config["first_message_received_at"] = tc.receipt
+ }
+ id := receiptInstallation(t, fx, status, channel, installed, config)
+ historyChannel := tc.historyChannel
+ if historyChannel == "" {
+ historyChannel = channel
+ }
+ for _, at := range tc.history {
+ receiptHistory(t, fx, id, historyChannel, at)
+ }
+ // History for a different installation is never evidence for this one.
+ receiptHistory(t, fx, uuid.NewString(), channel, installed)
+ n, err := q.BackfillLegacyFeishuInboundReceipts(context.Background(), 100)
+ if err != nil {
+ t.Fatal(err)
+ }
+ want := int64(0)
+ if tc.verified {
+ want = 1
+ }
+ if n != want {
+ t.Fatalf("updated=%d want %d", n, want)
+ }
+ got := receiptConfig(t, pool, id)
+ if tc.verified {
+ at, err := time.Parse(time.RFC3339Nano, got["first_message_received_at"].(string))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !at.Equal(tc.history[0]) {
+ t.Fatalf("receipt=%s want historical %s", at, tc.history[0])
+ }
+ delete(got, "first_message_received_at")
+ }
+ gotJSON, _ := json.Marshal(got)
+ wantJSON, _ := json.Marshal(config)
+ if string(gotJSON) != string(wantJSON) {
+ t.Fatalf("config changed: %s want %s", gotJSON, wantJSON)
+ }
+ before := receiptConfig(t, pool, id)
+ n, err = q.BackfillLegacyFeishuInboundReceipts(context.Background(), 100)
+ if err != nil || n != 0 {
+ t.Fatalf("rerun=%d err=%v", n, err)
+ }
+ after := receiptConfig(t, pool, id)
+ beforeJSON, _ := json.Marshal(before)
+ afterJSON, _ := json.Marshal(after)
+ if string(beforeJSON) != string(afterJSON) {
+ t.Fatal("rerun overwrote evidence")
+ }
+ })
+ }
+}
+
+func TestLegacyReceiptBackfillBatchLimit(t *testing.T) {
+ pool, fx := legacyReceiptFixture(t)
+ installed := time.Date(2026, 10, 30, 0, 0, 0, 0, time.UTC)
+ for i := 0; i < 5; i++ {
+ id := receiptInstallation(t, fx, "active", "feishu", installed, map[string]any{"app_id": "cli_" + uuid.NewString()})
+ receiptHistory(t, fx, id, "feishu", installed)
+ }
+ q := db.New(pool)
+ for _, want := range []int64{2, 2, 1, 0} {
+ n, err := q.BackfillLegacyFeishuInboundReceipts(context.Background(), 2)
+ if err != nil || n != want {
+ t.Fatalf("batch updated=%d want %d err=%v", n, want, err)
+ }
+ }
+}
+
+func TestLegacyReceiptBackfillConcurrentWriters(t *testing.T) {
+ pool, fx := legacyReceiptFixture(t)
+ installed := time.Date(2026, 10, 30, 0, 0, 0, 0, time.UTC)
+ liveReceipt := installed.Add(time.Hour).Format(time.RFC3339Nano)
+ for _, tc := range []struct {
+ name, update string
+ want int64
+ }{
+ {"rebind", `config=config || '{"binding_generation":"new"}'::jsonb, installed_at=installed_at+interval '1 second'`, 0},
+ {"legacy reinstall", `installed_at=installed_at+interval '1 second'`, 0},
+ {"revocation", `status='revoked'`, 0},
+ {"live receipt", `config=jsonb_set(config,'{first_message_received_at}','"` + liveReceipt + `"'::jsonb)`, 0},
+ {"metadata", `config=jsonb_set(config,'{bot_union_id}','"on_keep"'::jsonb)`, 1},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ id := receiptInstallation(t, fx, "active", "feishu", installed, map[string]any{"app_id": "cli_" + uuid.NewString()})
+ receiptHistory(t, fx, id, "feishu", installed)
+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
+ defer cancel()
+ worker, err := pool.Acquire(ctx)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer worker.Release()
+ pid := worker.Conn().PgConn().PID()
+ tx, err := pool.Begin(ctx)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer tx.Rollback(context.Background())
+ // The rollout statement sees old eligibility, then waits on this uncommitted
+ // writer. Rechecking after the lock is granted must use the committed state.
+ if _, err := tx.Exec(ctx, "UPDATE channel_installation SET "+tc.update+" WHERE id=$1", id); err != nil {
+ t.Fatal(err)
+ }
+ type result struct {
+ n int64
+ err error
+ }
+ done := make(chan result, 1)
+ go func() { n, err := db.New(worker).BackfillLegacyFeishuInboundReceipts(ctx, 100); done <- result{n, err} }()
+ blocked := false
+ for deadline := time.Now().Add(2 * time.Second); time.Now().Before(deadline); {
+ if err := pool.QueryRow(ctx, "SELECT COALESCE(wait_event_type='Lock',false) FROM pg_stat_activity WHERE pid=$1", pid).Scan(&blocked); err != nil {
+ t.Fatal(err)
+ }
+ if blocked {
+ break
+ }
+ time.Sleep(5 * time.Millisecond)
+ }
+ if !blocked {
+ _ = tx.Rollback(ctx)
+ <-done
+ t.Fatal("backfill did not reach the fixture row lock")
+ }
+ if err := tx.Commit(ctx); err != nil {
+ t.Fatal(err)
+ }
+ got := <-done
+ if got.err != nil || got.n != tc.want {
+ t.Fatalf("updated=%d want %d err=%v", got.n, tc.want, got.err)
+ }
+ config := receiptConfig(t, pool, id)
+ switch tc.name {
+ case "metadata":
+ if config["bot_union_id"] != "on_keep" || config["first_message_received_at"] == nil {
+ t.Fatal("lost concurrent metadata or receipt")
+ }
+ case "live receipt":
+ if config["first_message_received_at"] != liveReceipt {
+ t.Fatal("overwrote live receipt")
+ }
+ default:
+ if config["first_message_received_at"] != nil {
+ t.Fatal("old history verified changed binding")
+ }
+ }
+ })
+ }
+}
+
+type legacyBackfillFunc func(context.Context, int32) (int64, error)
+
+func (f legacyBackfillFunc) BackfillLegacyFeishuInboundReceipts(ctx context.Context, batch int32) (int64, error) {
+ return f(ctx, batch)
+}
+
+func TestLegacyReceiptRolloutBounds(t *testing.T) {
+ calls := 0
+ store := legacyBackfillFunc(func(_ context.Context, batch int32) (int64, error) {
+ calls++
+ if batch != legacyReceiptBatchSize {
+ t.Fatalf("unbounded batch %d", batch)
+ }
+ return int64(batch), nil
+ })
+ rows, err := backfillLegacyInboundReceipts(context.Background(), store)
+ if err != nil || calls != legacyReceiptMaxBatches || rows != legacyReceiptBatchSize*legacyReceiptMaxBatches {
+ t.Fatalf("calls=%d rows=%d err=%v", calls, rows, err)
+ }
+ ctx, cancel := context.WithCancel(context.Background())
+ cancel()
+ _, err = backfillLegacyInboundReceipts(ctx, store)
+ if err != context.Canceled || calls != legacyReceiptMaxBatches {
+ t.Fatal("cancellation did not stop rollout")
+ }
+ calls = 0
+ failure := context.DeadlineExceeded
+ store = legacyBackfillFunc(func(context.Context, int32) (int64, error) { calls++; return 0, failure })
+ _, err = backfillLegacyInboundReceipts(context.Background(), store)
+ if err != failure || calls != 1 {
+ t.Fatal("retried failed batch without a bound")
+ }
+}
diff --git a/server/internal/integrations/lark/inbound_verification_test.go b/server/internal/integrations/lark/inbound_verification_test.go
new file mode 100644
index 0000000000..d909789d1b
--- /dev/null
+++ b/server/internal/integrations/lark/inbound_verification_test.go
@@ -0,0 +1,375 @@
+package lark
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "os"
+ "testing"
+ "time"
+
+ "github.com/google/uuid"
+ "github.com/jackc/pgx/v5/pgtype"
+ "github.com/multica-ai/multica/server/internal/testutil"
+ "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"
+)
+
+func receiptMessage() InboundMessage {
+ return InboundMessage{EventType: "im.message.receive_v1", EventID: "ev-1", AppID: "cli_receipt", MessageID: "om-1", ChatID: "oc-1", ChatType: ChatTypeGroup, SenderOpenID: "ou-1", MessageType: "text", Content: `{"text":"hello"}`}
+}
+
+func TestReceiptMessageValidation(t *testing.T) {
+ inst := Installation{AppID: "cli_receipt"}
+ for _, tc := range []struct {
+ name string
+ mutate func(*InboundMessage)
+ }{
+ {"other app", func(m *InboundMessage) { m.AppID = "other" }},
+ {"no app", func(m *InboundMessage) { m.AppID = "" }},
+ {"other event", func(m *InboundMessage) { m.EventType = "card.action.trigger" }},
+ {"no event id", func(m *InboundMessage) { m.EventID = "" }},
+ {"no message id", func(m *InboundMessage) { m.MessageID = "" }},
+ {"no chat", func(m *InboundMessage) { m.ChatID = "" }},
+ {"no sender", func(m *InboundMessage) { m.SenderOpenID = "" }},
+ {"no message type", func(m *InboundMessage) { m.MessageType = "" }},
+ {"unknown chat", func(m *InboundMessage) { m.ChatType = "unknown" }},
+ {"broken content", func(m *InboundMessage) { m.Content = "{" }},
+ {"null content", func(m *InboundMessage) { m.Content = "null" }},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ m := receiptMessage()
+ tc.mutate(&m)
+ if validReceiptMessage(inst, m) {
+ t.Fatal("invalid event accepted as evidence")
+ }
+ })
+ }
+ if !validReceiptMessage(inst, receiptMessage()) {
+ t.Fatal("unaddressed group message should prove receipt")
+ }
+}
+
+type receiptVerifierFunc func(context.Context, Installation, InboundMessage) error
+
+func (f receiptVerifierFunc) RecordInboundReceipt(ctx context.Context, inst Installation, msg InboundMessage) error {
+ return f(ctx, inst, msg)
+}
+
+func TestWSReceiptBeforeRoutingAndWriteFailureDoesNotChangeACK(t *testing.T) {
+ for _, fail := range []bool{false, true} {
+ t.Run(map[bool]string{false: "success", true: "write failure"}[fail], func(t *testing.T) {
+ conn := newFakeWSConn()
+ c := quietConnector(t, conn, NewLarkJSONFrameDecoder(), time.Hour)
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+ calls := 0
+ c.cfg.InboundVerifier = receiptVerifierFunc(func(ctx context.Context, inst Installation, msg InboundMessage) error {
+ calls++
+ if _, ok := ctx.Deadline(); !ok {
+ t.Error("unbounded verification write")
+ }
+ if fail {
+ return errors.New("database down")
+ }
+ return nil
+ })
+ // Control frames, unknown events and malformed events cannot verify receipt.
+ conn.Push(NewPongFrame(7).Marshal())
+ pushDataFrame(conn, []byte(`{"header":{"event_type":"card.action.trigger"}}`), "other")
+ pushDataFrame(conn, []byte(`{"header":{"event_type":"im.message.receive_v1"},"event":{}}`), "bad")
+ msg := receiptMessage()
+ payload, _ := json.Marshal(map[string]any{"schema": "2.0", "header": map[string]any{"event_type": msg.EventType, "event_id": msg.EventID, "app_id": msg.AppID}, "event": map[string]any{"sender": map[string]any{"sender_id": map[string]string{"open_id": string(msg.SenderOpenID)}}, "message": map[string]string{"message_id": msg.MessageID, "chat_id": string(msg.ChatID), "chat_type": "group", "message_type": "text", "content": msg.Content}}})
+ pushDataFrame(conn, payload, "valid1")
+ pushDataFrame(conn, payload, "duplicate")
+ emits := 0
+ done := make(chan error, 1)
+ go func() {
+ done <- c.Run(ctx, Installation{AppID: msg.AppID}, func(context.Context, InboundMessage) (DispatchResult, error) {
+ emits++
+ if emits > 1 && calls == 0 {
+ t.Error("valid receipt not recorded before routing")
+ }
+ if emits == 3 {
+ cancel()
+ }
+ return DispatchResult{}, nil
+ })
+ }()
+ select {
+ case err := <-done:
+ if err != nil {
+ t.Fatal(err)
+ }
+ case <-time.After(3 * time.Second):
+ t.Fatal("connector stuck")
+ }
+ want := 1
+ if fail {
+ want = 2
+ }
+ if calls != want {
+ t.Fatalf("verification calls=%d want %d", calls, want)
+ }
+ // All data frames, including the business-filtered and duplicate messages,
+ // retain the connector's normal success ACK behavior.
+ if got := len(conn.snapshot()); got != 4 {
+ t.Fatalf("ACK count=%d want 4", got)
+ }
+ for _, raw := range conn.snapshot() {
+ f, err := UnmarshalFrame(raw)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var ack struct {
+ Code int `json:"code"`
+ }
+ _ = json.Unmarshal(f.Payload, &ack)
+ if f.Method == FrameMethodData && ack.Code != 200 {
+ t.Fatalf("unexpected ACK %s", f.Payload)
+ }
+ }
+ })
+ }
+}
+
+func TestInboundReceiptDatabaseGenerationAndScope(t *testing.T) {
+ if os.Getenv("DATABASE_URL") == "" {
+ t.Skip("explicit disposable DATABASE_URL required")
+ }
+ pool := channelScopeTestDB(t)
+ fx := testutil.New(pool, "", "")
+ suffix := uuid.NewString()
+ fx.UserID = fx.User(t, "Receipt test", "receipt-"+suffix+"@example.invalid")
+ fx.WorkspaceID = fx.Workspace(t, "Receipt test", "receipt-"+suffix)
+ runtime := fx.Runtime(t, "Receipt runtime")
+ agent := fx.Agent(t, "Receipt agent", runtime)
+ box, err := secretbox.New(make([]byte, 32))
+ if err != nil {
+ t.Fatal(err)
+ }
+ svc, err := NewInstallationService(db.New(pool), box)
+ if err != nil {
+ t.Fatal(err)
+ }
+ p := InstallationParams{WorkspaceID: util.MustParseUUID(fx.WorkspaceID), AgentID: util.MustParseUUID(agent), InstallerUserID: util.MustParseUUID(fx.UserID), AppID: "cli_receipt_" + suffix, AppSecret: "test", BotOpenID: "ou_bot"}
+ ctx := context.Background()
+ inst, err := svc.Upsert(ctx, p)
+ if err != nil {
+ t.Fatal(err)
+ }
+ fx.Cleanup(t, "DELETE FROM channel_installation WHERE id=$1", inst.ID)
+ read := func() Installation {
+ t.Helper()
+ got, err := svc.GetInWorkspace(ctx, inst.ID, p.WorkspaceID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return got
+ }
+ record := func(snapshot Installation) {
+ t.Helper()
+ msg := receiptMessage()
+ msg.AppID = snapshot.AppID
+ if err := svc.RecordInboundReceipt(ctx, snapshot, msg); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if inst.Status != "active" || inst.FirstMessageReceivedAt != nil || inst.BindingGeneration == "" {
+ t.Fatal("new install should be active, pending verification with a generation")
+ }
+ // No arrival (including GetBotInfo/install success) must leave no evidence.
+ if read().FirstMessageReceivedAt != nil {
+ t.Fatal("silent connection marked verified")
+ }
+ record(inst)
+ first := read()
+ if first.FirstMessageReceivedAt == nil {
+ t.Fatal("valid receipt not persisted")
+ }
+ // Block the metadata update after its read (the former RMW path), then
+ // record receipt while holding the row lock. Its eventual update must merge
+ // the latest config rather than erase the arrival or binding generation.
+ fx.Exec(t, "UPDATE channel_installation SET config=config-'first_message_received_at' WHERE id=$1", inst.ID)
+ metadataConn, err := pool.Acquire(ctx)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer metadataConn.Release()
+ tx, err := pool.Begin(ctx)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer tx.Rollback(ctx)
+ if _, err := tx.Exec(ctx, "SELECT id FROM channel_installation WHERE id=$1 FOR UPDATE", inst.ID); err != nil {
+ t.Fatal(err)
+ }
+ metadataDone := make(chan error, 1)
+ metadataCtx, cancelMetadata := context.WithTimeout(ctx, 3*time.Second)
+ defer cancelMetadata()
+ go func() {
+ metadataDone <- NewChannelStore(db.New(metadataConn)).SetLarkInstallationBotUnionID(metadataCtx, SetInstallationBotUnionIDParams{ID: inst.ID, BotUnionID: pgtype.Text{String: "on_bot", Valid: true}})
+ }()
+ blocked := false
+ for deadline := time.Now().Add(time.Second); time.Now().Before(deadline); {
+ if err := pool.QueryRow(ctx, "SELECT COALESCE(wait_event_type='Lock',false) FROM pg_stat_activity WHERE pid=$1", metadataConn.Conn().PgConn().PID()).Scan(&blocked); err != nil {
+ t.Fatal(err)
+ }
+ if blocked {
+ break
+ }
+ time.Sleep(5 * time.Millisecond)
+ }
+ if !blocked {
+ _ = tx.Rollback(ctx)
+ <-metadataDone
+ t.Fatal("metadata update did not block on fixture row lock")
+ }
+ if err := db.New(tx).RecordFeishuInboundReceipt(ctx, db.RecordFeishuInboundReceiptParams{ID: inst.ID, WorkspaceID: p.WorkspaceID, AppID: inst.AppID, BindingGeneration: inst.BindingGeneration}); err != nil {
+ t.Fatal(err)
+ }
+ if err := tx.Commit(ctx); err != nil {
+ t.Fatal(err)
+ }
+ if err := <-metadataDone; err != nil {
+ t.Fatal(err)
+ }
+ first = read()
+ if first.FirstMessageReceivedAt == nil || first.BindingGeneration != inst.BindingGeneration {
+ t.Fatal("concurrent identity backfill lost receipt or generation")
+ }
+
+ record(inst)
+ if !read().FirstMessageReceivedAt.Equal(*first.FirstMessageReceivedAt) {
+ t.Fatal("duplicate changed first receipt")
+ }
+ rebound, err := svc.Upsert(ctx, p)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if rebound.ID != inst.ID || rebound.BindingGeneration == inst.BindingGeneration || rebound.FirstMessageReceivedAt != nil {
+ t.Fatal("rebind did not reset receipt and rotate generation")
+ }
+ record(inst)
+ if read().FirstMessageReceivedAt != nil {
+ t.Fatal("late old socket verified new binding")
+ }
+ // Exercise the SQL fence directly, as if a rebind/revoke raced the read.
+ q := db.New(pool)
+ stale := db.RecordFeishuInboundReceiptParams{ID: inst.ID, WorkspaceID: p.WorkspaceID, AppID: inst.AppID, BindingGeneration: inst.BindingGeneration}
+ if err := q.RecordFeishuInboundReceipt(ctx, stale); err != nil {
+ t.Fatal(err)
+ }
+ if read().FirstMessageReceivedAt != nil {
+ t.Fatal("atomic generation fence failed")
+ }
+ stale.BindingGeneration = rebound.BindingGeneration
+ stale.WorkspaceID = util.MustParseUUID(uuid.NewString())
+ if err := q.RecordFeishuInboundReceipt(ctx, stale); err != nil {
+ t.Fatal(err)
+ }
+ if read().FirstMessageReceivedAt != nil {
+ t.Fatal("workspace fence failed")
+ }
+ stale.WorkspaceID = p.WorkspaceID
+ stale.AppID = "other"
+ if err := q.RecordFeishuInboundReceipt(ctx, stale); err != nil {
+ t.Fatal(err)
+ }
+ if read().FirstMessageReceivedAt != nil {
+ t.Fatal("app fence failed")
+ }
+ if err := svc.Revoke(ctx, inst.ID); err != nil {
+ t.Fatal(err)
+ }
+ record(rebound)
+ stale.AppID = p.AppID
+ if err := q.RecordFeishuInboundReceipt(ctx, stale); err != nil {
+ t.Fatal(err)
+ }
+ if read().FirstMessageReceivedAt != nil {
+ t.Fatal("revoked binding verified")
+ }
+ // The query must also reject another channel even if its app matches.
+ fx.Exec(t, "UPDATE channel_installation SET status='active', channel_type='slack' WHERE id=$1", inst.ID)
+ if err := q.RecordFeishuInboundReceipt(ctx, stale); err != nil {
+ t.Fatal(err)
+ }
+ var marked bool
+ if err := pool.QueryRow(ctx, "SELECT config ? 'first_message_received_at' FROM channel_installation WHERE id=$1", inst.ID).Scan(&marked); err != nil {
+ t.Fatal(err)
+ }
+ if marked {
+ t.Fatal("another channel was marked verified")
+ }
+ fx.Exec(t, "UPDATE channel_installation SET channel_type='feishu' WHERE id=$1", inst.ID)
+ // Existing installs have no generation/evidence; a legacy socket can verify
+ // its own binding, but cannot verify the next rebind's nonempty generation.
+ fx.Exec(t, "UPDATE channel_installation SET status='active', config=config-'binding_generation' WHERE id=$1", inst.ID)
+ legacy := read()
+ record(legacy)
+ if read().FirstMessageReceivedAt == nil {
+ t.Fatal("legacy binding cannot verify")
+ }
+ inst, err = svc.Upsert(ctx, p)
+ if err != nil {
+ t.Fatal(err)
+ }
+ record(legacy)
+ if read().FirstMessageReceivedAt != nil {
+ t.Fatal("legacy socket verified new binding")
+ }
+ record(inst)
+ if read().FirstMessageReceivedAt == nil {
+ t.Fatal("current binding could not verify after stale callback")
+ }
+}
+
+func TestReceiptDoesNotRotateConnectionButRebindDoes(t *testing.T) {
+ row := db.ChannelInstallation{ChannelType: channelTypeFeishu, Config: []byte(`{"app_id":"app","binding_generation":"one"}`)}
+ before := rowFingerprint(row)
+ row.Config = []byte(`{"binding_generation":"one","first_message_received_at":"2026-10-29T00:00:00Z","app_id":"app"}`)
+ if rowFingerprint(row) != before {
+ t.Fatal("receipt evidence rotates healthy connection")
+ }
+ row.Config = []byte(`{"app_id":"app","binding_generation":"two"}`)
+ if rowFingerprint(row) == before {
+ t.Fatal("rebind did not rotate connection")
+ }
+}
+
+func TestWSReceiptSurvivesDispatchFailure(t *testing.T) {
+ conn := newFakeWSConn()
+ msg := receiptMessage()
+ c := quietConnector(t, conn, FrameDecoderFunc(func([]byte, Installation) (InboundMessage, bool, error) { return msg, true, nil }), time.Hour)
+ recorded := false
+ c.cfg.InboundVerifier = receiptVerifierFunc(func(context.Context, Installation, InboundMessage) error { recorded = true; return nil })
+ pushDataFrame(conn, []byte(`{}`), "valid")
+ err := c.Run(context.Background(), Installation{AppID: msg.AppID}, func(context.Context, InboundMessage) (DispatchResult, error) {
+ if !recorded {
+ t.Error("routing ran before receipt was recorded")
+ }
+ return DispatchResult{}, errors.New("dispatch failed")
+ })
+ if err == nil || !recorded {
+ t.Fatal("routing failure lost receipt evidence")
+ }
+ writes := conn.snapshot()
+ if len(writes) != 1 {
+ t.Fatalf("expected one NACK, got %d writes", len(writes))
+ }
+ f, err := UnmarshalFrame(writes[0])
+ if err != nil {
+ t.Fatal(err)
+ }
+ var ack struct {
+ Code int `json:"code"`
+ }
+ if err := json.Unmarshal(f.Payload, &ack); err != nil {
+ t.Fatal(err)
+ }
+ if ack.Code != 500 {
+ t.Fatalf("dispatch failure ACK code %d want 500", ack.Code)
+ }
+}
diff --git a/server/internal/integrations/lark/store.go b/server/internal/integrations/lark/store.go
index 20809b2f0e..54892d4980 100644
--- a/server/internal/integrations/lark/store.go
+++ b/server/internal/integrations/lark/store.go
@@ -28,6 +28,7 @@ import (
"encoding/json"
"fmt"
"strings"
+ "time"
"github.com/jackc/pgx/v5/pgtype"
@@ -40,22 +41,24 @@ import (
// (AppID, AppSecretEncrypted, TenantKey, BotOpenID, BotUnionID, Region) come
// from the JSONB config; the rest are flat columns.
type Installation struct {
- ID pgtype.UUID
- WorkspaceID pgtype.UUID
- AgentID pgtype.UUID
- AppID string
- AppSecretEncrypted []byte
- TenantKey pgtype.Text
- BotOpenID string
- InstallerUserID pgtype.UUID
- Status string
- WsLeaseToken pgtype.Text
- WsLeaseExpiresAt pgtype.Timestamptz
- InstalledAt pgtype.Timestamptz
- CreatedAt pgtype.Timestamptz
- UpdatedAt pgtype.Timestamptz
- BotUnionID pgtype.Text
- Region string
+ BindingGeneration string
+ FirstMessageReceivedAt *time.Time
+ ID pgtype.UUID
+ WorkspaceID pgtype.UUID
+ AgentID pgtype.UUID
+ AppID string
+ AppSecretEncrypted []byte
+ TenantKey pgtype.Text
+ BotOpenID string
+ InstallerUserID pgtype.UUID
+ Status string
+ WsLeaseToken pgtype.Text
+ WsLeaseExpiresAt pgtype.Timestamptz
+ InstalledAt pgtype.Timestamptz
+ CreatedAt pgtype.Timestamptz
+ UpdatedAt pgtype.Timestamptz
+ BotUnionID pgtype.Text
+ Region string
}
// UserBinding is the flat view of a channel_user_binding row. ChannelUserID is
@@ -132,12 +135,14 @@ type OutboundCardMessage struct {
// rather than as a json []byte field, so MIME-wrapped base64 from the SQL
// backfill round-trips too. omitempty mirrors the migration's jsonb_strip_nulls.
type feishuInstallConfig struct {
- AppID string `json:"app_id"`
- AppSecretEncrypted string `json:"app_secret_encrypted,omitempty"`
- TenantKey string `json:"tenant_key,omitempty"`
- BotOpenID string `json:"bot_open_id,omitempty"`
- BotUnionID string `json:"bot_union_id,omitempty"`
- Region string `json:"region,omitempty"`
+ BindingGeneration string `json:"binding_generation,omitempty"`
+ FirstMessageReceivedAt *time.Time `json:"first_message_received_at,omitempty"`
+ AppID string `json:"app_id"`
+ AppSecretEncrypted string `json:"app_secret_encrypted,omitempty"`
+ TenantKey string `json:"tenant_key,omitempty"`
+ BotOpenID string `json:"bot_open_id,omitempty"`
+ BotUnionID string `json:"bot_union_id,omitempty"`
+ Region string `json:"region,omitempty"`
}
// feishuBindingConfig is the JSON shape of channel_user_binding.config.
@@ -159,22 +164,24 @@ func installationFromRow(row db.ChannelInstallation) (Installation, error) {
return Installation{}, fmt.Errorf("decode app_secret_encrypted: %w", err)
}
return Installation{
- ID: row.ID,
- WorkspaceID: row.WorkspaceID,
- AgentID: row.AgentID,
- AppID: cfg.AppID,
- AppSecretEncrypted: secret,
- TenantKey: textOrNull(cfg.TenantKey),
- BotOpenID: cfg.BotOpenID,
- InstallerUserID: row.InstallerUserID,
- Status: row.Status,
- WsLeaseToken: row.WsLeaseToken,
- WsLeaseExpiresAt: row.WsLeaseExpiresAt,
- InstalledAt: row.InstalledAt,
- CreatedAt: row.CreatedAt,
- UpdatedAt: row.UpdatedAt,
- BotUnionID: textOrNull(cfg.BotUnionID),
- Region: cfg.Region,
+ BindingGeneration: cfg.BindingGeneration,
+ FirstMessageReceivedAt: cfg.FirstMessageReceivedAt,
+ ID: row.ID,
+ WorkspaceID: row.WorkspaceID,
+ AgentID: row.AgentID,
+ AppID: cfg.AppID,
+ AppSecretEncrypted: secret,
+ TenantKey: textOrNull(cfg.TenantKey),
+ BotOpenID: cfg.BotOpenID,
+ InstallerUserID: row.InstallerUserID,
+ Status: row.Status,
+ WsLeaseToken: row.WsLeaseToken,
+ WsLeaseExpiresAt: row.WsLeaseExpiresAt,
+ InstalledAt: row.InstalledAt,
+ CreatedAt: row.CreatedAt,
+ UpdatedAt: row.UpdatedAt,
+ BotUnionID: textOrNull(cfg.BotUnionID),
+ Region: cfg.Region,
}, nil
}
@@ -182,11 +189,13 @@ func installationFromRow(row db.ChannelInstallation) (Installation, error) {
// feishu fields of an Installation. The secret is emitted as unwrapped base64.
func encodeInstallConfig(inst Installation) ([]byte, error) {
cfg := feishuInstallConfig{
- AppID: inst.AppID,
- TenantKey: inst.TenantKey.String,
- BotOpenID: inst.BotOpenID,
- BotUnionID: inst.BotUnionID.String,
- Region: inst.Region,
+ BindingGeneration: inst.BindingGeneration,
+ FirstMessageReceivedAt: inst.FirstMessageReceivedAt,
+ AppID: inst.AppID,
+ TenantKey: inst.TenantKey.String,
+ BotOpenID: inst.BotOpenID,
+ BotUnionID: inst.BotUnionID.String,
+ Region: inst.Region,
}
if len(inst.AppSecretEncrypted) > 0 {
cfg.AppSecretEncrypted = base64.StdEncoding.EncodeToString(inst.AppSecretEncrypted)
diff --git a/server/internal/integrations/lark/ws_connector.go b/server/internal/integrations/lark/ws_connector.go
index 9590d37a15..04b3d5aa61 100644
--- a/server/internal/integrations/lark/ws_connector.go
+++ b/server/internal/integrations/lark/ws_connector.go
@@ -61,6 +61,10 @@ type WSConnectorConfig struct {
// disables enrichment (the decoded body is emitted as-is).
Enricher Enricher
+ // InboundVerifier records receipt evidence independently of business routing.
+ // A failed write must not change dispatch or acknowledgement behavior.
+ InboundVerifier InboundVerifier
+
// EnrichTimeout caps a single message's enrichment (at most two
// GetMessage calls). It MUST stay well under Lark's ~3s long-conn
// ACK window, since enrichment runs before the frame is ACKed.
@@ -226,6 +230,7 @@ func (c *WSLongConnConnector) Run(ctx context.Context, inst Installation, emit E
// type once per connection rather than once per frame. Read-loop-local:
// no lock, and a reconnect re-reports.
reportedDrops := make(map[string]struct{})
+ receiptRecorded := false
// Ping loop: app-layer binary ping frames at the server's PingInterval.
pingDone := make(chan struct{})
@@ -398,6 +403,19 @@ func (c *WSLongConnConnector) Run(ctx context.Context, inst Installation, emit E
continue
}
+ if !receiptRecorded && c.cfg.InboundVerifier != nil &&
+ frame.Method == FrameMethodData && frame.HeaderValue(FrameHeaderTypeKey) == FrameHeaderTypeEvent &&
+ validReceiptMessage(inst, msg) {
+ verifyCtx, cancelVerify := context.WithTimeout(ctx, 250*time.Millisecond)
+ verifyErr := c.cfg.InboundVerifier.RecordInboundReceipt(verifyCtx, inst, msg)
+ cancelVerify()
+ if verifyErr != nil {
+ log.Warn("lark ws connector: record inbound receipt failed", "err", verifyErr.Error())
+ } else {
+ receiptRecorded = true
+ }
+ }
+
// Enrich the decoded body with explicitly-attached context
// (quoted reply / forwarded bundle) before emitting. This runs
// before the frame ACK, so it is bounded by EnrichTimeout and
diff --git a/server/pkg/db/generated/channel.sql.go b/server/pkg/db/generated/channel.sql.go
index b8f7dc1a6e..c929e6a406 100644
--- a/server/pkg/db/generated/channel.sql.go
+++ b/server/pkg/db/generated/channel.sql.go
@@ -3263,9 +3263,8 @@ type SetChannelInstallationConfigParams struct {
Config []byte `json:"config"`
}
-// Replaces the whole config blob for one installation. Used by the
-// operator backfills (e.g. setting a freshly-fetched bot_union_id) that
-// read-modify-write the JSON in Go and persist it back atomically by id.
+// Replaces the whole config blob for one installation. Prefer field-level
+// patches for metadata that can change concurrently with receipt evidence.
func (q *Queries) SetChannelInstallationConfig(ctx context.Context, arg SetChannelInstallationConfigParams) error {
_, err := q.db.Exec(ctx, setChannelInstallationConfig, arg.ID, arg.Config)
return err
diff --git a/server/pkg/db/generated/feishu_verification.sql.go b/server/pkg/db/generated/feishu_verification.sql.go
new file mode 100644
index 0000000000..2ff61cfc3b
--- /dev/null
+++ b/server/pkg/db/generated/feishu_verification.sql.go
@@ -0,0 +1,99 @@
+// Code generated by sqlc. DO NOT EDIT.
+// versions:
+// sqlc v1.31.1
+// source: feishu_verification.sql
+
+package db
+
+import (
+ "context"
+
+ "github.com/jackc/pgx/v5/pgtype"
+)
+
+const backfillLegacyFeishuInboundReceipts = `-- name: BackfillLegacyFeishuInboundReceipts :execrows
+WITH evidence AS MATERIALIZED (
+ SELECT installation.id, installation.installed_at, min(binding.created_at) AS received_at
+ FROM channel_installation AS installation
+ JOIN channel_chat_session_binding AS binding
+ ON binding.installation_id = installation.id
+ AND binding.channel_type = installation.channel_type
+ AND binding.created_at >= installation.installed_at
+ WHERE installation.channel_type = 'feishu'
+ AND installation.status = 'active'
+ AND installation.config->>'binding_generation' IS NULL
+ AND installation.config->>'first_message_received_at' IS NULL
+ GROUP BY installation.id, installation.installed_at
+ ORDER BY installation.id
+ LIMIT $1::int
+)
+UPDATE channel_installation AS installation
+SET config = jsonb_set(installation.config, '{first_message_received_at}', to_jsonb(evidence.received_at))
+FROM evidence
+WHERE installation.id = evidence.id
+ AND installation.installed_at = evidence.installed_at
+ AND installation.channel_type = 'feishu'
+ AND installation.status = 'active'
+ AND installation.config->>'binding_generation' IS NULL
+ AND installation.config->>'first_message_received_at' IS NULL
+`
+
+// Session routes are positive receipt evidence only for the current binding.
+// Materialize the candidate timestamp; recheck eligibility after any concurrent
+// writer, preserving live receipt writes and never validating a later rebind.
+func (q *Queries) BackfillLegacyFeishuInboundReceipts(ctx context.Context, batchSize int32) (int64, error) {
+ result, err := q.db.Exec(ctx, backfillLegacyFeishuInboundReceipts, batchSize)
+ if err != nil {
+ return 0, err
+ }
+ return result.RowsAffected(), nil
+}
+
+const recordFeishuInboundReceipt = `-- name: RecordFeishuInboundReceipt :exec
+UPDATE channel_installation
+SET config = jsonb_set(config, '{first_message_received_at}', to_jsonb(now()))
+WHERE id = $1
+ AND workspace_id = $2
+ AND channel_type = 'feishu'
+ AND status = 'active'
+ AND config->>'app_id' = $3::text
+ AND COALESCE(config->>'binding_generation', '') = $4::text
+ AND config->>'first_message_received_at' IS NULL
+`
+
+type RecordFeishuInboundReceiptParams struct {
+ ID pgtype.UUID `json:"id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ AppID string `json:"app_id"`
+ BindingGeneration string `json:"binding_generation"`
+}
+
+// Rebind replaces config with a new generation and no receipt. Legacy configs
+// without a generation match only other legacy snapshots, never a new binding.
+func (q *Queries) RecordFeishuInboundReceipt(ctx context.Context, arg RecordFeishuInboundReceiptParams) error {
+ _, err := q.db.Exec(ctx, recordFeishuInboundReceipt,
+ arg.ID,
+ arg.WorkspaceID,
+ arg.AppID,
+ arg.BindingGeneration,
+ )
+ return err
+}
+
+const setFeishuInstallationBotUnionID = `-- name: SetFeishuInstallationBotUnionID :exec
+UPDATE channel_installation
+SET config = jsonb_set(config, '{bot_union_id}', to_jsonb($1::text)),
+ updated_at = now()
+WHERE id = $2 AND channel_type = 'feishu'
+`
+
+type SetFeishuInstallationBotUnionIDParams struct {
+ BotUnionID string `json:"bot_union_id"`
+ ID pgtype.UUID `json:"id"`
+}
+
+// Preserve concurrently recorded receipt evidence and binding generation.
+func (q *Queries) SetFeishuInstallationBotUnionID(ctx context.Context, arg SetFeishuInstallationBotUnionIDParams) error {
+ _, err := q.db.Exec(ctx, setFeishuInstallationBotUnionID, arg.BotUnionID, arg.ID)
+ return err
+}
diff --git a/server/pkg/db/queries/channel.sql b/server/pkg/db/queries/channel.sql
index 83078a4049..2f7aae0ee1 100644
--- a/server/pkg/db/queries/channel.sql
+++ b/server/pkg/db/queries/channel.sql
@@ -466,9 +466,8 @@ SET status = $2, updated_at = now()
WHERE id = $1;
-- name: SetChannelInstallationConfig :exec
--- Replaces the whole config blob for one installation. Used by the
--- operator backfills (e.g. setting a freshly-fetched bot_union_id) that
--- read-modify-write the JSON in Go and persist it back atomically by id.
+-- Replaces the whole config blob for one installation. Prefer field-level
+-- patches for metadata that can change concurrently with receipt evidence.
UPDATE channel_installation
SET config = $2, updated_at = now()
WHERE id = $1;
diff --git a/server/pkg/db/queries/feishu_verification.sql b/server/pkg/db/queries/feishu_verification.sql
new file mode 100644
index 0000000000..823b00118b
--- /dev/null
+++ b/server/pkg/db/queries/feishu_verification.sql
@@ -0,0 +1,48 @@
+-- name: RecordFeishuInboundReceipt :exec
+-- Rebind replaces config with a new generation and no receipt. Legacy configs
+-- without a generation match only other legacy snapshots, never a new binding.
+UPDATE channel_installation
+SET config = jsonb_set(config, '{first_message_received_at}', to_jsonb(now()))
+WHERE id = sqlc.arg('id')
+ AND workspace_id = sqlc.arg('workspace_id')
+ AND channel_type = 'feishu'
+ AND status = 'active'
+ AND config->>'app_id' = sqlc.arg('app_id')::text
+ AND COALESCE(config->>'binding_generation', '') = sqlc.arg('binding_generation')::text
+ AND config->>'first_message_received_at' IS NULL;
+
+-- name: SetFeishuInstallationBotUnionID :exec
+-- Preserve concurrently recorded receipt evidence and binding generation.
+UPDATE channel_installation
+SET config = jsonb_set(config, '{bot_union_id}', to_jsonb(sqlc.arg('bot_union_id')::text)),
+ updated_at = now()
+WHERE id = sqlc.arg('id') AND channel_type = 'feishu';
+
+-- name: BackfillLegacyFeishuInboundReceipts :execrows
+-- Session routes are positive receipt evidence only for the current binding.
+-- Materialize the candidate timestamp; recheck eligibility after any concurrent
+-- writer, preserving live receipt writes and never validating a later rebind.
+WITH evidence AS MATERIALIZED (
+ SELECT installation.id, installation.installed_at, min(binding.created_at) AS received_at
+ FROM channel_installation AS installation
+ JOIN channel_chat_session_binding AS binding
+ ON binding.installation_id = installation.id
+ AND binding.channel_type = installation.channel_type
+ AND binding.created_at >= installation.installed_at
+ WHERE installation.channel_type = 'feishu'
+ AND installation.status = 'active'
+ AND installation.config->>'binding_generation' IS NULL
+ AND installation.config->>'first_message_received_at' IS NULL
+ GROUP BY installation.id, installation.installed_at
+ ORDER BY installation.id
+ LIMIT sqlc.arg('batch_size')::int
+)
+UPDATE channel_installation AS installation
+SET config = jsonb_set(installation.config, '{first_message_received_at}', to_jsonb(evidence.received_at))
+FROM evidence
+WHERE installation.id = evidence.id
+ AND installation.installed_at = evidence.installed_at
+ AND installation.channel_type = 'feishu'
+ AND installation.status = 'active'
+ AND installation.config->>'binding_generation' IS NULL
+ AND installation.config->>'first_message_received_at' IS NULL;