Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
Lark Bot integration MVP: migration + service boundary (MUL-2671) (#3277)
Bohan Jiang8c98940b797e
diff --git a/apps/web/app/lark/bind/page.tsx b/apps/web/app/lark/bind/page.tsxnew file mode 100644index 0000000000..485181b8e5--- /dev/null+++ b/apps/web/app/lark/bind/page.tsx@@ -0,0 +1,23 @@+"use client";++import { Suspense } from "react";+import { useSearchParams } from "next/navigation";+import { LarkBindPage } from "@multica/views/lark";++// /lark/bind?token=<raw> is the Bot's "you're not bound yet, click here"+// destination. Suspense wraps useSearchParams per Next.js 15's CSR-bailout+// rule; the loading text never paints in practice because the redemption+// page itself renders the "redeeming…" state immediately.+function LarkBindPageContent() {+ const searchParams = useSearchParams();+ const token = searchParams.get("token");+ return <LarkBindPage token={token} />;+}++export default function Page() {+ return (+ <Suspense fallback={null}>+ <LarkBindPageContent />+ </Suspense>+ );+}diff --git a/packages/core/api/client.ts b/packages/core/api/client.tsindex 02f5f0d3ba..b768ceddd4 100644--- a/packages/core/api/client.ts+++ b/packages/core/api/client.ts@@ -100,6 +100,10 @@ import type {GitHubPullRequest,ListGitHubInstallationsResponse,GitHubConnectResponse,+ ListLarkInstallationsResponse,+ BeginLarkInstallResponse,+ LarkInstallStatusResponse,+ RedeemLarkBindingTokenResponse,Squad,SquadMember,SquadMemberStatusListResponse,@@ -2047,4 +2051,33 @@ export class ApiClient {async listIssuePullRequests(issueId: string): Promise<{ pull_requests: GitHubPullRequest[] }> {return this.fetch(`/api/issues/${issueId}/pull-requests`);}++ // Lark integration+ async listLarkInstallations(workspaceId: string): Promise<ListLarkInstallationsResponse> {+ return this.fetch(`/api/workspaces/${workspaceId}/lark/installations`);+ }++ async beginLarkInstall(workspaceId: string, agentId: string): Promise<BeginLarkInstallResponse> {+ const search = new URLSearchParams({ agent_id: agentId });+ return this.fetch(`/api/workspaces/${workspaceId}/lark/install/begin?${search.toString()}`, {+ method: "POST",+ });+ }++ async getLarkInstallStatus(workspaceId: string, sessionId: string): Promise<LarkInstallStatusResponse> {+ return this.fetch(`/api/workspaces/${workspaceId}/lark/install/${sessionId}/status`);+ }++ async deleteLarkInstallation(workspaceId: string, installationId: string): Promise<void> {+ await this.fetch(`/api/workspaces/${workspaceId}/lark/installations/${installationId}`, {+ method: "DELETE",+ });+ }++ async redeemLarkBindingToken(token: string): Promise<RedeemLarkBindingTokenResponse> {+ return this.fetch(`/api/lark/binding/redeem`, {+ method: "POST",+ body: JSON.stringify({ token }),+ });+ }}diff --git a/packages/core/lark/index.ts b/packages/core/lark/index.tsnew file mode 100644index 0000000000..dfc34af176--- /dev/null+++ b/packages/core/lark/index.ts@@ -0,0 +1 @@+export { larkKeys, larkInstallationsOptions } from "./queries";diff --git a/packages/core/lark/queries.ts b/packages/core/lark/queries.tsnew file mode 100644index 0000000000..62c6de9ca2--- /dev/null+++ b/packages/core/lark/queries.ts@@ -0,0 +1,17 @@+import { queryOptions } from "@tanstack/react-query";+import { api } from "../api";++/** Query key namespace for everything Lark-installation-related. Realtime+ * sync invalidates `installations(wsId)` on `lark_installation:*` events+ * so the Settings panel updates without a refetch. */+export const larkKeys = {+ all: (wsId: string) => ["lark", wsId] as const,+ installations: (wsId: string) => [...larkKeys.all(wsId), "installations"] as const,+};++export const larkInstallationsOptions = (wsId: string) =>+ queryOptions({+ queryKey: larkKeys.installations(wsId),+ queryFn: () => api.listLarkInstallations(wsId),+ enabled: !!wsId,+ });diff --git a/packages/core/package.json b/packages/core/package.jsonindex 7ec0d9a144..83d3621830 100644--- a/packages/core/package.json+++ b/packages/core/package.json@@ -81,6 +81,8 @@"./billing/mutations": "./billing/mutations.ts","./github": "./github/index.ts","./github/queries": "./github/queries.ts",+ "./lark": "./lark/index.ts",+ "./lark/queries": "./lark/queries.ts","./feedback": "./feedback/index.ts","./feedback/mutations": "./feedback/mutations.ts","./realtime": "./realtime/index.ts",diff --git a/packages/core/realtime/use-realtime-sync.ts b/packages/core/realtime/use-realtime-sync.tsindex 3674a8e83d..0a9777c4d3 100644--- a/packages/core/realtime/use-realtime-sync.ts+++ b/packages/core/realtime/use-realtime-sync.ts@@ -22,6 +22,7 @@ import {agentTasksKeys,} from "../agents/queries";import { githubKeys } from "../github/queries";+import { larkKeys } from "../lark/queries";import {onIssueCreated,onIssueUpdated,@@ -328,6 +329,10 @@ export function useRealtimeSync(const wsId = getCurrentWsId();if (wsId) qc.invalidateQueries({ queryKey: githubKeys.installations(wsId) });},+ lark_installation: () => {+ const wsId = getCurrentWsId();+ if (wsId) qc.invalidateQueries({ queryKey: larkKeys.installations(wsId) });+ },pull_request: () => {// PR list is keyed by issue id, not workspace, so we invalidate all// PR queries — the open issue detail page will refetch its own list.diff --git a/packages/core/types/index.ts b/packages/core/types/index.tsindex 445607ebcb..3e5d76f1df 100644--- a/packages/core/types/index.ts+++ b/packages/core/types/index.ts@@ -93,6 +93,13 @@ export type {ListGitHubInstallationsResponse,GitHubConnectResponse,} from "./github";+export type {+ LarkInstallation,+ ListLarkInstallationsResponse,+ BeginLarkInstallResponse,+ LarkInstallStatusResponse,+ RedeemLarkBindingTokenResponse,+} from "./lark";export type {Autopilot,AutopilotStatus,diff --git a/packages/core/types/lark.ts b/packages/core/types/lark.tsnew file mode 100644index 0000000000..4798adcc6f--- /dev/null+++ b/packages/core/types/lark.ts@@ -0,0 +1,70 @@+/** A Lark Bot installation bound to a single Multica agent.+ *+ * Wire shape mirrors `LarkInstallationResponse` in+ * `server/internal/handler/lark.go`. New fields the backend adds in the+ * future MUST default to optional so older desktop builds keep parsing+ * the response — see CLAUDE.md → API Response Compatibility. */+export interface LarkInstallation {+ id: string;+ workspace_id: string;+ agent_id: string;+ app_id: string;+ tenant_key?: string | null;+ bot_open_id: string;+ installer_user_id: string;+ status: "active" | "revoked" | string;+ installed_at: string;+ created_at: string;+ updated_at: string;+}++export interface ListLarkInstallationsResponse {+ installations: LarkInstallation[];+ /** Whether the deployment has the at-rest secret key configured. When+ * false the Bind button must be disabled and the panel renders an+ * empty / "ask the operator to enable Lark" state. */+ configured: boolean;+ /** Whether new installs via the device-flow scan-to-bind path can+ * complete end-to-end — i.e. the device-flow RegistrationService is+ * wired AND the real Lark HTTP APIClient (not the no-op stub) is in+ * place. When false the install entry points are hidden and the+ * panel surfaces a "coming soon" notice. Optional so older desktop+ * builds receiving a server that does not yet emit the field+ * default to `undefined`, treated as not supported. */+ install_supported?: boolean;+}++/** First half of the device-flow install: the server has opened a+ * registration session against accounts.feishu.cn and returned the QR+ * URL. The frontend renders `qr_code_url` as a QR (and as a clickable+ * link fallback) and starts polling `/install/{session_id}/status` at+ * the supplied cadence until success or terminal failure. */+export interface BeginLarkInstallResponse {+ session_id: string;+ qr_code_url: string;+ expires_in_seconds: number;+ poll_interval_seconds: number;+}++/** Status polling result. `status` is the discriminator. */+export interface LarkInstallStatusResponse {+ status: "pending" | "success" | "error" | string;+ /** Populated when status === "success". The frontend invalidates the+ * installations cache so the new row appears in the Settings tab. */+ installation_id?: string;+ /** Stable code on error — switch on this (NOT error_message) to pick+ * the right copy. Common values: "expired", "access_denied",+ * "lark_protocol_error", "bot_info_failed", "installation_conflict",+ * "installer_bind_failed", "internal_error". */+ error_reason?: string;+ /** Human-readable error tail for debugging; the production UI should+ * surface the copy keyed off error_reason and use this only as a+ * diagnostic tooltip. */+ error_message?: string;+}++export interface RedeemLarkBindingTokenResponse {+ workspace_id: string;+ installation_id: string;+ lark_open_id: string;+}diff --git a/packages/views/agents/components/agent-detail-inspector.tsx b/packages/views/agents/components/agent-detail-inspector.tsxindex d694354c3c..44127f8027 100644--- a/packages/views/agents/components/agent-detail-inspector.tsx+++ b/packages/views/agents/components/agent-detail-inspector.tsx@@ -46,6 +46,7 @@ import { RuntimePicker } from "./inspector/runtime-picker";import { SkillAttach } from "./inspector/skill-attach";import { ThinkingPropRow } from "./inspector/thinking-prop-row";import { VisibilityPicker } from "./inspector/visibility-picker";+import { LarkAgentBindButton } from "../../settings/components/lark-tab";interface InspectorProps {agent: Agent;@@ -205,6 +206,27 @@ export function AgentDetailInspector({<SkillAttach agent={agent} canEdit={canEdit} /></div></div>++ {/* Integrations — surfaces external-channel bind entry points+ (Lark Bot today; Slack / Discord in the future). The bind+ button self-hides when the server-side device-flow install+ capability gate is closed, so this section may render empty+ on deployments without a configured Lark app — that's+ intentional and matches the "don't surface a flow that will+ fail" guarantee. We only mount it for editors: viewers+ shouldn't see a CTA they can't action. */}+ {canEdit && (+ <div className="flex flex-col px-5 py-4">+ <div className="mb-2 flex items-center gap-2">+ <span className="text-[10px] font-medium uppercase tracking-wider text-muted-foreground">+ {t(($) => $.inspector.section_integrations)}+ </span>+ </div>+ <div className="flex flex-wrap gap-2">+ <LarkAgentBindButton agentId={agent.id} agentName={agent.name} />+ </div>+ </div>+ )}</aside>);}diff --git a/packages/views/lark/bind-page.tsx b/packages/views/lark/bind-page.tsxnew file mode 100644index 0000000000..d1e9e4973e--- /dev/null+++ b/packages/views/lark/bind-page.tsx@@ -0,0 +1,138 @@+"use client";++import { useEffect, useState } from "react";+import { Card, CardContent } from "@multica/ui/components/ui/card";+import { Button } from "@multica/ui/components/ui/button";+import { api } from "@multica/core/api";+import { useAuthStore } from "@multica/core/auth";+import { useNavigation } from "../navigation";+import { useT } from "../i18n";++type RedeemState =+ | { kind: "idle" }+ | { kind: "redeeming" }+ | { kind: "done"; workspaceId: string; installationId: string }+ | { kind: "needs-auth" }+ | { kind: "error"; reason: string };++// LarkBindPage is the destination the Bot's "you need to bind" reply+// card points at. The user lands here logged out OR logged in; we+// require auth before redeeming because the redeemer's Multica+// identity is taken from the session (the token alone never proves+// who is binding — see lark.BindingTokenService.RedeemAndBind).+//+// The token comes in via `?token=<raw>`. We POST it to+// /api/lark/binding/redeem; the backend returns 410 (invalid/expired),+// 409 (already bound to another user), 403 (not a workspace member)+// or 200 with the bound installation. Each maps to distinct user-+// facing copy via lark_bind in common.json.+export function LarkBindPage({ token }: { token: string | null }) {+ const { t } = useT("common");+ const user = useAuthStore((s) => s.user);+ const navigation = useNavigation();+ const [state, setState] = useState<RedeemState>({ kind: "idle" });++ useEffect(() => {+ if (!token) {+ setState({ kind: "error", reason: "missing_token" });+ return;+ }+ if (!user) {+ setState({ kind: "needs-auth" });+ return;+ }+ if (state.kind !== "idle") return;+ setState({ kind: "redeeming" });+ (async () => {+ try {+ const resp = await api.redeemLarkBindingToken(token);+ setState({+ kind: "done",+ workspaceId: resp.workspace_id,+ installationId: resp.installation_id,+ });+ } catch (e) {+ setState({+ kind: "error",+ reason: redemptionFailureReason(e),+ });+ }+ })();+ }, [token, user, state.kind]);++ return (+ <div className="mx-auto flex min-h-screen max-w-md flex-col items-center justify-center p-6">+ <Card className="w-full">+ <CardContent className="space-y-4">+ <h1 className="text-lg font-semibold">{t(($) => $.lark_bind.page_title)}</h1>+ {state.kind === "idle" || state.kind === "redeeming" ? (+ <p className="text-sm text-muted-foreground">{t(($) => $.lark_bind.redeeming)}</p>+ ) : state.kind === "needs-auth" ? (+ <>+ <p className="text-sm text-muted-foreground">+ {t(($) => $.lark_bind.needs_auth_description)}+ </p>+ <Button+ size="sm"+ onClick={() =>+ navigation.push(+ `/login?redirect=${encodeURIComponent(+ `/lark/bind?token=${encodeURIComponent(token ?? "")}`,+ )}`,+ )+ }+ >+ {t(($) => $.lark_bind.sign_in)}+ </Button>+ </>+ ) : state.kind === "done" ? (+ <>+ <p className="text-sm font-medium">{t(($) => $.lark_bind.done_title)}</p>+ <p className="text-xs text-muted-foreground">+ {t(($) => $.lark_bind.done_description)}+ </p>+ </>+ ) : (+ <>+ <p className="text-sm font-medium">{t(($) => $.lark_bind.error_title)}</p>+ <p className="text-xs text-muted-foreground">+ {(() => {+ switch (state.reason) {+ case "missing_token":+ return t(($) => $.lark_bind.error_missing_token);+ case "expired":+ return t(($) => $.lark_bind.error_expired);+ case "already_bound":+ return t(($) => $.lark_bind.error_already_bound);+ case "not_member":+ return t(($) => $.lark_bind.error_not_member);+ default:+ return t(($) => $.lark_bind.error_unknown);+ }+ })()}+ </p>+ <p className="text-[10px] text-muted-foreground">+ {t(($) => $.lark_bind.error_admin_hint)}+ </p>+ </>+ )}+ </CardContent>+ </Card>+ </div>+ );+}++function redemptionFailureReason(err: unknown): string {+ const msg = err instanceof Error ? err.message : "";+ const lower = msg.toLowerCase();+ if (lower.includes("invalid") || lower.includes("expired") || lower.includes("410")) {+ return "expired";+ }+ if (lower.includes("already bound") || lower.includes("409")) {+ return "already_bound";+ }+ if (lower.includes("workspace member") || lower.includes("403")) {+ return "not_member";+ }+ return "unknown";+}diff --git a/packages/views/lark/index.ts b/packages/views/lark/index.tsnew file mode 100644index 0000000000..b33639fc10--- /dev/null+++ b/packages/views/lark/index.ts@@ -0,0 +1 @@+export { LarkBindPage } from "./bind-page";diff --git a/packages/views/locales/en/agents.json b/packages/views/locales/en/agents.jsonindex 45b62c597d..f863c93264 100644--- a/packages/views/locales/en/agents.json+++ b/packages/views/locales/en/agents.json@@ -140,6 +140,7 @@"section_properties": "Properties","section_details": "Details","section_skills": "Skills",+ "section_integrations": "Integrations","prop_runtime": "Runtime","prop_model": "Model","prop_thinking": "Thinking",diff --git a/packages/views/locales/en/common.json b/packages/views/locales/en/common.jsonindex 140da49061..e9ae54f9ab 100644--- a/packages/views/locales/en/common.json+++ b/packages/views/locales/en/common.json@@ -9,5 +9,20 @@"minutes_ago": "{{count}}m ago","hours_ago": "{{count}}h ago","days_ago": "{{count}}d ago"+ },+ "lark_bind": {+ "page_title": "Bind your Lark account",+ "redeeming": "Redeeming binding token…",+ "needs_auth_description": "Sign in to Multica to complete the binding. The token in the link binds your Lark account to this Multica user, so you must be logged in first.",+ "sign_in": "Sign in",+ "done_title": "You're bound.",+ "done_description": "Your next message to the Bot in Lark will go straight to the Agent. You can close this tab.",+ "error_title": "Couldn't complete the binding",+ "error_admin_hint": "If this keeps happening, ask the workspace admin to re-send the binding link from Lark.",+ "error_missing_token": "The link is missing its binding token. Ask the Bot to send a new one in Lark.",+ "error_expired": "This binding link is invalid or expired (links are valid for 15 minutes). Ask the Bot to send a new one.",+ "error_already_bound": "This Lark account is already bound to a different Multica user. Account transfers must go through an explicit unbind first.",+ "error_not_member": "You're signed in to a Multica account that isn't a member of this workspace.",+ "error_unknown": "Something went wrong. Try again, and if the problem persists, contact the workspace admin."}}diff --git a/packages/views/locales/en/settings.json b/packages/views/locales/en/settings.jsonindex f96f9aac61..8d1f9681a0 100644--- a/packages/views/locales/en/settings.json+++ b/packages/views/locales/en/settings.json@@ -174,12 +174,6 @@"section_placeholder_description": "Experimental settings will land here as they ship. Today this tab is intentionally empty.","toast_failed": "Failed to update setting"},- "integrations": {- "section_title": "Integrations",- "empty_title": "No third-party integrations yet",- "empty_description": "Once Slack, Linear, and other integrations are wired up they will appear here. GitHub has moved to its own tab.",- "manage_hint": "Only admins and owners can manage integrations."- },"github": {"page_description": "Connect a GitHub App, control how Pull Requests show up inside Multica, and decide what your agents leave behind in commit history.","section_master": "Enable GitHub features",@@ -223,6 +217,56 @@"repositories_shortcut_link": "Manage repositories →","toast_failed": "Failed to update GitHub settings"},+ "lark": {+ "section_title": "Lark",+ "page_description": "Connect each Multica Agent to a Lark (飞书) PersonalAgent Bot. Members can DM the Bot, @ it in groups, and type /issue to spin up a new Multica issue.",+ "not_enabled_title": "Lark integration not enabled",+ "not_enabled_description_prefix": "Set",+ "not_enabled_description_suffix": "on the server to enable Lark Bot installations.",+ "not_enabled_self_host_hint": "Self-hosters: see the project README for details.",+ "preview_title": "Lark Bot installation coming soon",+ "preview_description": "The at-rest key is set, but the Lark HTTP client is not wired in this build. The install entry point will appear here once the transport is enabled in a follow-up release.",+ "connected_bots": "Connected bots",+ "loading": "Loading…",+ "empty_title": "No bots connected yet",+ "empty_description_prefix": "Open an Agent in this workspace and click",+ "empty_description_cta": "Bind to Lark",+ "empty_description_suffix": "to install a Bot for it.",+ "revoked_badge": "revoked",+ "installed_at_label": "Installed {{when}}",+ "disconnect": "Disconnect",+ "disconnecting": "Disconnecting…",+ "disconnect_confirm_title": "Disconnect this Lark bot?",+ "disconnect_confirm_description": "The Bot will stop receiving Lark messages and the WebSocket connection will be torn down. The installation row is kept for audit; you can re-install later from the same Agent.",+ "disconnect_confirm_cancel": "Cancel",+ "toast_disconnected": "Disconnected Lark bot",+ "toast_disconnect_failed": "Disconnect failed",+ "bind_button": "Bind to Lark",+ "bind_button_title": "Bind {{agent}} to a Lark Bot",+ "agent_bot_connected_label": "Connected to Lark",+ "agent_bot_manage_link": "Manage in Lark",+ "agent_bot_manage_tooltip": "Open this Bot's app page in Lark — manage scopes, edit display name, request additional permissions.",+ "install_dialog_title": "Bind to Lark",+ "install_dialog_description": "Open Lark on your phone and scan the code below to create a PersonalAgent Bot.",+ "install_dialog_description_for_agent": "Open Lark on your phone and scan the code below to create a Bot for {{agent}}.",+ "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_toast": "Lark Bot installed",+ "install_close": "Close",+ "install_retry": "Scan again",+ "install_poll_retry": "Network blip while checking install status — retrying.",+ "install_error_expired": "QR expired before authorization. Scan again.",+ "install_error_access_denied": "Install cancelled in Lark.",+ "install_error_protocol": "Lark refused the install — try again.",+ "install_error_bot_info": "Authorized, but Multica couldn't fetch the Bot's identity. Try again.",+ "install_error_conflict": "Could not save the installation. Another bot may already be bound to this agent.",+ "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."+ },"repositories": {"section_title": "Repositories","description": "Git repositories associated with this workspace. Agents use these to clone and work on code.",diff --git a/packages/views/locales/ja/agents.json b/packages/views/locales/ja/agents.jsonindex a58ee2937c..f850cafffd 100644--- a/packages/views/locales/ja/agents.json+++ b/packages/views/locales/ja/agents.json@@ -127,6 +127,7 @@"section_properties": "プロパティ","section_details": "詳細","section_skills": "スキル",+ "section_integrations": "連携","prop_runtime": "ランタイム","prop_model": "モデル","prop_thinking": "思考",diff --git a/packages/views/locales/ja/common.json b/packages/views/locales/ja/common.jsonindex 11a922611e..8ab8f1b571 100644--- a/packages/views/locales/ja/common.json+++ b/packages/views/locales/ja/common.json@@ -9,5 +9,20 @@"minutes_ago": "{{count}}分前","hours_ago": "{{count}}時間前","days_ago": "{{count}}日前"+ },+ "lark_bind": {+ "page_title": "Lark アカウントを連携",+ "redeeming": "バインディングトークンを使用しています…",+ "needs_auth_description": "連携を完了するには Multica にログインしてください。リンク内のトークンが Lark アカウントを現在の Multica ユーザーに紐付けるため、先にログインが必要です。",+ "sign_in": "ログイン",+ "done_title": "連携が完了しました。",+ "done_description": "次回 Lark でボットに送ったメッセージは、そのままエージェントに届きます。このタブは閉じても問題ありません。",+ "error_title": "連携を完了できませんでした",+ "error_admin_hint": "問題が続く場合は、ワークスペース管理者に Lark から連携リンクを再送してもらってください。",+ "error_missing_token": "リンクにバインディングトークンが含まれていません。Lark のボットに新しいリンクを送ってもらってください。",+ "error_expired": "この連携リンクは無効か期限切れです(有効期間は 15 分)。ボットに新しいリンクを送ってもらってください。",+ "error_already_bound": "この Lark アカウントはすでに別の Multica ユーザーに連携されています。アカウントを移すには、まず明示的に連携を解除する必要があります。",+ "error_not_member": "現在ログイン中の Multica アカウントは、このワークスペースのメンバーではありません。",+ "error_unknown": "問題が発生しました。もう一度試し、それでも解決しない場合はワークスペース管理者にお問い合わせください。"}}diff --git a/packages/views/locales/ja/settings.json b/packages/views/locales/ja/settings.jsonindex f9020e4f39..7d7b34d2d5 100644--- a/packages/views/locales/ja/settings.json+++ b/packages/views/locales/ja/settings.json@@ -174,12 +174,6 @@"section_placeholder_description": "実験的な設定はリリースされ次第ここに表示されます。現在このタブは意図的に空にしてあります。","toast_failed": "設定を更新できませんでした"},- "integrations": {- "section_title": "連携",- "empty_title": "まだサードパーティ連携はありません",- "empty_description": "Slack、Linear などの連携が設定されると、ここに表示されます。GitHub は専用タブに移動しました。",- "manage_hint": "連携を管理できるのは admin と owner のみです。"- },"github": {"page_description": "GitHub App を接続し、Pull request が Multica 内でどう表示されるかを制御し、エージェントがコミット履歴に残す情報を設定します。","section_master": "GitHub 機能を有効にする",@@ -223,6 +217,56 @@"repositories_shortcut_link": "リポジトリを管理 →","toast_failed": "GitHub 設定を更新できませんでした"},+ "lark": {+ "section_title": "Lark",+ "page_description": "各 Multica エージェントを Lark (飞书) PersonalAgent ボットに接続します。メンバーはボットに DM したり、グループで @ メンションしたり、/issue と入力して新しい Multica イシューを起こすことができます。",+ "not_enabled_title": "Lark 連携が有効化されていません",+ "not_enabled_description_prefix": "Lark ボットの設置を有効化するにはサーバーに",+ "not_enabled_description_suffix": "を設定してください。",+ "not_enabled_self_host_hint": "セルフホスト運用者の方は、詳細はプロジェクトの README を参照してください。",+ "preview_title": "Lark ボットの設置はまもなく利用可能になります",+ "preview_description": "保管時暗号化キーは設定されていますが、このビルドには Lark HTTP クライアントが接続されていません。後続リリースでトランスポートが有効化されると、設置エントリーポイントがここに表示されます。",+ "connected_bots": "接続済みのボット",+ "loading": "読み込み中…",+ "empty_title": "まだボットが接続されていません",+ "empty_description_prefix": "このワークスペースのエージェントを開いて",+ "empty_description_cta": "Lark に接続",+ "empty_description_suffix": "をクリックすると、対応するボットを設置できます。",+ "revoked_badge": "取り消し済み",+ "installed_at_label": "{{when}} に設置",+ "disconnect": "切断",+ "disconnecting": "切断しています…",+ "disconnect_confirm_title": "この Lark ボットを切断しますか?",+ "disconnect_confirm_description": "ボットは Lark のメッセージを受け取らなくなり、WebSocket 接続も切断されます。監査用にインストール行は保持され、同じエージェントから再設置できます。",+ "disconnect_confirm_cancel": "キャンセル",+ "toast_disconnected": "Lark ボットを切断しました",+ "toast_disconnect_failed": "切断に失敗しました",+ "bind_button": "Lark に接続",+ "bind_button_title": "{{agent}} を Lark ボットに接続",+ "agent_bot_connected_label": "Lark に接続済み",+ "agent_bot_manage_link": "Lark で管理",+ "agent_bot_manage_tooltip": "Lark のデベロッパーコンソールでこのボットのアプリページを開き、スコープ管理 / 名称変更 / 追加権限の申請ができます。",+ "install_dialog_title": "Lark に接続",+ "install_dialog_description": "Lark を開き、以下のコードをスキャンして PersonalAgent ボットを作成してください。",+ "install_dialog_description_for_agent": "Lark を開き、以下のコードをスキャンして {{agent}} 用のボットを作成してください。",+ "install_starting": "QR コードを準備しています…",+ "install_scan_hint": "Lark → スキャン → 新しい PersonalAgent を承認してください。",+ "install_open_link_fallback": "ここをタップして Lark で開く",+ "install_success": "設置が完了しました — ボットはオンラインです。",+ "install_success_toast": "Lark ボットを設置しました",+ "install_close": "閉じる",+ "install_retry": "もう一度スキャン",+ "install_poll_retry": "設置状況の確認中に一時的にネットワークが途切れました — 再試行します。",+ "install_error_expired": "承認前に QR が期限切れになりました。もう一度スキャンしてください。",+ "install_error_access_denied": "Lark で設置がキャンセルされました。",+ "install_error_protocol": "Lark が設置を拒否しました — もう一度お試しください。",+ "install_error_bot_info": "承認はされましたが、Multica がボットの識別子を取得できませんでした。もう一度お試しください。",+ "install_error_conflict": "設置を保存できませんでした。別のボットがすでにこのエージェントに接続されている可能性があります。",+ "install_error_installer_bind": "ボットは設置されましたが、Lark の身元情報を連携できませんでした。もう一度お試しいただくか、サポートにお問い合わせください。",+ "install_error_session_lost": "設置セッションが期限切れまたは失われました。もう一度スキャンしてやり直してください。",+ "install_error_forbidden": "このワークスペースに Lark ボットを設置する権限がなくなりました。ワークスペース管理者にお問い合わせください。",+ "install_error_generic": "設置に失敗しました。もう一度お試しください。"+ },"repositories": {"section_title": "リポジトリ","description": "このワークスペースに関連付けられた Git リポジトリです。エージェントはこれらをクローンしてコードを作業します。",diff --git a/packages/views/locales/ko/agents.json b/packages/views/locales/ko/agents.jsonindex b486ea80a2..d718b048ff 100644--- a/packages/views/locales/ko/agents.json+++ b/packages/views/locales/ko/agents.json@@ -140,6 +140,7 @@"section_properties": "속성","section_details": "세부 정보","section_skills": "스킬",+ "section_integrations": "연동","prop_runtime": "런타임","prop_model": "모델","prop_thinking": "추론",diff --git a/packages/views/locales/ko/common.json b/packages/views/locales/ko/common.jsonindex b9ac7f0b55..a5f3770bd0 100644--- a/packages/views/locales/ko/common.json+++ b/packages/views/locales/ko/common.json@@ -9,5 +9,20 @@"minutes_ago": "{{count}}분 전","hours_ago": "{{count}}시간 전","days_ago": "{{count}}일 전"+ },+ "lark_bind": {+ "page_title": "Lark 계정 연결",+ "redeeming": "바인딩 토큰을 사용하는 중…",+ "needs_auth_description": "바인딩을 완료하려면 Multica에 로그인하세요. 링크의 토큰이 Lark 계정을 현재 로그인된 Multica 사용자에 연결하므로, 먼저 로그인해야 합니다.",+ "sign_in": "로그인",+ "done_title": "연결 완료.",+ "done_description": "이제 Lark에서 봇에게 보낸 메시지가 곧바로 에이전트로 전달됩니다. 이 탭은 닫아도 됩니다.",+ "error_title": "바인딩을 완료하지 못했어요",+ "error_admin_hint": "계속 실패한다면, 워크스페이스 관리자에게 Lark에서 바인딩 링크를 다시 보내달라고 요청하세요.",+ "error_missing_token": "링크에 바인딩 토큰이 없습니다. Lark에서 봇에게 새 링크를 다시 받아주세요.",+ "error_expired": "이 바인딩 링크는 유효하지 않거나 만료되었습니다(유효 시간 15분). 봇에게 새 링크를 다시 받아주세요.",+ "error_already_bound": "이 Lark 계정은 이미 다른 Multica 사용자에 연결되어 있습니다. 계정 이전은 먼저 명시적으로 연결을 해제해야 합니다.",+ "error_not_member": "현재 로그인한 Multica 계정이 이 워크스페이스의 멤버가 아닙니다.",+ "error_unknown": "문제가 발생했어요. 다시 시도해 보고, 계속되면 워크스페이스 관리자에게 문의하세요."}}diff --git a/packages/views/locales/ko/settings.json b/packages/views/locales/ko/settings.jsonindex 15a46b3e1c..a190e0a7f7 100644--- a/packages/views/locales/ko/settings.json+++ b/packages/views/locales/ko/settings.json@@ -174,12 +174,6 @@"section_placeholder_description": "실험적 설정은 출시되는 대로 여기에 표시됩니다. 현재 이 탭은 의도적으로 비어 있습니다.","toast_failed": "설정을 업데이트하지 못했습니다"},- "integrations": {- "section_title": "연동",- "empty_title": "아직 서드파티 연동이 없습니다",- "empty_description": "Slack, Linear 등 연동이 연결되면 여기에 표시됩니다. GitHub는 별도 탭으로 이동했습니다.",- "manage_hint": "관리자와 소유자만 연동을 관리할 수 있습니다."- },"github": {"page_description": "GitHub App을 연결하고, Pull request가 Multica 안에서 표시되는 방식을 제어하며, 에이전트가 커밋 기록에 남기는 정보를 설정합니다.","section_master": "GitHub 기능 사용",@@ -299,5 +293,55 @@"description": "이슈 생성 및 작업"}}+ },+ "lark": {+ "section_title": "Lark",+ "page_description": "각 Multica 에이전트를 Lark(飞书) PersonalAgent 봇에 연결하세요. 멤버는 봇과 1:1로 대화하거나, 그룹에서 @ 멘션하거나, /issue 를 입력해 새 Multica 이슈를 만들 수 있습니다.",+ "not_enabled_title": "Lark 연동이 비활성화되어 있어요",+ "not_enabled_description_prefix": "Lark 봇 설치를 활성화하려면 서버에",+ "not_enabled_description_suffix": "을(를) 설정하세요.",+ "not_enabled_self_host_hint": "셀프 호스트 운영자: 자세한 내용은 프로젝트 README를 참고하세요.",+ "preview_title": "Lark 봇 설치 곧 출시 예정",+ "preview_description": "암호화 키는 설정되어 있지만, 이 빌드에는 Lark HTTP 클라이언트가 연결되어 있지 않습니다. 후속 릴리스에서 전송 계층이 활성화되면 설치 진입점이 여기에 표시됩니다.",+ "connected_bots": "연결된 봇",+ "loading": "불러오는 중…",+ "empty_title": "아직 연결된 봇이 없어요",+ "empty_description_prefix": "이 워크스페이스의 에이전트를 열고",+ "empty_description_cta": "Lark에 연결",+ "empty_description_suffix": "을(를) 클릭해 봇을 설치하세요.",+ "revoked_badge": "취소됨",+ "installed_at_label": "{{when}} 설치됨",+ "disconnect": "연결 해제",+ "disconnecting": "연결을 해제하는 중…",+ "disconnect_confirm_title": "이 Lark 봇의 연결을 해제할까요?",+ "disconnect_confirm_description": "봇은 더 이상 Lark 메시지를 받지 않으며 WebSocket 연결도 끊깁니다. 감사 로그를 위해 설치 행은 유지되며, 같은 에이전트에서 다시 설치할 수 있습니다.",+ "disconnect_confirm_cancel": "취소",+ "toast_disconnected": "Lark 봇 연결을 해제했어요",+ "toast_disconnect_failed": "연결 해제에 실패했어요",+ "bind_button": "Lark에 연결",+ "bind_button_title": "{{agent}}을(를) Lark 봇에 연결",+ "agent_bot_connected_label": "Lark에 연결됨",+ "agent_bot_manage_link": "Lark에서 관리",+ "agent_bot_manage_tooltip": "Lark 개발자 콘솔에서 이 봇의 앱 페이지를 열어 스코프 관리, 이름 변경, 추가 권한 신청을 할 수 있어요.",+ "install_dialog_title": "Lark에 연결",+ "install_dialog_description": "휴대폰에서 Lark를 열고 아래 코드를 스캔해 PersonalAgent 봇을 만드세요.",+ "install_dialog_description_for_agent": "휴대폰에서 Lark를 열고 아래 코드를 스캔해 {{agent}}용 봇을 만드세요.",+ "install_starting": "QR 코드를 준비하는 중…",+ "install_scan_hint": "Lark → 스캔 → 새 PersonalAgent를 승인하세요.",+ "install_open_link_fallback": "또는 여기를 눌러 Lark에서 열기",+ "install_success": "설치 완료 — 봇이 온라인 상태입니다.",+ "install_success_toast": "Lark 봇이 설치되었어요",+ "install_close": "닫기",+ "install_retry": "다시 스캔",+ "install_poll_retry": "설치 상태를 확인하는 중 네트워크가 일시적으로 끊겼어요 — 다시 시도합니다.",+ "install_error_expired": "승인 전에 QR이 만료되었어요. 다시 스캔하세요.",+ "install_error_access_denied": "Lark에서 설치가 취소되었어요.",+ "install_error_protocol": "Lark가 설치를 거부했어요 — 다시 시도하세요.",+ "install_error_bot_info": "승인되었지만 Multica가 봇의 식별자를 가져오지 못했어요. 다시 시도하세요.",+ "install_error_conflict": "설치를 저장하지 못했어요. 다른 봇이 이미 이 에이전트에 연결되어 있을 수 있어요.",+ "install_error_installer_bind": "봇은 설치되었지만 Lark 신원을 연결하지 못했어요. 다시 시도하거나 지원팀에 문의하세요.",+ "install_error_session_lost": "설치 세션이 만료되었거나 유실되었어요. 다시 스캔해 처음부터 진행하세요.",+ "install_error_forbidden": "이 워크스페이스에 Lark 봇을 설치할 권한이 더 이상 없어요. 워크스페이스 관리자에게 문의하세요.",+ "install_error_generic": "설치에 실패했어요. 다시 시도하세요."}}diff --git a/packages/views/locales/zh-Hans/agents.json b/packages/views/locales/zh-Hans/agents.jsonindex 4445321698..88f3c0841e 100644--- a/packages/views/locales/zh-Hans/agents.json+++ b/packages/views/locales/zh-Hans/agents.json@@ -135,6 +135,7 @@"section_properties": "属性","section_details": "详情","section_skills": "Skills",+ "section_integrations": "外部集成","prop_runtime": "运行时","prop_model": "模型","prop_thinking": "思考",diff --git a/packages/views/locales/zh-Hans/common.json b/packages/views/locales/zh-Hans/common.jsonindex 61c2dfe0e7..444ca7eb7e 100644--- a/packages/views/locales/zh-Hans/common.json+++ b/packages/views/locales/zh-Hans/common.json@@ -9,5 +9,20 @@"minutes_ago": "{{count}} 分钟前","hours_ago": "{{count}} 小时前","days_ago": "{{count}} 天前"+ },+ "lark_bind": {+ "page_title": "绑定飞书账号",+ "redeeming": "正在兑换绑定 token…",+ "needs_auth_description": "需要登录 Multica 才能完成绑定。链接中的 token 会将你的飞书账号绑定到当前登录的 Multica 用户。",+ "sign_in": "登录",+ "done_title": "已绑定。",+ "done_description": "下次在飞书向 Bot 发送消息时,会直接送达绑定的智能体。可以关闭此页面。",+ "error_title": "绑定未完成",+ "error_admin_hint": "如果反复失败,请让工作区管理员从飞书重新发送绑定链接。",+ "error_missing_token": "链接缺少绑定 token。请让 Bot 在飞书重新发送一份。",+ "error_expired": "绑定链接无效或已过期(有效期 15 分钟)。请让 Bot 重新发送一份。",+ "error_already_bound": "该飞书账号已绑定到其他 Multica 用户。账户转移需要先显式解绑。",+ "error_not_member": "你登录的 Multica 账号不是当前工作区成员。",+ "error_unknown": "出现未知错误。请稍后再试,如反复失败请联系工作区管理员。"}}diff --git a/packages/views/locales/zh-Hans/settings.json b/packages/views/locales/zh-Hans/settings.jsonindex ed1d6afda6..8e63ba9ede 100644--- a/packages/views/locales/zh-Hans/settings.json+++ b/packages/views/locales/zh-Hans/settings.json@@ -174,12 +174,6 @@"section_placeholder_description": "实验性功能上线后会出现在这里。当前实验室页面是空的。","toast_failed": "更新设置失败"},- "integrations": {- "section_title": "集成",- "empty_title": "暂无第三方集成",- "empty_description": "Slack、Linear 等集成接入后会出现在这里。GitHub 已迁出到独立的标签页。",- "manage_hint": "只有管理员和所有者可以管理集成。"- },"github": {"page_description": "连接 GitHub App、控制 Pull Request 如何出现在 Multica 中,并决定智能体在 commit 记录里留下哪些痕迹。","section_master": "启用 GitHub 功能",@@ -223,6 +217,56 @@"repositories_shortcut_link": "前往管理 →","toast_failed": "更新 GitHub 设置失败"},+ "lark": {+ "section_title": "飞书",+ "page_description": "将每个 Multica 智能体绑定到飞书 PersonalAgent Bot。成员可在飞书私聊 Bot、群聊 @ Bot,或输入 /issue 直接创建 Multica issue。",+ "not_enabled_title": "未启用飞书集成",+ "not_enabled_description_prefix": "需要在服务器上设置",+ "not_enabled_description_suffix": "才能启用飞书 Bot 绑定。",+ "not_enabled_self_host_hint": "自托管部署请参考项目 README。",+ "preview_title": "飞书 Bot 安装即将上线",+ "preview_description": "服务器已配置加密密钥,但本版本尚未接入真实的飞书 HTTP 客户端。后续版本启用传输层后,安装入口将在此展示。",+ "connected_bots": "已连接的 Bot",+ "loading": "加载中…",+ "empty_title": "暂无已绑定的 Bot",+ "empty_description_prefix": "在工作区里打开任一智能体,点击",+ "empty_description_cta": "绑定到飞书",+ "empty_description_suffix": "即可为它安装 Bot。",+ "revoked_badge": "已撤销",+ "installed_at_label": "安装于 {{when}}",+ "disconnect": "断开连接",+ "disconnecting": "正在断开…",+ "disconnect_confirm_title": "断开这个飞书 Bot?",+ "disconnect_confirm_description": "Bot 将停止接收飞书消息,WebSocket 连接会被销毁。安装记录会保留以便审计;可随时从同一智能体重新安装。",+ "disconnect_confirm_cancel": "取消",+ "toast_disconnected": "已断开飞书 Bot",+ "toast_disconnect_failed": "断开失败",+ "bind_button": "绑定到飞书",+ "bind_button_title": "将 {{agent}} 绑定到飞书 Bot",+ "agent_bot_connected_label": "已连接到飞书",+ "agent_bot_manage_link": "在飞书中管理",+ "agent_bot_manage_tooltip": "打开飞书开发者控制台中该 Bot 的应用页面——管理权限、修改名称、申请新的权限范围。",+ "install_dialog_title": "绑定到飞书",+ "install_dialog_description": "用飞书扫描下方二维码,创建一个 PersonalAgent Bot。",+ "install_dialog_description_for_agent": "用飞书扫描下方二维码,为 {{agent}} 创建一个 Bot。",+ "install_starting": "正在准备二维码…",+ "install_scan_hint": "飞书 → 扫一扫 → 授权新 PersonalAgent。",+ "install_open_link_fallback": "或点这里直接在飞书中打开",+ "install_success": "安装完成,Bot 已上线。",+ "install_success_toast": "飞书 Bot 已安装",+ "install_close": "关闭",+ "install_retry": "重新扫码",+ "install_poll_retry": "网络抖动,正在重试查询安装状态。",+ "install_error_expired": "二维码过期,请重新扫码。",+ "install_error_access_denied": "已在飞书内取消安装。",+ "install_error_protocol": "飞书拒绝了安装请求,请重试。",+ "install_error_bot_info": "授权完成,但 Multica 无法获取 Bot 身份信息,请重试。",+ "install_error_conflict": "未能保存安装信息:该智能体可能已绑定其他 Bot。",+ "install_error_installer_bind": "已安装 Bot,但未能绑定你的飞书身份。请重试或联系管理员。",+ "install_error_session_lost": "安装会话已失效或丢失,请重新扫码。",+ "install_error_forbidden": "你已没有在此工作区安装飞书 Bot 的权限,请联系工作区管理员。",+ "install_error_generic": "安装失败,请重试。"+ },"repositories": {"section_title": "代码仓库","description": "与该工作区关联的 Git 仓库。智能体会从这里 clone 代码并完成工作。",diff --git a/packages/views/package.json b/packages/views/package.jsonindex e5e5e3ca34..895a2eb5a9 100644--- a/packages/views/package.json+++ b/packages/views/package.json@@ -43,6 +43,8 @@"./search": "./search/index.ts","./chat": "./chat/index.ts","./settings": "./settings/index.ts",+ "./settings/lark-tab": "./settings/components/lark-tab.tsx",+ "./lark": "./lark/index.ts","./invite": "./invite/index.ts","./invitations": "./invitations/index.ts","./onboarding": "./onboarding/index.ts",@@ -89,6 +91,7 @@"motion": "^12.38.0","pinyin-pro": "3.26.0","react-markdown": "^10.1.0",+ "react-qr-code": "catalog:","react-resizable-panels": "^4.7.5","react-virtuoso": "catalog:","recharts": "3.8.0",diff --git a/packages/views/settings/components/integrations-tab.tsx b/packages/views/settings/components/integrations-tab.tsxindex aa9b75f30a..628cd6adb8 100644--- a/packages/views/settings/components/integrations-tab.tsx+++ b/packages/views/settings/components/integrations-tab.tsx@@ -1,41 +1,21 @@"use client";-import { Plug } from "lucide-react";-import {- Empty,- EmptyContent,- EmptyDescription,- EmptyHeader,- EmptyMedia,- EmptyTitle,-} from "@multica/ui/components/ui/empty";+import { LarkTab } from "./lark-tab";import { useT } from "../../i18n";-// GitHub now lives in its own Settings tab (see github-tab.tsx). Until other-// third-party integrations land, this tab is intentionally an empty state —-// it stays in the IA so deep links and muscle memory don't break.+// Integrations is the umbrella tab for third-party platform connections.+// GitHub has its own top-level tab (see github-tab.tsx); everything else+// — currently just Lark, with Slack/Linear etc. to follow — lives in+// here under its own section heading so additional integrations slot in+// without changing the IA. IntegrationsTab is just the host; each+// integration owns its own description and install flow.export function IntegrationsTab() {const { t } = useT("settings");return (- <div className="space-y-4">+ <div className="space-y-10"><section className="space-y-4">- <h2 className="text-sm font-semibold">{t(($) => $.integrations.section_title)}</h2>- <Empty>- <EmptyHeader>- <EmptyMedia variant="icon">- <Plug className="h-4 w-4" />- </EmptyMedia>- <EmptyTitle>{t(($) => $.integrations.empty_title)}</EmptyTitle>- <EmptyDescription>- {t(($) => $.integrations.empty_description)}- </EmptyDescription>- </EmptyHeader>- <EmptyContent>- <p className="text-xs text-muted-foreground">- {t(($) => $.integrations.manage_hint)}- </p>- </EmptyContent>- </Empty>+ <h2 className="text-sm font-semibold">{t(($) => $.lark.section_title)}</h2>+ <LarkTab /></section></div>);diff --git a/packages/views/settings/components/lark-tab.test.tsx b/packages/views/settings/components/lark-tab.test.tsxnew file mode 100644index 0000000000..4b225c96e4--- /dev/null+++ b/packages/views/settings/components/lark-tab.test.tsx@@ -0,0 +1,474 @@+import { StrictMode, type ReactNode } from "react";+import { describe, it, expect, beforeEach, afterEach, vi } from "vitest";+import { act, render, screen, waitFor } from "@testing-library/react";+import userEvent from "@testing-library/user-event";+import { I18nProvider } from "@multica/core/i18n/react";+import enCommon from "../../locales/en/common.json";+import enSettings from "../../locales/en/settings.json";++// ApiError is re-exported from @multica/core/api; we mock the api module+// itself but still need a real ApiError class so `e instanceof ApiError`+// in the polling catch behaves the way it does at runtime.+const ApiError = vi.hoisted(() => {+ class ApiError extends Error {+ readonly status: number;+ readonly statusText: string;+ readonly body?: unknown;+ constructor(message: string, status: number, statusText = "", body?: unknown) {+ super(message);+ this.name = "ApiError";+ this.status = status;+ this.statusText = statusText;+ this.body = body;+ }+ }+ return ApiError;+});++const mockBeginInstall = vi.hoisted(() => vi.fn());+const mockGetStatus = vi.hoisted(() => vi.fn());+const mockDeleteInstallation = vi.hoisted(() => vi.fn());+const mockInvalidate = vi.hoisted(() => vi.fn());++type MemberRole = "owner" | "admin" | "member" | "guest";++const membersRef = vi.hoisted(() => ({+ current: [{ user_id: "user-1", role: "owner" as MemberRole }],+}));+const installationsRef = vi.hoisted(() => ({+ current: {+ installations: [] as unknown[],+ configured: true,+ install_supported: true,+ },+}));++vi.mock("@tanstack/react-query", () => ({+ useQuery: (opts: { queryKey: unknown[]; enabled?: boolean }) => {+ if (opts.enabled === false) return { data: undefined, isLoading: false };+ const key = JSON.stringify(opts.queryKey);+ if (key.includes("members")) return { data: membersRef.current, isLoading: false };+ if (key.includes("installations")) {+ return { data: installationsRef.current, isLoading: false };+ }+ return { data: undefined, isLoading: false };+ },+ useQueryClient: () => ({+ invalidateQueries: mockInvalidate,+ }),+ queryOptions: <T,>(opts: T) => opts,+}));++vi.mock("@multica/core/hooks", () => ({+ useWorkspaceId: () => "workspace-1",+}));++vi.mock("@multica/core/workspace/queries", () => ({+ memberListOptions: () => ({ queryKey: ["members"], queryFn: vi.fn() }),+}));++// useActorName is the workspace-wide identity helper. The Installation+// row uses it to render the Multica agent's name in place of the raw+// Lark app_id. Stubbing it here decouples LarkTab tests from the agent+// list query plumbing.+const agentNameByIdRef = vi.hoisted(() => ({+ current: new Map<string, string>(),+}));+vi.mock("@multica/core/workspace/hooks", () => ({+ useActorName: () => ({+ getAgentName: (agentId: string) =>+ agentNameByIdRef.current.get(agentId) ?? "Unknown Agent",+ getMemberName: () => "Unknown",+ getSquadName: () => "Unknown Squad",+ getActorName: () => "Unknown",+ getActorInitials: () => "??",+ getActorAvatarUrl: () => null,+ }),+}));++// ActorAvatar pulls in a deep tree (hover cards, presence query, paths).+// In LarkTab tests we only care that the row identifies the correct+// agent — render a tiny stub that surfaces actorId in the DOM so the+// agent-identity assertion can read it directly.+vi.mock("../../common/actor-avatar", () => ({+ ActorAvatar: ({ actorType, actorId }: { actorType: string; actorId: string }) => (+ <span data-testid="actor-avatar" data-actor-type={actorType} data-actor-id={actorId} />+ ),+}));++vi.mock("@multica/core/lark", () => ({+ larkInstallationsOptions: () => ({+ queryKey: ["lark", "installations"],+ queryFn: vi.fn(),+ }),+ larkKeys: { installations: (wsId: string) => ["lark", "installations", wsId] },+}));++vi.mock("@multica/core/api", () => ({+ api: {+ beginLarkInstall: mockBeginInstall,+ getLarkInstallStatus: mockGetStatus,+ deleteLarkInstallation: mockDeleteInstallation,+ },+ ApiError,+}));++vi.mock("@multica/core/auth", () => {+ const useAuthStore = Object.assign(+ (sel?: (s: { user: { id: string } }) => unknown) =>+ sel ? sel({ user: { id: "user-1" } }) : { user: { id: "user-1" } },+ { getState: () => ({ user: { id: "user-1" } }) },+ );+ return { useAuthStore };+});++vi.mock("sonner", () => ({+ toast: {+ success: vi.fn(),+ error: vi.fn(),+ message: vi.fn(),+ },+}));++// react-qr-code renders SVG that jsdom doesn't fully support — a stub+// keeps the dialog DOM compact and lets us assert on the surrounding+// chrome (status text, buttons) without QR mechanics.+vi.mock("react-qr-code", () => ({+ default: ({ value }: { value: string }) => (+ <span data-testid="qr-code" data-value={value} />+ ),+}));++import { LarkAgentBindButton, LarkTab } from "./lark-tab";++const TEST_RESOURCES = {+ en: { common: enCommon, settings: enSettings },+};++function I18nWrapper({ children }: { children: ReactNode }) {+ return (+ <I18nProvider locale="en" resources={TEST_RESOURCES}>+ {children}+ </I18nProvider>+ );+}++// StrictMode wrapper used to reproduce the dev-mode mount → unmount →+// remount cycle. React 19 dev runs this on every component, which+// surfaces effect cleanup bugs that don't show in production builds.+function StrictModeWrapper({ children }: { children: ReactNode }) {+ return (+ <StrictMode>+ <I18nProvider locale="en" resources={TEST_RESOURCES}>+ {children}+ </I18nProvider>+ </StrictMode>+ );+}++function resetFixtures() {+ vi.clearAllMocks();+ membersRef.current = [{ user_id: "user-1", role: "owner" }];+ installationsRef.current = {+ installations: [],+ configured: true,+ install_supported: true,+ };+ agentNameByIdRef.current = new Map();+}++describe("LarkAgentBindButton (CTA gate)", () => {+ beforeEach(resetFixtures);++ it("renders the bind CTA when the viewer is a workspace owner and install is supported", () => {+ render(<LarkAgentBindButton agentId="agent-1" agentName="Bot" />, {+ wrapper: I18nWrapper,+ });+ expect(screen.getByRole("button", { name: /Bind to Lark/i })).toBeTruthy();+ });++ it("renders the bind CTA when the viewer is a workspace admin", () => {+ membersRef.current = [{ user_id: "user-1", role: "admin" }];+ render(<LarkAgentBindButton agentId="agent-1" agentName="Bot" />, {+ wrapper: I18nWrapper,+ });+ expect(screen.getByRole("button", { name: /Bind to Lark/i })).toBeTruthy();+ });++ it("hides the bind CTA for a non-admin agent owner (matches backend admin gate)", () => {+ membersRef.current = [{ user_id: "user-1", role: "member" }];+ const { container } = render(+ <LarkAgentBindButton agentId="agent-1" agentName="Bot" />,+ { wrapper: I18nWrapper },+ );+ expect(container.querySelector("button")).toBeNull();+ });++ it("hides the bind CTA when the device-flow install path is not wired on the server", () => {+ installationsRef.current.install_supported = false;+ const { container } = render(+ <LarkAgentBindButton agentId="agent-1" agentName="Bot" />,+ { wrapper: I18nWrapper },+ );+ expect(container.querySelector("button")).toBeNull();+ });++ it("swaps the bind CTA for a 'Connected + Manage in Lark' badge when this agent already has an active installation", () => {+ // Anti-zombie guard: re-scanning the same agent upserts the row+ // and orphans the previously-created Lark PersonalAgent. The badge+ // closes the install entry point and links the user to the Bot's+ // dev console page where scopes / display name / additional+ // permissions are actually managed.+ installationsRef.current.installations = [+ {+ id: "inst-1",+ workspace_id: "ws-1",+ agent_id: "agent-1",+ app_id: "cli_existing_app",+ bot_open_id: "ou_existing_bot",+ installer_user_id: "user-1",+ status: "active",+ installed_at: "2026-06-03T00:00:00Z",+ created_at: "2026-06-03T00:00:00Z",+ updated_at: "2026-06-03T00:00:00Z",+ },+ ];+ const { container } = render(+ <LarkAgentBindButton agentId="agent-1" agentName="Bot" />,+ { wrapper: I18nWrapper },+ );+ expect(container.querySelector("button")).toBeNull();+ expect(screen.getByText(/Connected to Lark/i)).toBeTruthy();+ const link = screen.getByRole("link", { name: /Manage in Lark/i }) as HTMLAnchorElement;+ expect(link.href).toBe("https://open.feishu.cn/app/cli_existing_app");+ expect(link.target).toBe("_blank");+ expect(link.rel).toContain("noopener");+ });++ it("still shows the bind CTA when an installation exists for a DIFFERENT agent (per-agent scoping)", () => {+ installationsRef.current.installations = [+ {+ id: "inst-other",+ workspace_id: "ws-1",+ agent_id: "agent-other",+ app_id: "cli_other",+ bot_open_id: "ou_other",+ installer_user_id: "user-1",+ status: "active",+ installed_at: "2026-06-03T00:00:00Z",+ created_at: "2026-06-03T00:00:00Z",+ updated_at: "2026-06-03T00:00:00Z",+ },+ ];+ render(<LarkAgentBindButton agentId="agent-1" agentName="Bot" />, {+ wrapper: I18nWrapper,+ });+ expect(screen.getByRole("button", { name: /Bind to Lark/i })).toBeTruthy();+ });++ it("still shows the bind CTA when this agent's only installation is revoked (treat as not-installed for re-bind)", () => {+ installationsRef.current.installations = [+ {+ id: "inst-revoked",+ workspace_id: "ws-1",+ agent_id: "agent-1",+ app_id: "cli_revoked",+ bot_open_id: "ou_revoked",+ installer_user_id: "user-1",+ status: "revoked",+ installed_at: "2026-06-03T00:00:00Z",+ created_at: "2026-06-03T00:00:00Z",+ updated_at: "2026-06-03T00:00:00Z",+ },+ ];+ render(<LarkAgentBindButton agentId="agent-1" agentName="Bot" />, {+ wrapper: I18nWrapper,+ });+ expect(screen.getByRole("button", { name: /Bind to Lark/i })).toBeTruthy();+ });+});++describe("LarkInstallDialog (polling terminal errors)", () => {+ beforeEach(() => {+ resetFixtures();+ vi.useFakeTimers({ shouldAdvanceTime: true });+ mockBeginInstall.mockResolvedValue({+ session_id: "sess-1",+ qr_code_url: "https://accounts.feishu.cn/oauth/v1/device?u=abc",+ expires_in_seconds: 300,+ poll_interval_seconds: 2,+ });+ });++ afterEach(() => {+ vi.useRealTimers();+ });++ async function openDialog() {+ const user = userEvent.setup({ advanceTimers: vi.advanceTimersByTime });+ render(<LarkAgentBindButton agentId="agent-1" agentName="Bot" />, {+ wrapper: I18nWrapper,+ });+ await user.click(screen.getByRole("button", { name: /Bind to Lark/i }));+ // Let the begin-session promise resolve and the QR render.+ await waitFor(() => {+ expect(screen.getByTestId("qr-code")).toBeTruthy();+ });+ }++ it("falls into a terminal session_lost error state when status polling 404s instead of looping forever", async () => {+ mockGetStatus.mockRejectedValue(+ new ApiError("install session not found", 404, "Not Found"),+ );++ await openDialog();+ // Drive the polling timer (intervalMs = max(2000, 2*1000)) and let+ // the rejected promise propagate into the catch.+ await act(async () => {+ await vi.advanceTimersByTimeAsync(2100);+ });++ await waitFor(() => {+ expect(+ screen.getByText(+ /Install session expired or was lost\. Scan again to start over\./i,+ ),+ ).toBeTruthy();+ });+ expect(screen.getByRole("button", { name: /Scan again/i })).toBeTruthy();+ // The dialog renders multiple Close affordances (footer button + the+ // built-in dialog dismiss); we only need to confirm at least one is+ // mounted alongside the retry button.+ expect(screen.getAllByRole("button", { name: /Close/i }).length).toBeGreaterThan(0);+ });++ it("treats 403 as a terminal forbidden error state (no infinite retry on revoked permission)", async () => {+ mockGetStatus.mockRejectedValue(+ new ApiError("forbidden", 403, "Forbidden"),+ );++ await openDialog();+ await act(async () => {+ await vi.advanceTimersByTimeAsync(2100);+ });++ await waitFor(() => {+ expect(+ screen.getByText(+ /You no longer have permission to install Lark Bots in this workspace/i,+ ),+ ).toBeTruthy();+ });+ // Drive another full poll interval — the polling loop must NOT+ // schedule a follow-up fetch after a terminal 4xx.+ const callsAfterTerminal = mockGetStatus.mock.calls.length;+ await act(async () => {+ await vi.advanceTimersByTimeAsync(5000);+ });+ expect(mockGetStatus.mock.calls.length).toBe(callsAfterTerminal);+ });++ // Regression test for the empty-dialog bug Bohan hit on PR #3277:+ // the QR area was completely blank after opening the dialog. React 19+ // StrictMode dev mounts every component twice. The mount/cleanup/mount+ // cycle preserves the component's useRef across the simulated remount,+ // so the cleanup's `closedRef.current = true` survived into the+ // second mount. Both beginSession() promises then saw closedRef=true+ // at the post-await guard and skipped setSession(), leaving the dialog+ // body with no QR, no error, no loading text — just empty. Resetting+ // closedRef.current at the START of the effect re-arms the guard on+ // every mount.+ it("renders the QR after a React StrictMode double-mount (regression for empty dialog body)", async () => {+ const user = userEvent.setup({ advanceTimers: vi.advanceTimersByTime });+ render(<LarkAgentBindButton agentId="agent-1" agentName="Bot" />, {+ wrapper: StrictModeWrapper,+ });+ await user.click(screen.getByRole("button", { name: /Bind to Lark/i }));++ // The QR must appear even though the dialog mounted, unmounted, and+ // mounted again under StrictMode. The previous bug left the body+ // empty here.+ await waitFor(+ () => {+ expect(screen.getByTestId("qr-code")).toBeTruthy();+ },+ { timeout: 2000 },+ );++ // And the QR's value should match what the (latest) begin call+ // returned — not be empty / undefined.+ const qr = screen.getByTestId("qr-code");+ expect(qr.getAttribute("data-value")).toBe(+ "https://accounts.feishu.cn/oauth/v1/device?u=abc",+ );+ });+});++// The Connected bots list used to surface Lark's raw cli_… app_id and+// ou_… bot_open_id, which are meaningless to product users. The row now+// renders the Multica agent's avatar + name (joined via inst.agent_id),+// since the binding is 1:1 with an Agent. These tests pin that identity+// rendering so the row never regresses to leaking the cli_ prefix.+describe("LarkTab connected bots list (agent identity rendering)", () => {+ beforeEach(resetFixtures);++ it("renders the Multica agent's name and avatar instead of the raw Lark app_id / bot_open_id", () => {+ agentNameByIdRef.current = new Map([["agent-1", "Bohan's Helper"]]);+ installationsRef.current.installations = [+ {+ id: "inst-1",+ workspace_id: "ws-1",+ agent_id: "agent-1",+ app_id: "cli_aa941499d4f95cd9",+ bot_open_id: "ou_abc123",+ installer_user_id: "user-1",+ status: "active",+ installed_at: "2026-06-03T00:00:00Z",+ created_at: "2026-06-03T00:00:00Z",+ updated_at: "2026-06-03T00:00:00Z",+ },+ ];++ render(<LarkTab />, { wrapper: I18nWrapper });++ // The agent's display name is the primary identifier.+ expect(screen.getByText("Bohan's Helper")).toBeTruthy();++ // The ActorAvatar stub records the actor it was asked to render —+ // confirms we joined on agent_id (and didn't accidentally pass the+ // bot_open_id or installation id).+ const avatar = screen.getByTestId("actor-avatar");+ expect(avatar.getAttribute("data-actor-type")).toBe("agent");+ expect(avatar.getAttribute("data-actor-id")).toBe("agent-1");++ // The raw Lark IDs are explicitly absent — the row must not leak+ // the cli_ / ou_ prefixes anymore.+ expect(screen.queryByText(/cli_aa941499d4f95cd9/)).toBeNull();+ expect(screen.queryByText(/ou_abc123/)).toBeNull();+ });++ it("falls back to a stable placeholder when the agent has been deleted (so the row is still actionable for cleanup)", () => {+ // Empty map → useActorName.getAgentName returns "Unknown Agent".+ // The row must still render so admins can hit Disconnect.+ installationsRef.current.installations = [+ {+ id: "inst-orphan",+ workspace_id: "ws-1",+ agent_id: "agent-deleted",+ app_id: "cli_orphan",+ bot_open_id: "ou_orphan",+ installer_user_id: "user-1",+ status: "active",+ installed_at: "2026-06-03T00:00:00Z",+ created_at: "2026-06-03T00:00:00Z",+ updated_at: "2026-06-03T00:00:00Z",+ },+ ];++ render(<LarkTab />, { wrapper: I18nWrapper });++ expect(screen.getByText(/Unknown Agent/)).toBeTruthy();+ // Disconnect stays reachable so the orphan row can be cleaned up.+ expect(screen.getByRole("button", { name: /Disconnect/i })).toBeTruthy();+ });+});diff --git a/packages/views/settings/components/lark-tab.tsx b/packages/views/settings/components/lark-tab.tsxnew file mode 100644index 0000000000..1f4b7f2a60--- /dev/null+++ b/packages/views/settings/components/lark-tab.tsx@@ -0,0 +1,653 @@+"use client";++import { useEffect, useRef, useState } from "react";+import { useQuery, useQueryClient } from "@tanstack/react-query";+import { toast } from "sonner";+import { ExternalLink, RefreshCw, Trash2 } from "lucide-react";+import QRCode from "react-qr-code";+import { Button } from "@multica/ui/components/ui/button";+import { Card, CardContent } from "@multica/ui/components/ui/card";+import {+ AlertDialog,+ AlertDialogAction,+ AlertDialogCancel,+ AlertDialogContent,+ AlertDialogDescription,+ AlertDialogFooter,+ AlertDialogHeader,+ AlertDialogTitle,+} from "@multica/ui/components/ui/alert-dialog";+import {+ Dialog,+ DialogContent,+ DialogHeader,+ DialogTitle,+ DialogDescription,+ DialogFooter,+} from "@multica/ui/components/ui/dialog";+import { useAuthStore } from "@multica/core/auth";+import { useWorkspaceId } from "@multica/core/hooks";+import { memberListOptions } from "@multica/core/workspace/queries";+import { useActorName } from "@multica/core/workspace/hooks";+import { larkInstallationsOptions, larkKeys } from "@multica/core/lark";+import { api, ApiError } from "@multica/core/api";+import type { LarkInstallation, LarkInstallStatusResponse } from "@multica/core/types";+import { ActorAvatar } from "../../common/actor-avatar";+import { useT } from "../../i18n";++// LarkTab is the workspace settings panel for Lark Bot installations.+// Listing is member-visible; the disconnect action is admin-only (the+// backend enforces it; the UI hides the button for non-admins to match).+//+// Adding a new installation flows through the Agent detail page: the+// install path is per-agent (each Multica Agent gets exactly one Bot —+// see the (workspace_id, agent_id) UNIQUE in lark_installation), so+// asking the user to pick an agent here would re-create that page's+// picker. The "Bind your first agent" copy in the empty state hints+// users at the right entry point.+export function LarkTab() {+ const { t } = useT("settings");+ const wsId = useWorkspaceId();+ const qc = useQueryClient();+ const user = useAuthStore((s) => s.user);++ const { data: members = [] } = useQuery(memberListOptions(wsId));+ const currentMember = members.find((m) => m.user_id === user?.id) ?? null;+ const canManage =+ currentMember?.role === "owner" || currentMember?.role === "admin";++ const { data, isLoading } = useQuery({+ ...larkInstallationsOptions(wsId),+ enabled: !!wsId,+ });+ const installations = data?.installations ?? [];+ const configured = data?.configured === true;+ // install_supported tracks whether the device-flow install path is+ // wired end-to-end on the server. When false, scan-to-bind would+ // fail at the post-poll bot-info step, so we hide install entry+ // points and surface a "coming soon" notice in their place rather+ // than send users into a broken flow. Already-installed bots still+ // appear in the listing below and remain manageable.+ const installSupported = data?.install_supported === true;++ const [disconnectTarget, setDisconnectTarget] = useState<string | null>(null);+ const [disconnecting, setDisconnecting] = useState(false);++ async function handleDisconnect() {+ if (!disconnectTarget || disconnecting) return;+ setDisconnecting(true);+ try {+ await api.deleteLarkInstallation(wsId, disconnectTarget);+ await qc.invalidateQueries({ queryKey: larkKeys.installations(wsId) });+ toast.success(t(($) => $.lark.toast_disconnected));+ setDisconnectTarget(null);+ } catch (e) {+ toast.error(e instanceof Error ? e.message : t(($) => $.lark.toast_disconnect_failed));+ } finally {+ setDisconnecting(false);+ }+ }++ return (+ <div className="space-y-8">+ <section className="space-y-1">+ <p className="text-sm text-muted-foreground">+ {t(($) => $.lark.page_description)}+ </p>+ </section>++ {!configured ? (+ <Card>+ <CardContent className="space-y-2">+ <p className="text-sm font-medium">{t(($) => $.lark.not_enabled_title)}</p>+ <p className="text-xs text-muted-foreground">+ {t(($) => $.lark.not_enabled_description_prefix)}{" "}+ <code className="rounded bg-muted px-1 py-0.5 text-[10px]">+ MULTICA_LARK_SECRET_KEY+ </code>{" "}+ {t(($) => $.lark.not_enabled_description_suffix)}{" "}+ {t(($) => $.lark.not_enabled_self_host_hint)}+ </p>+ </CardContent>+ </Card>+ ) : !installSupported && installations.length === 0 ? (+ // Device-flow install path is not wired (HTTP client is the stub+ // or RegistrationService didn't initialize). We deliberately do+ // NOT direct users to the agent-detail "Bind" button because the+ // backend would 503 anyway. Existing installations still render+ // via the branch below; this only hides the empty-state CTA+ // when there is nothing to manage.+ <Card>+ <CardContent className="space-y-2">+ <p className="text-sm font-medium">{t(($) => $.lark.preview_title)}</p>+ <p className="text-xs text-muted-foreground">+ {t(($) => $.lark.preview_description)}+ </p>+ </CardContent>+ </Card>+ ) : (+ <section className="space-y-3">+ <h2 className="text-sm font-semibold">{t(($) => $.lark.connected_bots)}</h2>+ {isLoading ? (+ <Card>+ <CardContent>+ <p className="text-sm text-muted-foreground">{t(($) => $.lark.loading)}</p>+ </CardContent>+ </Card>+ ) : installations.length === 0 ? (+ <Card>+ <CardContent className="space-y-2">+ <p className="text-sm font-medium">{t(($) => $.lark.empty_title)}</p>+ <p className="text-xs text-muted-foreground">+ {t(($) => $.lark.empty_description_prefix)}{" "}+ <strong>{t(($) => $.lark.empty_description_cta)}</strong>{" "}+ {t(($) => $.lark.empty_description_suffix)}+ </p>+ </CardContent>+ </Card>+ ) : (+ <Card>+ <CardContent className="divide-y">+ {installations.map((inst) => (+ <InstallationRow+ key={inst.id}+ installation={inst}+ canManage={canManage}+ onDisconnect={() => setDisconnectTarget(inst.id)}+ />+ ))}+ </CardContent>+ </Card>+ )}+ </section>+ )}++ <AlertDialog+ open={!!disconnectTarget}+ onOpenChange={(v) => {+ if (!v && !disconnecting) setDisconnectTarget(null);+ }}+ >+ <AlertDialogContent>+ <AlertDialogHeader>+ <AlertDialogTitle>+ {t(($) => $.lark.disconnect_confirm_title)}+ </AlertDialogTitle>+ <AlertDialogDescription>+ {t(($) => $.lark.disconnect_confirm_description)}+ </AlertDialogDescription>+ </AlertDialogHeader>+ <AlertDialogFooter>+ <AlertDialogCancel disabled={disconnecting}>+ {t(($) => $.lark.disconnect_confirm_cancel)}+ </AlertDialogCancel>+ <AlertDialogAction onClick={handleDisconnect} disabled={disconnecting}>+ {disconnecting+ ? t(($) => $.lark.disconnecting)+ : t(($) => $.lark.disconnect)}+ </AlertDialogAction>+ </AlertDialogFooter>+ </AlertDialogContent>+ </AlertDialog>+ </div>+ );+}++function InstallationRow({+ installation,+ canManage,+ onDisconnect,+}: {+ installation: LarkInstallation;+ canManage: boolean;+ onDisconnect: () => void;+}) {+ const { t } = useT("settings");+ // The bot is bound 1:1 to a Multica Agent (per the (workspace_id,+ // agent_id) UNIQUE in lark_installation). Render the Multica agent's+ // identity here rather than the raw Lark app_id / bot_open_id — those+ // mean nothing to product users. getAgentName falls back to+ // "Unknown Agent" when the agent has been deleted; the Disconnect+ // affordance below is the recovery path for that orphan row.+ const { getAgentName } = useActorName();+ const isActive = installation.status === "active";+ const agentName = getAgentName(installation.agent_id);+ return (+ <div className="flex items-start justify-between gap-4 py-3 first:pt-0 last:pb-0">+ <div className="flex items-start gap-3">+ <ActorAvatar+ actorType="agent"+ actorId={installation.agent_id}+ size={32}+ enableHoverCard+ profileLink+ />+ <div className="space-y-1">+ <p className="text-sm font-medium">+ {agentName}+ {!isActive && (+ <span className="ml-2 rounded bg-muted px-1.5 py-0.5 text-[10px] text-muted-foreground">+ {t(($) => $.lark.revoked_badge)}+ </span>+ )}+ </p>+ <p className="text-[10px] text-muted-foreground">+ {t(($) => $.lark.installed_at_label, {+ when: new Date(installation.installed_at).toLocaleString(),+ })}+ </p>+ </div>+ </div>+ {canManage && isActive && (+ <Button variant="outline" size="sm" onClick={onDisconnect}>+ <Trash2 className="h-3 w-3" />+ {t(($) => $.lark.disconnect)}+ </Button>+ )}+ </div>+ );+}++// LarkAgentBindButton is the per-agent CTA we expose from the agent+// detail page. The Settings panel above is the management view; this+// button is the entry point.+//+// The button hides itself when either:+// (a) the device-flow install path is not wired on the server+// (install_supported == false on the listing endpoint), or+// (b) the current viewer is not a workspace owner/admin — the backend+// gates `POST /lark/install/begin` and the status poll on those+// roles (see server/cmd/server/router.go:478-487), and+// `canEditAgent` lets agent owners through even when they're not+// workspace admins, so the parent's `canEdit` gate alone would+// expose a CTA that's guaranteed to 403.+// This is the "don't expose a flow that's guaranteed to fail"+// guarantee — both halves matter.+export function LarkAgentBindButton({+ agentId,+ agentName,+ className,+}: {+ agentId: string;+ agentName?: string;+ className?: string;+}) {+ const { t } = useT("settings");+ const wsId = useWorkspaceId();+ const user = useAuthStore((s) => s.user);+ const [dialogOpen, setDialogOpen] = useState(false);++ const { data: listing } = useQuery({+ ...larkInstallationsOptions(wsId),+ enabled: !!wsId,+ });+ const installSupported = listing?.install_supported === true;++ const { data: members = [] } = useQuery({+ ...memberListOptions(wsId),+ enabled: !!wsId,+ });+ const currentMember = members.find((m) => m.user_id === user?.id) ?? null;+ const canManage =+ currentMember?.role === "owner" || currentMember?.role === "admin";++ if (!installSupported || !canManage) return null;++ // Re-scanning the same agent overwrites the existing installation row+ // (lark_installation upserts on the (workspace_id, agent_id) UNIQUE)+ // and leaves the previously-created PersonalAgent dangling on Lark's+ // side as a zombie bot — users were getting trapped re-scanning when+ // they wanted to manage scopes. When this agent already has an+ // ACTIVE installation, we close the install entry point and surface+ // a link to the Bot's Lark app page instead, where scopes / display+ // name / additional permissions are managed.+ const existing = listing?.installations.find(+ (inst) => inst.agent_id === agentId && inst.status === "active",+ );+ if (existing) {+ return (+ <LarkAgentBotConnectedBadge installation={existing} className={className} />+ );+ }++ return (+ <>+ <Button+ variant="outline"+ size="sm"+ onClick={() => setDialogOpen(true)}+ disabled={!agentId}+ className={className}+ title={agentName ? t(($) => $.lark.bind_button_title, { agent: agentName }) : undefined}+ >+ <ExternalLink className="h-3 w-3" />+ {t(($) => $.lark.bind_button)}+ </Button>+ {dialogOpen && (+ <LarkInstallDialog+ wsId={wsId}+ agentId={agentId}+ agentName={agentName}+ onClose={() => setDialogOpen(false)}+ />+ )}+ </>+ );+}++// LarkAgentBotConnectedBadge is the "already connected" affordance the+// agent inspector renders in place of the Bind button when this agent+// has an active Lark installation. The badge is non-interactive (just+// a status pill), the Manage link opens the Bot's dev console page in+// a new tab so the user can manage scopes / display name / additional+// permissions without re-scanning the QR.+//+// The dev console URL host follows the same default as the backend's+// LARK_BASE_URL (open.feishu.cn for mainland Lark). Operators on the+// Lark international tenant currently see the wrong host; future-+// proofing requires the backend to surface a per-installation+// `dev_console_url` on the listings response. Tracked separately.+const LARK_DEV_CONSOLE_HOST = "https://open.feishu.cn";++function LarkAgentBotConnectedBadge({+ installation,+ className,+}: {+ installation: LarkInstallation;+ className?: string;+}) {+ const { t } = useT("settings");+ const manageHref = `${LARK_DEV_CONSOLE_HOST}/app/${encodeURIComponent(installation.app_id)}`;+ return (+ <div className={className} data-testid="lark-agent-bot-connected">+ <span className="inline-flex items-center gap-2 text-xs text-muted-foreground">+ <span className="inline-block h-2 w-2 rounded-full bg-emerald-500" />+ {t(($) => $.lark.agent_bot_connected_label)}+ </span>+ <a+ href={manageHref}+ target="_blank"+ rel="noopener noreferrer"+ className="ml-3 inline-flex items-center gap-1 text-xs text-primary underline-offset-2 hover:underline"+ title={t(($) => $.lark.agent_bot_manage_tooltip)}+ >+ <ExternalLink className="h-3 w-3" />+ {t(($) => $.lark.agent_bot_manage_link)}+ </a>+ </div>+ );+}++// LarkInstallDialog walks the user through the device-flow install:+// 1) POST /lark/install/begin → render QR+// 2) poll /lark/install/{sessionId}/status until success | error | expiry+// 3) on success: toast, close, invalidate installations cache+//+// The dialog deliberately re-fetches a fresh session on each "retry"+// rather than reusing a stale device_code — Lark's device_code is+// single-use and a re-render of the same QR after an error would just+// fail again at the next poll.+function LarkInstallDialog({+ wsId,+ agentId,+ agentName,+ onClose,+}: {+ wsId: string;+ agentId: string;+ agentName?: string;+ onClose: () => void;+}) {+ const { t } = useT("settings");+ const qc = useQueryClient();++ // We track session lifecycle as local state because TanStack Query is+ // optimized for cached server reads, and this dialog is a one-shot+ // flow whose entire state collapses on close. Using `useQuery` for+ // the polling would also fight TanStack's default refetch heuristics+ // (window focus, online/offline, retries) that have the wrong shape+ // for a single bounded session.+ const [session, setSession] = useState<null | {+ sessionId: string;+ qrCodeURL: string;+ expiresInSeconds: number;+ pollIntervalSeconds: number;+ }>(null);+ const [status, setStatus] = useState<LarkInstallStatusResponse["status"]>("pending");+ const [errorReason, setErrorReason] = useState<string | null>(null);+ const [errorMessage, setErrorMessage] = useState<string | null>(null);+ const [beginning, setBeginning] = useState(false);+ const closedRef = useRef(false);++ // beginSession is callable from both the initial mount and the+ // "scan again" action. Wrapping in a function (instead of a useEffect+ // dependency cascade) makes the retry path explicit.+ async function beginSession() {+ setBeginning(true);+ setStatus("pending");+ setErrorReason(null);+ setErrorMessage(null);+ setSession(null);+ try {+ const res = await api.beginLarkInstall(wsId, agentId);+ if (closedRef.current) return;+ setSession({+ sessionId: res.session_id,+ qrCodeURL: res.qr_code_url,+ expiresInSeconds: res.expires_in_seconds,+ pollIntervalSeconds: res.poll_interval_seconds,+ });+ } catch (e) {+ if (closedRef.current) return;+ setStatus("error");+ setErrorReason("internal_error");+ setErrorMessage(e instanceof Error ? e.message : String(e));+ } finally {+ setBeginning(false);+ }+ }++ // Kick off on mount.+ //+ // Reset closedRef AT THE START of every mount, not just at construction.+ // React 18+ / 19 StrictMode dev runs effects twice (mount → cleanup →+ // mount) on the same component instance, which preserves useRef across+ // the simulated remount. Without resetting, the cleanup from mount #1+ // flips closedRef.current=true, and on mount #2 every beginSession+ // promise sees closedRef=true at the await boundary and early-exits+ // before calling setSession — leaving the dialog body empty (no+ // "starting" placeholder, no QR, no error), which is exactly the+ // "QR never appears" bug. Reset on entry so the second mount+ // re-arms the in-flight cancellation guard.+ useEffect(() => {+ closedRef.current = false;+ void beginSession();+ return () => {+ closedRef.current = true;+ };+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, []);++ // Polling loop. Bounded by the device-flow expiry — once that+ // elapses Lark's server returns expired_token and our backend marks+ // the session errored, so we don't need a separate client-side+ // expiry timer.+ useEffect(() => {+ if (!session || status !== "pending") return;+ const intervalMs = Math.max(2000, session.pollIntervalSeconds * 1000);+ let cancelled = false;+ let timer: ReturnType<typeof setTimeout> | null = null;++ const poll = async () => {+ if (cancelled) return;+ try {+ const res = await api.getLarkInstallStatus(wsId, session.sessionId);+ if (cancelled) return;+ setStatus(res.status);+ if (res.status === "success") {+ await qc.invalidateQueries({ queryKey: larkKeys.installations(wsId) });+ toast.success(t(($) => $.lark.install_success_toast));+ // Close after a tiny beat so the user sees the success state+ // briefly before the dialog disappears.+ setTimeout(() => {+ if (!cancelled) onClose();+ }, 800);+ return;+ }+ if (res.status === "error") {+ setErrorReason(res.error_reason ?? "internal_error");+ setErrorMessage(res.error_message ?? null);+ return;+ }+ timer = setTimeout(poll, intervalMs);+ } catch (e) {+ if (cancelled) return;+ // Terminal HTTP states must NOT be retried — the session is+ // gone or the caller has lost permission, and polling forever+ // would trap the user on a stale QR with no error feedback.+ // 404: server restarted, multi-instance routed elsewhere, or+ // the in-process GC swept the session. Treat as session+ // lost — user has to scan a fresh QR.+ // 403: permission revoked mid-session (role downgrade, etc.).+ // The CTA gate prevents this on entry, but a role change+ // while the dialog is open would land here.+ // 401: the global ApiClient interceptor handles re-auth, so+ // reaching the catch with 401 means re-auth itself+ // failed — treat as terminal so the user doesn't loop.+ if (e instanceof ApiError) {+ if (e.status === 404) {+ setStatus("error");+ setErrorReason("session_lost");+ setErrorMessage(e.message);+ return;+ }+ if (e.status === 403 || e.status === 401) {+ setStatus("error");+ setErrorReason("forbidden");+ setErrorMessage(e.message);+ return;+ }+ }+ // Transient errors (network blip, 5xx) — schedule another+ // poll rather than killing the session. The next backend+ // status read will either confirm pending or surface the+ // terminal error the polling goroutine recorded.+ timer = setTimeout(poll, intervalMs);+ // Surface the message as a non-blocking toast for diagnostics.+ toast.message(t(($) => $.lark.install_poll_retry), {+ description: e instanceof Error ? e.message : String(e),+ });+ }+ };++ timer = setTimeout(poll, intervalMs);+ return () => {+ cancelled = true;+ if (timer) clearTimeout(timer);+ };+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [session?.sessionId, status]);++ return (+ <Dialog+ open+ onOpenChange={(o) => {+ if (!o) onClose();+ }}+ >+ <DialogContent className="max-w-sm">+ <DialogHeader>+ <DialogTitle>{t(($) => $.lark.install_dialog_title)}</DialogTitle>+ <DialogDescription>+ {agentName+ ? t(($) => $.lark.install_dialog_description_for_agent, { agent: agentName })+ : t(($) => $.lark.install_dialog_description)}+ </DialogDescription>+ </DialogHeader>++ <div className="flex flex-col items-center gap-4 py-2">+ {beginning && !session && (+ <p className="text-sm text-muted-foreground">{t(($) => $.lark.install_starting)}</p>+ )}++ {session && status === "pending" && (+ <>+ <div className="rounded-md border bg-white p-3">+ {/* react-qr-code renders an inline SVG — no external+ network image dependency, prints at any DPI. */}+ <QRCode value={session.qrCodeURL} size={192} />+ </div>+ <p className="text-center text-xs text-muted-foreground">+ {t(($) => $.lark.install_scan_hint)}+ </p>+ <a+ href={session.qrCodeURL}+ target="_blank"+ rel="noopener noreferrer"+ className="text-xs underline text-muted-foreground"+ >+ {t(($) => $.lark.install_open_link_fallback)}+ </a>+ </>+ )}++ {status === "success" && (+ <p className="text-sm font-medium">{t(($) => $.lark.install_success)}</p>+ )}++ {status === "error" && (+ <div className="space-y-2 text-center">+ <p className="text-sm font-medium text-destructive">+ {(() => {+ switch (errorReason) {+ case "expired":+ return t(($) => $.lark.install_error_expired);+ case "access_denied":+ return t(($) => $.lark.install_error_access_denied);+ case "lark_protocol_error":+ return t(($) => $.lark.install_error_protocol);+ case "bot_info_failed":+ return t(($) => $.lark.install_error_bot_info);+ case "installation_conflict":+ return t(($) => $.lark.install_error_conflict);+ case "installer_bind_failed":+ return t(($) => $.lark.install_error_installer_bind);+ case "session_lost":+ return t(($) => $.lark.install_error_session_lost);+ case "forbidden":+ return t(($) => $.lark.install_error_forbidden);+ default:+ return t(($) => $.lark.install_error_generic);+ }+ })()}+ </p>+ {errorMessage && (+ <p className="text-[10px] text-muted-foreground break-all">+ {errorMessage}+ </p>+ )}+ </div>+ )}+ </div>++ <DialogFooter>+ {status === "error" ? (+ <>+ <Button variant="outline" size="sm" onClick={onClose}>+ {t(($) => $.lark.install_close)}+ </Button>+ <Button size="sm" onClick={beginSession} disabled={beginning}>+ <RefreshCw className="h-3 w-3" />+ {t(($) => $.lark.install_retry)}+ </Button>+ </>+ ) : (+ <Button variant="outline" size="sm" onClick={onClose}>+ {t(($) => $.lark.install_close)}+ </Button>+ )}+ </DialogFooter>+ </DialogContent>+ </Dialog>+ );+}diff --git a/packages/views/settings/components/settings-page.tsx b/packages/views/settings/components/settings-page.tsxindex f324e28345..5dc317519f 100644--- a/packages/views/settings/components/settings-page.tsx+++ b/packages/views/settings/components/settings-page.tsx@@ -64,6 +64,14 @@ const WORKSPACE_TAB_ICONS = {const DEFAULT_TAB = "profile";const TAB_QUERY_KEY = "tab";+// Legacy `?tab=…` values that have been collapsed into another tab. Old+// bookmarks still land on the correct surface without us preserving a+// dead TabsContent entry. Lark used to be its own top-level workspace+// tab; it now lives inside Integrations.+const LEGACY_WORKSPACE_TAB_REDIRECTS: Record<string, string> = {+ lark: "integrations",+};+export interface ExtraSettingsTab {value: string;label: string;@@ -95,8 +103,11 @@ export function SettingsPage({ extraAccountTabs }: SettingsPageProps = {}) {);const tabFromUrl = navigation.searchParams.get(TAB_QUERY_KEY);+ const candidateTab = tabFromUrl+ ? LEGACY_WORKSPACE_TAB_REDIRECTS[tabFromUrl] ?? tabFromUrl+ : null;const activeTab =- tabFromUrl && validTabs.has(tabFromUrl) ? tabFromUrl : DEFAULT_TAB;+ candidateTab && validTabs.has(candidateTab) ? candidateTab : DEFAULT_TAB;// replace (not push) so settings tab switches don't pollute browser history.// Preserve any other query params the page may carry.diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex ca4374b2b1..1e92f7a84a 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -69,6 +69,9 @@ catalogs:react-i18next:specifier: ^17.0.6version: 17.0.6+ react-qr-code:+ specifier: ^2.0.18+ version: 2.0.21react-virtuoso:specifier: ^4.14.0version: 4.18.7@@ -1065,6 +1068,9 @@ importers:react-markdown:specifier: ^10.1.0version: 10.1.0(@types/[email protected])([email protected])+ react-qr-code:+ specifier: 'catalog:'+ version: 2.0.21([email protected])react-resizable-panels:specifier: ^4.7.5@@ -8956,6 +8962,9 @@ packages:resolution: {integrity: sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==}engines: {node: '>=6'}+ resolution: {integrity: sha512-c4iYnWb+k2E+vYpRimHqSu575b1/wKl4XFeJGpFmrJQz5I88v9aY2czh7s0w36srfCM1sXgC/xpoJz5dJfq+OQ==}+resolution: {integrity: sha512-mAZTtNCeetKMH+pSjrb76NAM8V9a05I9aBZOHztWy/UqcJdQYNsf59vrRKWnojAT9Y+GbIvoTBC++CPHqpDBhQ==}engines: {node: '>=0.6'}@@ -9162,6 +9171,11 @@ packages:'@types/react':optional: true+ resolution: {integrity: sha512-xaywjo0eaF4S3LOz6ns5eoPbM2E+q9HYl4VATYpxK4bBniOhQ9noY2RJ9G4SnZFhUwzx63FUT6KdHzfKgUwyuQ==}+ peerDependencies:+ react: '*'+resolution: {integrity: sha512-ROY9fvHhwOD9ySfrF0wmvu//bKCQ6AeZZq1nJNtbDC+kk5DuSuNX/n6YWYF/SYy7bSba4D4FSz8DJeKY/S/r+g==}peerDependencies:@@ -20334,6 +20348,8 @@ snapshots:+ [email protected]: {}+dependencies:side-channel: 1.1.0@@ -20606,6 +20622,12 @@ snapshots:- supports-color- utf-8-validate+ dependencies:+ prop-types: 15.8.1+ qr.js: 0.0.0+ react: 19.2.3+dependencies:'@types/use-sync-external-store': 0.0.6diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yamlindex 2db8c624e5..c2aaeef43c 100644--- a/pnpm-workspace.yaml+++ b/pnpm-workspace.yaml@@ -46,6 +46,11 @@ catalog:# Loading animations (chat StatusPill)unicode-animations: "^1.0.3"+ # QR rendering — Lark device-flow scan-to-install dialog renders the+ # verification_uri_complete as a QR so users can scan it from their+ # phone instead of typing the URL.+ "react-qr-code": "^2.0.18"+# Virtualized timeline (issue detail comments)react-virtuoso: "^4.14.0"diff --git a/server/cmd/server/main.go b/server/cmd/server/main.goindex b8d06b0ec2..0e29464041 100644--- a/server/cmd/server/main.go+++ b/server/cmd/server/main.go@@ -312,7 +312,7 @@ func main() {// shutdown so any pending bumps are flushed before we exit.heartbeatScheduler := handler.NewBatchedHeartbeatScheduler(queries, handler.DefaultHeartbeatBatchInterval)- r := NewRouterWithOptions(pool, hub, bus, analyticsClient, storeRedis, RouterOptions{+ r, h := NewRouterWithOptions(pool, hub, bus, analyticsClient, storeRedis, RouterOptions{HTTPMetrics: httpMetrics,BusinessMetrics: businessMetrics,DaemonHub: daemonHub,@@ -350,6 +350,16 @@ func main() {go runAutopilotFailureMonitor(autopilotCtx, queries, bus, envFailureMonitorConfig())go runDBStatsLogger(sweepCtx, pool)+ // Lark inbound supervisor: holds the §4.4 WS lease per installation+ // and runs the EventConnector for each. Nil when the Lark master+ // key is unset — self-host deployments that have not opted in to+ // Lark do not pay any goroutine cost. Lifecycle is bound to+ // sweepCtx so the Hub winds down alongside the other long-running+ // workers, AFTER the HTTP server has drained.+ if h.LarkHub != nil {+ go h.LarkHub.Run(sweepCtx)+ }+if metricsServer != nil {go func() {slog.Info("metrics server starting", "addr", metricsConfig.Addr)@@ -391,6 +401,22 @@ func main() {sweepCancel()heartbeatScheduler.Stop()+ // Join the Lark Hub's per-installation supervisor goroutines so the+ // lease renewer can issue a final release before process exit;+ // otherwise the next replica would have to wait the full LeaseTTL+ // before picking up the installation on the other side of the+ // redeploy. The wait is bounded — if a supervisor is wedged (DB+ // pool stalled, a future real EventConnector ignoring ctx, etc.)+ // the fallback is the natural LeaseTTL expiry on the other side,+ // which is strictly better than holding shutdown open forever.+ if h.LarkHub != nil {+ if !h.LarkHub.WaitWithTimeout(h.LarkHub.ShutdownTimeout()) {+ slog.Warn("lark hub: supervisors did not exit within shutdown timeout; proceeding",+ "timeout", h.LarkHub.ShutdownTimeout().String(),+ )+ }+ }+if metricsServer != nil {metricsShutdownCtx, metricsShutdownCancel := context.WithTimeout(context.Background(), 3*time.Second)if err := metricsServer.Shutdown(metricsShutdownCtx); err != nil {diff --git a/server/cmd/server/router.go b/server/cmd/server/router.goindex e655a6c068..147db50497 100644--- a/server/cmd/server/router.go+++ b/server/cmd/server/router.go@@ -22,12 +22,14 @@ import ("github.com/multica-ai/multica/server/internal/daemonws""github.com/multica-ai/multica/server/internal/events""github.com/multica-ai/multica/server/internal/handler"+ "github.com/multica-ai/multica/server/internal/integrations/lark"obsmetrics "github.com/multica-ai/multica/server/internal/metrics""github.com/multica-ai/multica/server/internal/middleware""github.com/multica-ai/multica/server/internal/realtime""github.com/multica-ai/multica/server/internal/service""github.com/multica-ai/multica/server/internal/storage""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")@@ -95,7 +97,8 @@ func parseTrustedProxies(raw string) []netip.Prefix {// keeps the default in-memory stores which are fine for single-node dev and// tests.func NewRouter(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus, analyticsClient analytics.Client, rdb *redis.Client) chi.Router {- return NewRouterWithOptions(pool, hub, bus, analyticsClient, rdb, RouterOptions{})+ r, _ := NewRouterWithOptions(pool, hub, bus, analyticsClient, rdb, RouterOptions{})+ return r}type RouterOptions struct {@@ -110,7 +113,14 @@ type RouterOptions struct {HeartbeatScheduler handler.HeartbeatScheduler}-func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus, analyticsClient analytics.Client, rdb *redis.Client, opts RouterOptions) chi.Router {+// NewRouterWithOptions builds the fully-configured Chi router and+// returns the *handler.Handler it was constructed from. Callers that+// need to drive background lifecycle on services attached to the+// handler (e.g. starting the Lark inbound Hub under a long-running+// context, calling Wait on shutdown) use the returned handler;+// callers that only need the HTTP handler (tests, the simple+// NewRouter shim) discard the second value.+func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus, analyticsClient analytics.Client, rdb *redis.Client, opts RouterOptions) (chi.Router, *handler.Handler) {queries := db.New(pool)emailSvc := service.NewEmailService()daemonHub := opts.DaemonHub@@ -145,6 +155,7 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bush := handler.New(queries, pool, hub, bus, emailSvc, store, cfSigner, analyticsClient, signupConfig, daemonHub)h.Metrics = opts.BusinessMetricsh.TaskService.Metrics = opts.BusinessMetrics+ h.IssueService.Metrics = opts.BusinessMetricsif opts.BusinessMetrics != nil {// Wire the BusinessMetrics receiver into the cloud runtime client// so every outbound Fleet/Gateway request feeds the@@ -165,6 +176,164 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bush.WebhookRateLimiter = handler.NewRedisWebhookRateLimiter(rdb, handler.DefaultWebhookRateLimit())h.WebhookIPRateLimiter = handler.NewRedisWebhookIPRateLimiter(rdb, handler.DefaultWebhookIPRateLimit())}++ // Lark integration. Only wired when MULTICA_LARK_SECRET_KEY is set:+ // the InstallationService refuses to fall back to plaintext storage+ // for app_secret, and the BindingTokenService cannot mint usable+ // tokens without it either. When the key is absent the Lark+ // handlers return 503 with a clear message; the rest of the server+ // continues to start so self-host deployments that have not opted+ // in to Lark are unaffected.+ if larkKey, err := secretbox.LoadKey("MULTICA_LARK_SECRET_KEY"); err == nil {+ box, err := secretbox.New(larkKey)+ if err != nil {+ slog.Error("lark: secretbox.New failed; lark integration disabled", "error", err)+ } else {+ installSvc, err := lark.NewInstallationService(queries, box)+ if err != nil {+ slog.Error("lark: InstallationService init failed; lark integration disabled", "error", err)+ } else {+ h.LarkInstallations = installSvc+ h.LarkBindingTokens = lark.NewBindingTokenService(queries, pool)+ slog.Info("lark integration enabled")++ // APIClient selection: when MULTICA_LARK_HTTP_ENABLED is+ // "true" the real Lark Open Platform HTTP client is wired+ // (IM v1 send/patch + binding-prompt + bot info).+ // Otherwise the stub stays in place and every outbound+ // call surfaces ErrAPIClientNotConfigured — useful for+ // deployments that want the inbound dispatcher / database+ // surface online without committing to a Lark app yet.+ //+ // MULTICA_LARK_HTTP_BASE_URL overrides the default+ // open.feishu.cn host (set to https://open.larksuite.com+ // for the Lark international tenant, or to a mock for+ // integration tests).+ var larkClient lark.APIClient+ if strings.EqualFold(strings.TrimSpace(os.Getenv("MULTICA_LARK_HTTP_ENABLED")), "true") {+ larkClient = lark.NewHTTPAPIClient(lark.HTTPClientConfig{+ BaseURL: strings.TrimSpace(os.Getenv("MULTICA_LARK_HTTP_BASE_URL")),+ Logger: slog.Default(),+ })+ slog.Info("lark http api client enabled")+ } else {+ larkClient = lark.NewStubAPIClient(slog.Default())+ }+ // Expose the APIClient to handlers so the install+ // surface can consult IsConfigured — install_supported+ // flips true only once the real HTTP client is wired+ // (the stub cannot complete the post-poll GetBotInfo+ // call that finalizes a device-flow install).+ h.LarkAPIClient = larkClient+ patcher := lark.NewPatcher(queries, installSvc, larkClient, lark.PatcherConfig{})+ patcher.Register(bus)++ // Inbound pipeline: lark_inbound_audit logger,+ // channel-aware ChatSessionService, and the+ // Dispatcher that orders identity / dedup / append /+ // /issue / enqueue per §4.3. The Dispatcher depends+ // on the same IssueService + TaskService that back+ // HTTP, so /issue-created issues share counter, dup+ // guard, project boundary, broadcast, analytics and+ // agent-enqueue with the rest of the product.+ auditLogger := lark.NewAuditLogger(queries)+ chatSvc := lark.NewChatSessionService(queries, pool)+ dispatcher := &lark.Dispatcher{+ Queries: queries,+ Chat: chatSvc,+ Audit: auditLogger,+ IssueService: h.IssueService,+ TaskService: h.TaskService,+ }++ // WS Hub: lease + supervisor goroutines per installation.+ // The factory we hand the Hub picks one of two+ // connectors:+ //+ // - NoopConnector (default): holds the lease + sweeps+ // supervisors against real DB rows without dialing+ // Lark. Used on staging boxes that need the lease /+ // reconnect lifecycle exercised before the live WS+ // protocol is enabled, and as the safe fallback when+ // the outbound HTTP APIClient is the stub (no real+ // bearer means no `connection_token` call).+ //+ // - WSLongConnConnector (MULTICA_LARK_WS_ENABLED=true):+ // real Lark long-conn over gorilla/websocket. The+ // connector wraps every read with a ctx-cancel+ // watchdog so lease loss / shutdown breaks the+ // blocking ReadMessage in bounded time — the+ // invariant §4.4 leans on. Requires the HTTP client+ // to be enabled because the connection_token POST+ // piggybacks on its tenant_access_token cache.+ connectorFactory, connectorLabel := buildLarkConnectorFactory(larkClient, installSvc)+ h.LarkHub = lark.NewHub(queries, connectorFactory, dispatcher, lark.HubConfig{})++ // OutcomeReplier wires the outbound side of the+ // EventEmitter contract: NeedsBinding / AgentOffline /+ // AgentArchived translate to a Lark-side reply card.+ // Requires the real APIClient (the stub returns+ // ErrAPIClientNotConfigured on every send) and the+ // binding token service. When either is missing, the+ // Hub falls back to the noop replier and the outcomes+ // get logged but not delivered — clearly visible in+ // boot output so operators understand the gap.+ replier := lark.NewLarkOutcomeReplier(lark.OutcomeReplierConfig{+ APIClient: larkClient,+ BindingSvc: h.LarkBindingTokens,+ Credentials: installSvc,+ Queries: queries,+ PublicURL: signupConfig.PublicURL,+ Logger: slog.Default(),+ })+ h.LarkHub.SetOutcomeReplier(replier)+ slog.Info("lark inbound pipeline wired", "connector", connectorLabel)++ // One-shot union_id backfill for installations created+ // before migration 112 added bot_union_id. Runs off the+ // hot startup path so a slow Lark round-trip cannot block+ // HTTP listener boot. New installs already write+ // bot_union_id during the device-flow finalize, so this+ // is bridge code — it will simply find no rows to update+ // on a fresh deployment and exit. MUL-2671.+ go lark.BackfillBotUnionIDs(context.Background(), queries, larkClient, installSvc, slog.Default())++ // Device-flow registration service: end-to-end install+ // pipeline that talks to accounts.feishu.cn (RFC 8628)+ // for the QR-scan handshake and then commits the+ // resulting Bot credentials + the installer's+ // lark_user_binding in one DB transaction. The optional+ // MULTICA_LARK_REGISTRATION_DOMAIN / _LARK_DOMAIN env+ // vars override the protocol hosts for staging / dev.+ if larkClient.IsConfigured() {+ regCfg := lark.RegistrationConfig{+ Domain: strings.TrimSpace(os.Getenv("MULTICA_LARK_REGISTRATION_DOMAIN")),+ LarkDomain: strings.TrimSpace(os.Getenv("MULTICA_LARK_REGISTRATION_LARK_DOMAIN")),+ }+ regClient := lark.NewRegistrationClient(regCfg)+ regSvc, rerr := lark.NewRegistrationService(+ lark.RegistrationServiceConfig{Logger: slog.Default()},+ regClient,+ larkClient,+ queries,+ pool,+ installSvc,+ h.LarkBindingTokens,+ )+ if rerr != nil {+ slog.Error("lark: RegistrationService init failed; install disabled", "error", rerr)+ } else {+ h.LarkRegistration = regSvc+ slog.Info("lark device-flow install enabled")+ }+ } else {+ slog.Info("lark device-flow install disabled (set MULTICA_LARK_HTTP_ENABLED=true to enable)")+ }+ }+ }+ } else {+ slog.Info("lark integration disabled (MULTICA_LARK_SECRET_KEY not set)")+ }if opts.HeartbeatScheduler != nil {h.HeartbeatScheduler = opts.HeartbeatScheduler}@@ -393,9 +562,39 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Busr.Get("/github/connect", h.GitHubConnect)r.Delete("/github/installations/{installationId}", h.DeleteGitHubInstallation)})++ // Lark integration. Listing is member-visible (same+ // rationale as GitHub: the Integrations tab must+ // render for non-admins so they see "wired up by whom").+ // Install / revoke require admin to prevent a non-admin+ // from binding a Bot to a workspace agent or yanking+ // an installation out from under one.+ r.Group(func(r chi.Router) {+ r.Use(middleware.RequireWorkspaceMemberFromURL(queries, "id"))+ r.Get("/lark/installations", h.ListLarkInstallations)+ })+ r.Group(func(r chi.Router) {+ r.Use(middleware.RequireWorkspaceRoleFromURL(queries, "id", "owner", "admin"))+ r.Delete("/lark/installations/{installationId}", h.RevokeLarkInstallation)+ // Device-flow scan-to-install. Begin opens a new+ // registration session against Lark and returns+ // the QR-code URL; the frontend dialog then polls+ // /install/{sessionId}/status until success or+ // terminal failure.+ r.Post("/lark/install/begin", h.BeginLarkInstall)+ r.Get("/lark/install/{sessionId}/status", h.GetLarkInstallStatus)+ })})})+ // Lark binding-token redemption. NOT workspace-scoped because+ // the redeemer hits this BEFORE they have any workspace+ // context — the redemption itself is what mints their+ // lark_user_binding row. Identity comes from the session;+ // the token only proves "this open_id requested binding," and+ // is combined with the logged-in user to create the mapping.+ r.Post("/api/lark/binding/redeem", h.RedeemLarkBindingToken)+// User-scoped invitation routes (no workspace context required)r.Get("/api/invitations", h.ListMyInvitations)r.Get("/api/invitations/{id}", h.GetMyInvitation)@@ -746,7 +945,65 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus})})- return r+ return r, h+}++// buildLarkConnectorFactory picks between the staging-mode+// NoopConnector and the real WS long-conn connector based on+// MULTICA_LARK_WS_ENABLED. The real connector talks to+// /callback/ws/endpoint directly with app_id/app_secret (no+// tenant_access_token bearer needed for the bootstrap), so it can+// run independently of MULTICA_LARK_HTTP_ENABLED — but outbound+// reply cards (binding prompt, offline / archived notices) require+// the HTTP APIClient. We still recommend enabling both together;+// when only WS is on, the OutcomeReplier surfaces a warning and+// downgrades to silent drops.+//+// Returns the factory plus a short label for the boot log so+// operators can see at a glance which mode they are in.+func buildLarkConnectorFactory(client lark.APIClient, installSvc *lark.InstallationService) (lark.ConnectorFactory, string) {+ if !strings.EqualFold(strings.TrimSpace(os.Getenv("MULTICA_LARK_WS_ENABLED")), "true") {+ return lark.NoopConnectorFactory(slog.Default()), "noop"+ }+ endpointFetcher, err := lark.NewHTTPConnectionTokenFetcher(lark.HTTPConnectionTokenConfig{+ BaseURL: strings.TrimSpace(os.Getenv("MULTICA_LARK_CALLBACK_BASE_URL")),+ Logger: slog.Default(),+ })+ if err != nil {+ slog.Error("lark ws: endpoint fetcher init failed; falling back to noop", "error", err)+ return lark.NoopConnectorFactory(slog.Default()), "noop"+ }+ decoder := lark.NewLarkJSONFrameDecoder()+ dialer := lark.NewGorillaDialer()+ credsProvider := lark.CredentialsProviderFunc(func(ctx context.Context, inst db.LarkInstallation) (lark.InstallationCredentials, error) {+ secret, err := installSvc.DecryptAppSecret(inst)+ if err != nil {+ return lark.InstallationCredentials{}, err+ }+ creds := lark.InstallationCredentials{+ AppID: inst.AppID,+ AppSecret: secret,+ }+ if inst.TenantKey.Valid {+ creds.TenantKey = inst.TenantKey.String+ }+ return creds, nil+ })+ conn, err := lark.NewWSLongConnConnector(lark.WSConnectorConfig{+ Dialer: dialer,+ EndpointFetcher: endpointFetcher,+ FrameDecoder: decoder,+ CredentialsProvider: credsProvider,+ Logger: slog.Default(),+ })+ if err != nil {+ slog.Error("lark ws: connector init failed; falling back to noop", "error", err)+ return lark.NoopConnectorFactory(slog.Default()), "noop"+ }+ _ = client // outbound APIClient flows in through OutcomeReplier wiring on the Hub+ return func(_ db.LarkInstallation) (lark.EventConnector, error) {+ return conn, nil+ }, "ws-long-conn"}// membershipChecker implements realtime.MembershipChecker using database queries.diff --git a/server/internal/handler/agent_access.go b/server/internal/handler/agent_access.goindex 88e0514f49..58cac9f181 100644--- a/server/internal/handler/agent_access.go+++ b/server/internal/handler/agent_access.go@@ -73,8 +73,6 @@ func (h *Handler) accessibleAgentIDs(ctx context.Context, workspaceID, actorType}return allowed, true}--// canEnqueueSquadLeader returns true when the given actor is allowed to// trigger the squad's private leader. It loads the leader agent and delegates// to canAccessPrivateAgent. Non-private leaders always pass. System-initiateddiff --git a/server/internal/handler/github.go b/server/internal/handler/github.goindex f124b428d5..679a050178 100644--- a/server/internal/handler/github.go+++ b/server/internal/handler/github.go@@ -525,8 +525,6 @@ func (h *Handler) HandleGitHubWebhook(w http.ResponseWriter, r *http.Request) {return}event := r.Header.Get("X-GitHub-Event")- action := extractGitHubAction(body)- h.Metrics.RecordGithubEventReceived(event, action)ctx := r.Context()switch event {case "ping":@@ -545,19 +543,6 @@ func (h *Handler) HandleGitHubWebhook(w http.ResponseWriter, r *http.Request) {w.WriteHeader(http.StatusAccepted)}-// extractGitHubAction sniffs the top-level "action" field from a webhook-// body without committing to a typed struct (each event has its own shape;-// we just need the verb for the metric label).-func extractGitHubAction(body []byte) string {- var probe struct {- Action string `json:"action"`- }- if err := json.Unmarshal(body, &probe); err != nil {- return ""- }- return probe.Action-}-func verifyWebhookSignature(secret, header string, body []byte) bool {const prefix = "sha256="if !strings.HasPrefix(header, prefix) {@@ -724,12 +709,6 @@ func (h *Handler) handlePullRequestEvent(ctx context.Context, body []byte) {return}- if state == "merged" {- if openSeconds := pullRequestMergeSeconds(p.PullRequest.CreatedAt, p.PullRequest.MergedAt); openSeconds > 0 {- h.Metrics.ObserveGithubPRMergeSeconds(openSeconds)- }- }-workspaceID := uuidToString(inst.WorkspaceID)resp := githubPullRequestToResponse(pr)@@ -1044,25 +1023,6 @@ func parseGHTimeRequired(s string) pgtype.Timestamptz {return t}-// pullRequestMergeSeconds returns the open-to-merge latency in seconds, or-// 0 (caller skips) when either timestamp is missing or the merge happened-// before the create timestamp (clock skew safety).-func pullRequestMergeSeconds(createdAt, mergedAt string) float64 {- created, err := time.Parse(time.RFC3339, createdAt)- if err != nil {- return 0- }- merged, err := time.Parse(time.RFC3339, mergedAt)- if err != nil {- return 0- }- delta := merged.Sub(created).Seconds()- if delta <= 0 {- return 0- }- return delta-}-// extractIdentifiers pulls every "PREFIX-NUMBER" match across the supplied// fields, deduplicating in input order.func extractIdentifiers(parts ...string) []string {diff --git a/server/internal/handler/handler.go b/server/internal/handler/handler.goindex 59579697f3..ad3e5d597a 100644--- a/server/internal/handler/handler.go+++ b/server/internal/handler/handler.go@@ -20,6 +20,7 @@ import ("github.com/multica-ai/multica/server/internal/cloudruntime""github.com/multica-ai/multica/server/internal/daemonws""github.com/multica-ai/multica/server/internal/events"+ "github.com/multica-ai/multica/server/internal/integrations/lark"obsmetrics "github.com/multica-ai/multica/server/internal/metrics""github.com/multica-ai/multica/server/internal/middleware""github.com/multica-ai/multica/server/internal/realtime"@@ -96,6 +97,7 @@ type Handler struct {DaemonHub *daemonws.HubBus *events.BusTaskService *service.TaskService+ IssueService *service.IssueServiceAutopilotService *service.AutopilotServiceEmailService *service.EmailServiceUpdateStore UpdateStore@@ -118,7 +120,42 @@ type Handler struct {WebhookRateLimiter WebhookRateLimiterWebhookIPRateLimiter WebhookRateLimiterCloudRuntime cloudRuntimeProxy- cfg Config+ // Lark integration. All three are nil when the Lark master key+ // (MULTICA_LARK_SECRET_KEY) is unset; the corresponding HTTP+ // handlers return 503 in that case so a misconfigured self-host+ // deployment surfaces a clear error instead of silently using a+ // zero key. Wired in cmd/server/router.go after handler.New.+ LarkInstallations *lark.InstallationService+ LarkBindingTokens *lark.BindingTokenService+ // LarkRegistration owns the device-flow install lifecycle: begin+ // a registration session against accounts.feishu.cn, poll, and+ // on success write lark_installation + the installer's+ // lark_user_binding in one DB transaction. Nil when either the+ // at-rest key is unset or the real Lark HTTP APIClient is not+ // wired (the stub cannot complete the post-poll GetBotInfo call).+ LarkRegistration *lark.RegistrationService+ // LarkAPIClient is the live transport that backs SendInteractiveCard,+ // PatchInteractiveCard, SendBindingPromptCard, GetBotInfo. It is+ // `lark.NewStubAPIClient(...)` until the real Lark HTTP client is+ // wired; the UI hides install entry points while IsConfigured()+ // is false so users do not land in a flow that is guaranteed to+ // fail at the bot-info step.+ LarkAPIClient lark.APIClient+ // LarkHub owns the per-installation supervisor goroutines that+ // hold the §4.4 WS lease and run the EventConnector. Nil only+ // when the master at-rest key (MULTICA_LARK_SECRET_KEY) is unset+ // — the inbound pipeline does NOT depend on the outbound HTTP+ // APIClient, so the Hub still wires up under the stub APIClient+ // (the dispatcher and renewer touch DB rows, not Lark wire I/O).+ // The router constructs the Hub but does NOT call Run on it; the+ // process owner (main.go) starts it under a long-running context+ // and joins via WaitWithTimeout (bounded wait, fenced by+ // ShutdownTimeout) during graceful shutdown so the lease renewer+ // can yield cleanly when the DB is healthy without blocking+ // process exit indefinitely if the pool is frozen — at worst the+ // next replica waits the full TTL.+ LarkHub *lark.Hub+ cfg Config}func New(queries *db.Queries, txStarter txStarter, hub *realtime.Hub, bus *events.Bus, emailService *service.EmailService, store storage.Storage, cfSigner *auth.CloudFrontSigner, analyticsClient analytics.Client, cfg Config, daemonHubs ...*daemonws.Hub) *Handler {@@ -146,6 +183,7 @@ func New(queries *db.Queries, txStarter txStarter, hub *realtime.Hub, bus *eventDaemonHub: daemonHub,Bus: bus,TaskService: taskSvc,+ IssueService: service.NewIssueService(queries, txStarter, bus, analyticsClient, taskSvc),AutopilotService: service.NewAutopilotService(queries, txStarter, bus, taskSvc),EmailService: emailService,UpdateStore: NewInMemoryUpdateStore(),diff --git a/server/internal/handler/handler_test.go b/server/internal/handler/handler_test.goindex aa78b4ea40..bbbcac44d9 100644--- a/server/internal/handler/handler_test.go+++ b/server/internal/handler/handler_test.go@@ -523,6 +523,115 @@ func TestCreateIssueExplicitBacklogPreserved(t *testing.T) {testHandler.DeleteIssue(httptest.NewRecorder(), cleanupReq)}+// TestCreateIssueRejectsCrossWorkspaceParent guards the workspace+// boundary check that lives in service.IssueService.Create. A request+// that pins parent_issue_id to an issue in a foreign workspace must be+// rejected before the row is created — this is the structural reason+// IssueService owns the parent lookup (not the HTTP handler). The test+// inserts a foreign workspace + issue directly via SQL, then drives the+// request through the regular handler entry point.+func TestCreateIssueRejectsCrossWorkspaceParent(t *testing.T) {+ ctx := context.Background()++ var otherWorkspaceID string+ if err := testPool.QueryRow(ctx, `+ INSERT INTO workspace (name, slug, description, issue_prefix)+ VALUES ($1, $2, $3, $4)+ RETURNING id+ `, "Cross-workspace parent test", "xwp-parent-test", "Foreign workspace", "XWP").Scan(&otherWorkspaceID); err != nil {+ t.Fatalf("insert foreign workspace: %v", err)+ }+ t.Cleanup(func() {+ testPool.Exec(ctx, `DELETE FROM workspace WHERE id = $1`, otherWorkspaceID)+ })++ var foreignParentID string+ if err := testPool.QueryRow(ctx, `+ INSERT INTO issue (workspace_id, title, status, priority, creator_type, creator_id, number)+ VALUES ($1, $2, 'todo', 'none', 'member', $3, 1)+ RETURNING id+ `, otherWorkspaceID, "Foreign parent", testUserID).Scan(&foreignParentID); err != nil {+ t.Fatalf("insert foreign parent: %v", err)+ }++ w := httptest.NewRecorder()+ req := newRequest("POST", "/api/issues?workspace_id="+testWorkspaceID, map[string]any{+ "title": "Should be rejected",+ "parent_issue_id": foreignParentID,+ })+ testHandler.CreateIssue(w, req)+ if w.Code != http.StatusBadRequest {+ t.Fatalf("CreateIssue with foreign parent: expected 400, got %d: %s", w.Code, w.Body.String())+ }+ if !strings.Contains(w.Body.String(), "parent issue not found in this workspace") {+ t.Fatalf("CreateIssue with foreign parent: expected boundary error message, got %s", w.Body.String())+ }++ var count int+ if err := testPool.QueryRow(ctx,+ `SELECT COUNT(*) FROM issue WHERE workspace_id = $1 AND title = $2`,+ testWorkspaceID, "Should be rejected",+ ).Scan(&count); err != nil {+ t.Fatalf("count query: %v", err)+ }+ if count != 0 {+ t.Fatalf("rejected create still wrote a row (count=%d) — service-layer boundary check failed", count)+ }+}++// TestCreateIssueRejectsCrossWorkspaceProject mirrors the parent test for+// the project workspace boundary. Same reasoning: future create entries+// (Lark /issue, MCP, API keys) must inherit this guard from the service+// without re-implementing it.+func TestCreateIssueRejectsCrossWorkspaceProject(t *testing.T) {+ ctx := context.Background()++ var otherWorkspaceID string+ if err := testPool.QueryRow(ctx, `+ INSERT INTO workspace (name, slug, description, issue_prefix)+ VALUES ($1, $2, $3, $4)+ RETURNING id+ `, "Cross-workspace project test", "xwp-project-test", "Foreign workspace", "XWP").Scan(&otherWorkspaceID); err != nil {+ t.Fatalf("insert foreign workspace: %v", err)+ }+ t.Cleanup(func() {+ testPool.Exec(ctx, `DELETE FROM workspace WHERE id = $1`, otherWorkspaceID)+ })++ var foreignProjectID string+ if err := testPool.QueryRow(ctx, `+ INSERT INTO project (workspace_id, title, status, priority)+ VALUES ($1, $2, 'planned', 'none')+ RETURNING id+ `, otherWorkspaceID, "Foreign project").Scan(&foreignProjectID); err != nil {+ t.Fatalf("insert foreign project: %v", err)+ }++ w := httptest.NewRecorder()+ req := newRequest("POST", "/api/issues?workspace_id="+testWorkspaceID, map[string]any{+ "title": "Should be rejected",+ "project_id": foreignProjectID,+ })+ testHandler.CreateIssue(w, req)+ if w.Code != http.StatusBadRequest {+ t.Fatalf("CreateIssue with foreign project: expected 400, got %d: %s", w.Code, w.Body.String())+ }+ if !strings.Contains(w.Body.String(), "project not found in this workspace") {+ t.Fatalf("CreateIssue with foreign project: expected boundary error message, got %s", w.Body.String())+ }++ var count int+ if err := testPool.QueryRow(ctx,+ `SELECT COUNT(*) FROM issue WHERE workspace_id = $1 AND title = $2`,+ testWorkspaceID, "Should be rejected",+ ).Scan(&count); err != nil {+ t.Fatalf("count query: %v", err)+ }+ if count != 0 {+ t.Fatalf("rejected create still wrote a row (count=%d) — service-layer boundary check failed", count)+ }+}+func TestCreateSubIssueInheritsParentProject(t *testing.T) {var projectID, parentID, childID stringdefer func() {diff --git a/server/internal/handler/issue.go b/server/internal/handler/issue.goindex cc73ea3184..f010dbe2c3 100644--- a/server/internal/handler/issue.go+++ b/server/internal/handler/issue.go@@ -15,12 +15,10 @@ import ("github.com/go-chi/chi/v5""github.com/jackc/pgx/v5/pgtype"- "github.com/multica-ai/multica/server/internal/analytics""github.com/multica-ai/multica/server/internal/issueguard"- "github.com/multica-ai/multica/server/internal/issueposition""github.com/multica-ai/multica/server/internal/logger"- obsmetrics "github.com/multica-ai/multica/server/internal/metrics""github.com/multica-ai/multica/server/internal/middleware"+ "github.com/multica-ai/multica/server/internal/service""github.com/multica-ai/multica/server/internal/util""github.com/multica-ai/multica/server/pkg/agent"db "github.com/multica-ai/multica/server/pkg/db/generated"@@ -2036,19 +2034,11 @@ func (h *Handler) CreateIssue(w http.ResponseWriter, r *http.Request) {return}parentIssueID = id- // Validate parent exists in the same workspace.- parent, err := h.Queries.GetIssueInWorkspace(r.Context(), db.GetIssueInWorkspaceParams{- ID: parentIssueID,- WorkspaceID: wsUUID,- })- if err != nil || !parent.ID.Valid {- writeError(w, http.StatusBadRequest, "parent issue not found in this workspace")- return- }- if req.ProjectID == nil {- projectID = parent.ProjectID- }}+ // Cross-workspace parent / project existence is enforced inside+ // IssueService.Create (atomically with the create), so every entry+ // point — HTTP, Lark, future MCP — gets the same boundary check+ // without duplicating the lookup here.attachmentIDs, ok := parseUUIDSliceOrBadRequest(w, req.AttachmentIDs, "attachment_ids")if !ok {@@ -2075,40 +2065,6 @@ func (h *Handler) CreateIssue(w http.ResponseWriter, r *http.Request) {dueDate = d}- // Use a transaction to atomically guard against active duplicates,- // increment the workspace issue counter, and create the issue.- tx, err := h.TxStarter.Begin(r.Context())- if err != nil {- writeError(w, http.StatusInternalServerError, "failed to create issue")- return- }- defer tx.Rollback(r.Context())-- qtx := h.Queries.WithTx(tx)- duplicate, foundDuplicate, err := issueguard.LockAndFindActiveDuplicate(r.Context(), qtx, wsUUID, projectID, parentIssueID, req.Title, req.AllowDuplicate)- if err != nil {- slog.Warn("duplicate issue guard failed", append(logger.RequestAttrs(r), "error", err, "workspace_id", workspaceID)...)- writeError(w, http.StatusInternalServerError, "failed to create issue")- return- }- if foundDuplicate {- prefix := h.getIssuePrefix(r.Context(), duplicate.WorkspaceID)- existing := issueToResponse(duplicate, prefix)- writeJSON(w, http.StatusConflict, map[string]any{- "code": "active_duplicate_issue",- "error": duplicateIssueMessage(existing),- "issue": existing,- })- return- }-- issueNumber, err := qtx.IncrementIssueCounter(r.Context(), wsUUID)- if err != nil {- slog.Warn("increment issue counter failed", append(logger.RequestAttrs(r), "error", err, "workspace_id", workspaceID)...)- writeError(w, http.StatusInternalServerError, "failed to create issue")- return- }-// Determine creator identity: agent (via X-Agent-ID header) or member.creatorType, actualCreatorID := h.resolveActor(r, creatorID, workspaceID)@@ -2138,141 +2094,90 @@ func (h *Handler) CreateIssue(w http.ResponseWriter, r *http.Request) {originID = oid}- newPosition, err := issueposition.NextTopPosition(r.Context(), tx, wsUUID, status)- if err != nil {- slog.Warn("get next issue position failed", append(logger.RequestAttrs(r), "error", err, "workspace_id", workspaceID, "status", status)...)- writeError(w, http.StatusInternalServerError, "failed to create issue")- return- }-- var issue db.Issue- if originType.Valid {- issue, err = qtx.CreateIssueWithOrigin(r.Context(), db.CreateIssueWithOriginParams{- WorkspaceID: wsUUID,- Title: req.Title,- Description: ptrToText(req.Description),- Status: status,- Priority: priority,- AssigneeType: assigneeType,- AssigneeID: assigneeID,- CreatorType: creatorType,- CreatorID: parseUUID(actualCreatorID),- ParentIssueID: parentIssueID,- Position: newPosition,- StartDate: startDate,- DueDate: dueDate,- Number: issueNumber,- ProjectID: projectID,- OriginType: originType,- OriginID: originID,- })- } else {- issue, err = qtx.CreateIssue(r.Context(), db.CreateIssueParams{- WorkspaceID: wsUUID,- Title: req.Title,- Description: ptrToText(req.Description),- Status: status,- Priority: priority,- AssigneeType: assigneeType,- AssigneeID: assigneeID,- CreatorType: creatorType,- CreatorID: parseUUID(actualCreatorID),- ParentIssueID: parentIssueID,- Position: newPosition,- StartDate: startDate,- DueDate: dueDate,- Number: issueNumber,- ProjectID: projectID,- })- }- if err != nil {- slog.Warn("create issue failed", append(logger.RequestAttrs(r), "error", err, "workspace_id", workspaceID)...)- writeError(w, http.StatusInternalServerError, "failed to create issue: "+err.Error())- return- }+ // Prefix is workspace-level; pre-compute once so both the broadcast+ // payload builder and the HTTP response share the same value.+ prefix := h.getIssuePrefix(r.Context(), wsUUID)- if err := tx.Commit(r.Context()); err != nil {- writeError(w, http.StatusInternalServerError, "failed to create issue")- return+ // Analytics agent ID: assignee agent when the issue is being assigned+ // to an agent, otherwise the creator agent for agent-authored issues.+ // Resolved here (not in the service) because creator identity is HTTP-side.+ analyticsAgentID := ""+ if assigneeType.Valid && assigneeType.String == "agent" {+ analyticsAgentID = uuidToString(assigneeID)+ }+ if creatorType == "agent" && analyticsAgentID == "" {+ analyticsAgentID = actualCreatorID}- // Link any pre-uploaded attachments to this issue.- if len(attachmentIDs) > 0 {- h.linkAttachmentsByIssueIDs(r.Context(), issue.ID, issue.WorkspaceID, attachmentIDs)+ buildAttachmentResponses := func(atts []db.Attachment) []AttachmentResponse {+ if len(atts) == 0 {+ return nil+ }+ out := make([]AttachmentResponse, len(atts))+ for i, a := range atts {+ out[i] = h.attachmentToResponse(a)+ }+ return out}- prefix := h.getIssuePrefix(r.Context(), issue.WorkspaceID)- resp := issueToResponse(issue, prefix)+ res, err := h.IssueService.Create(r.Context(), service.IssueCreateParams{+ WorkspaceID: wsUUID,+ Title: req.Title,+ Description: ptrToText(req.Description),+ Status: status,+ Priority: priority,+ AssigneeType: assigneeType,+ AssigneeID: assigneeID,+ CreatorType: creatorType,+ CreatorID: parseUUID(actualCreatorID),+ ParentIssueID: parentIssueID,+ ProjectID: projectID,+ StartDate: startDate,+ DueDate: dueDate,+ OriginType: originType,+ OriginID: originID,+ AttachmentIDs: attachmentIDs,+ AllowDuplicate: req.AllowDuplicate,+ }, service.IssueCreateOpts{+ ActorID: actualCreatorID,+ AnalyticsAgentID: analyticsAgentID,+ Platform: func() string { p, _, _ := middleware.ClientMetadataFromContext(r.Context()); return p }(),+ BroadcastPayload: func(issue db.Issue, atts []db.Attachment) map[string]any {+ payload := issueToResponse(issue, prefix)+ payload.Attachments = buildAttachmentResponses(atts)+ return map[string]any{"issue": payload}+ },+ })- // Fetch linked attachments so they appear in the response.- if len(attachmentIDs) > 0 {- attachments, err := h.Queries.ListAttachmentsByIssue(r.Context(), db.ListAttachmentsByIssueParams{- IssueID: issue.ID,- WorkspaceID: issue.WorkspaceID,+ if errors.Is(err, service.ErrActiveDuplicate) {+ dup := *res.DuplicateIssue+ existing := issueToResponse(dup, h.getIssuePrefix(r.Context(), dup.WorkspaceID))+ writeJSON(w, http.StatusConflict, map[string]any{+ "code": "active_duplicate_issue",+ "error": duplicateIssueMessage(existing),+ "issue": existing,})- if err == nil && len(attachments) > 0 {- resp.Attachments = make([]AttachmentResponse, len(attachments))- for i, a := range attachments {- resp.Attachments[i] = h.attachmentToResponse(a)- }- }+ return}-- slog.Info("issue created", append(logger.RequestAttrs(r), "issue_id", uuidToString(issue.ID), "title", issue.Title, "status", issue.Status, "workspace_id", workspaceID)...)- h.publish(protocol.EventIssueCreated, workspaceID, creatorType, actualCreatorID, map[string]any{"issue": resp})- analyticsActorID := actualCreatorID- analyticsAgentID := ""- if issue.AssigneeType.Valid && issue.AssigneeType.String == "agent" {- analyticsAgentID = uuidToString(issue.AssigneeID)+ if errors.Is(err, service.ErrParentIssueNotFound) {+ writeError(w, http.StatusBadRequest, "parent issue not found in this workspace")+ return}- if creatorType == "agent" {- analyticsActorID = "agent:" + actualCreatorID- if analyticsAgentID == "" {- analyticsAgentID = actualCreatorID- }+ if errors.Is(err, service.ErrProjectNotFound) {+ writeError(w, http.StatusBadRequest, "project not found in this workspace")+ return}- analyticsSource := analytics.SourceManual- analyticsTaskID := ""- analyticsAutopilotRunID := ""- if originType.Valid {- switch originType.String {- case "quick_create":- analyticsSource = analytics.SourceManual- analyticsTaskID = uuidToString(originID)- case "autopilot":- analyticsSource = analytics.SourceAutopilot- analyticsAutopilotRunID = uuidToString(originID)- default:- slog.Warn("analytics: unknown issue origin type",- "origin_type", originType.String,- "issue_id", uuidToString(issue.ID),- )- }- }- platform, _, _ := middleware.ClientMetadataFromContext(r.Context())- obsmetrics.RecordEvent(h.Analytics, h.Metrics, analytics.IssueCreated(- analyticsActorID,- workspaceID,- uuidToString(issue.ID),- analyticsAgentID,- analyticsTaskID,- analyticsAutopilotRunID,- analyticsSource,- platform,- ))-- // Enqueue agent task when an agent-assigned issue is created.- if issue.AssigneeType.Valid && issue.AssigneeID.Valid {- if h.shouldEnqueueAgentTask(r.Context(), issue) {- h.TaskService.EnqueueTaskForIssue(r.Context(), issue)- }- // Squad assigned at creation: trigger the squad leader (skipping- // backlog, same parking-lot semantics as agent assignment).- if h.shouldEnqueueSquadLeaderOnAssign(r.Context(), issue) {- h.enqueueSquadLeaderTask(r.Context(), issue, pgtype.UUID{}, creatorType, actualCreatorID)- }+ if err != nil {+ slog.Warn("create issue failed", append(logger.RequestAttrs(r), "error", err, "workspace_id", workspaceID)...)+ writeError(w, http.StatusInternalServerError, "failed to create issue: "+err.Error())+ return}+ issue := res.Issue+ slog.Info("issue created", append(logger.RequestAttrs(r), "issue_id", uuidToString(issue.ID), "title", issue.Title, "status", issue.Status, "workspace_id", workspaceID)...)++ resp := issueToResponse(issue, prefix)+ resp.Attachments = buildAttachmentResponses(res.Attachments)writeJSON(w, http.StatusCreated, resp)}diff --git a/server/internal/handler/lark.go b/server/internal/handler/lark.gonew file mode 100644index 0000000000..ec5b047bcc--- /dev/null+++ b/server/internal/handler/lark.go@@ -0,0 +1,357 @@+package handler++import (+ "encoding/json"+ "errors"+ "net/http"+ "strings"+ "time"++ "github.com/go-chi/chi/v5"+ "github.com/multica-ai/multica/server/internal/integrations/lark"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+ "github.com/multica-ai/multica/server/pkg/protocol"+)++// LarkInstallationResponse is the wire shape for an installation row.+// `app_secret_encrypted` is INTENTIONALLY absent — the encrypted blob+// is server-internal and there is no product reason to expose it (the+// only consumer that needs the plaintext is the WS hub, which calls+// 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"`+ InstalledAt string `json:"installed_at"`+ CreatedAt string `json:"created_at"`+ UpdatedAt string `json:"updated_at"`+}++func larkInstallationToResponse(row db.LarkInstallation) 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,+ 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+ resp.TenantKey = &tk+ }+ return resp+}++// ListLarkInstallations (GET /api/workspaces/{id}/lark/installations)+// is member-visible — the Integrations tab should not render blank+// for non-admins. Unlike the GitHub list, we do not strip any field+// here because no API surface column doubles as a management handle:+// revocation goes by the UUID id, which is meaningless without the+// admin route's authorization, so exposing it is harmless.+//+// Response fields:+// - configured: at-rest encryption key is set (`LarkInstallations+// != nil`). When false, no install flow can succeed at all; the+// UI hides the tab.+// - install_supported: the device-flow install path is wired+// end-to-end: a RegistrationService exists (deployment supplied+// MULTICA_LARK_SECRET_KEY) AND the APIClient.IsConfigured signal+// is true (the real Lark HTTP client is in place — the stub+// cannot complete the post-poll GetBotInfo call). When false,+// the agent-detail "Bind" button stays hidden and the Settings+// tab surfaces a "coming soon" notice; already-installed bots+// still appear and remain manageable.+func (h *Handler) ListLarkInstallations(w http.ResponseWriter, r *http.Request) {+ if h.LarkInstallations == nil {+ writeJSON(w, http.StatusOK, map[string]any{+ "installations": []LarkInstallationResponse{},+ "configured": false,+ "install_supported": false,+ })+ return+ }+ wsUUID, ok := parseUUIDOrBadRequest(w, chi.URLParam(r, "id"), "workspace id")+ if !ok {+ return+ }+ rows, err := h.LarkInstallations.ListByWorkspace(r.Context(), wsUUID)+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to list lark installations")+ return+ }+ out := make([]LarkInstallationResponse, 0, len(rows))+ for _, row := range rows {+ out = append(out, larkInstallationToResponse(row))+ }+ writeJSON(w, http.StatusOK, map[string]any{+ "installations": out,+ "configured": true,+ "install_supported": h.LarkRegistration != nil && h.LarkAPIClient != nil && h.LarkAPIClient.IsConfigured(),+ })+}++// RevokeLarkInstallation (DELETE /api/workspaces/{id}/lark/installations/{installationId})+// flips status to 'revoked' so the WS hub drops the connection on its+// next sweep. The row itself is preserved for audit; a re-install via+// the device-flow path flips status back to 'active' atomically.+func (h *Handler) RevokeLarkInstallation(w http.ResponseWriter, r *http.Request) {+ if h.LarkInstallations == nil {+ writeError(w, http.StatusServiceUnavailable, "lark integration not configured")+ return+ }+ userID, ok := requireUserID(w, r)+ if !ok {+ return+ }+ wsUUID, ok := parseUUIDOrBadRequest(w, chi.URLParam(r, "id"), "workspace id")+ if !ok {+ return+ }+ instUUID, ok := parseUUIDOrBadRequest(w, chi.URLParam(r, "installationId"), "installation id")+ if !ok {+ return+ }+ // Workspace-scoped lookup ensures one workspace cannot revoke+ // another's installation by guessing the UUID.+ if _, err := h.LarkInstallations.GetInWorkspace(r.Context(), instUUID, wsUUID); err != nil {+ if errors.Is(err, lark.ErrInstallationNotFound) {+ writeError(w, http.StatusNotFound, "lark installation not found")+ return+ }+ writeError(w, http.StatusInternalServerError, "failed to load installation")+ return+ }+ if err := h.LarkInstallations.Revoke(r.Context(), instUUID); err != nil {+ writeError(w, http.StatusInternalServerError, "failed to revoke installation")+ return+ }+ h.publish(protocol.EventLarkInstallationRevoked, uuidToString(wsUUID), "user", userID, map[string]any{+ "id": uuidToString(instUUID),+ })+ w.WriteHeader(http.StatusNoContent)+}++// RedeemLarkBindingTokenRequest carries the raw token the user+// clicked through from the Bot's "you need to bind" reply card.+type RedeemLarkBindingTokenRequest struct {+ Token string `json:"token"`+}++// RedeemLarkBindingTokenResponse is the post-redemption shape. We+// echo the workspace/installation/open_id so the frontend can render+// "you are now bound to <workspace> via <agent>" without a second+// fetch.+type RedeemLarkBindingTokenResponse struct {+ WorkspaceID string `json:"workspace_id"`+ InstallationID string `json:"installation_id"`+ LarkOpenID string `json:"lark_open_id"`+}++// RedeemLarkBindingToken (POST /api/lark/binding/redeem) is the only+// path that writes a lark_user_binding row from user-driven action.+// The redeemer's identity is taken from the session, not the token,+// so a stolen token cannot bind a Lark open_id to an attacker's+// Multica account. The token only proves "this open_id requested+// binding" — combining it with the logged-in user is what creates+// the (open_id ↔ user) mapping.+//+// Consume + bind happen inside a single DB transaction (see+// lark.BindingTokenService.RedeemAndBind). The three failure modes+// each map to a distinct status code so the frontend can render the+// appropriate copy without a separate probe:+// - 410 Gone: token unknown / consumed / expired+// - 409 Conflict: open_id is already bound to a different user+// - 403 Forbidden: redeemer is not a workspace member+func (h *Handler) RedeemLarkBindingToken(w http.ResponseWriter, r *http.Request) {+ if h.LarkBindingTokens == nil {+ writeError(w, http.StatusServiceUnavailable, "lark integration not configured")+ return+ }+ userID, ok := requireUserID(w, r)+ if !ok {+ return+ }+ var req RedeemLarkBindingTokenRequest+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil {+ writeError(w, http.StatusBadRequest, "invalid request body")+ return+ }+ if req.Token == "" {+ writeError(w, http.StatusBadRequest, "token is required")+ return+ }+ userUUID, ok := parseUUIDOrBadRequest(w, userID, "user id")+ if !ok {+ return+ }++ redeemed, err := h.LarkBindingTokens.RedeemAndBind(r.Context(), req.Token, userUUID)+ if err != nil {+ switch {+ case errors.Is(err, lark.ErrBindingTokenInvalid):+ writeError(w, http.StatusGone, "binding token invalid or expired")+ case errors.Is(err, lark.ErrBindingAlreadyAssigned):+ writeError(w, http.StatusConflict, "this Lark account is already bound to a different Multica user")+ case errors.Is(err, lark.ErrBindingNotWorkspaceMember):+ writeError(w, http.StatusForbidden, "binding refused (are you a workspace member?)")+ default:+ writeError(w, http.StatusInternalServerError, "failed to redeem token")+ }+ return+ }++ writeJSON(w, http.StatusOK, RedeemLarkBindingTokenResponse{+ WorkspaceID: uuidToString(redeemed.WorkspaceID),+ InstallationID: uuidToString(redeemed.InstallationID),+ LarkOpenID: string(redeemed.LarkOpenID),+ })+}++// BeginLarkInstallResponse is the payload the QR-code dialog consumes.+// The frontend renders `qr_code_url` as a QR image (and as a tap-to-+// open link fallback) and starts polling+// /lark/install/{session_id}/status at the supplied cadence.+type BeginLarkInstallResponse struct {+ SessionID string `json:"session_id"`+ QRCodeURL string `json:"qr_code_url"`+ ExpiresInSeconds int `json:"expires_in_seconds"`+ PollIntervalSeconds int `json:"poll_interval_seconds"`+}++// BeginLarkInstall (POST /api/workspaces/{id}/lark/install/begin)+// opens a new device-flow registration session against Lark. Admin-only+// at the router. The agent_id query param picks which Multica Agent+// the new Bot will be bound to; the agent must belong to this+// workspace (RegistrationService re-checks that defense-in-depth).+//+// Returns 503 when the integration is not wired (no at-rest key, no+// HTTP client, no RegistrationService); the UI hides the bind button+// in that case so this should not be reached through the normal flow.+func (h *Handler) BeginLarkInstall(w http.ResponseWriter, r *http.Request) {+ if h.LarkRegistration == nil {+ writeError(w, http.StatusServiceUnavailable, "lark install not configured")+ 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+ }+ // Ownership pre-check at the HTTP boundary so a malformed+ // agent_id surfaces 404 here (not an opaque service error from+ // inside the service's own re-check).+ 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.LarkRegistration.BeginInstall(r.Context(), lark.BeginInstallParams{+ WorkspaceID: wsUUID,+ AgentID: agentUUID,+ InitiatorID: initiatorUUID,+ })+ if err != nil {+ writeError(w, http.StatusBadGateway, "failed to start install: "+err.Error())+ return+ }+ writeJSON(w, http.StatusOK, BeginLarkInstallResponse{+ SessionID: res.SessionID,+ QRCodeURL: res.QRCodeURL,+ ExpiresInSeconds: res.ExpiresInSeconds,+ PollIntervalSeconds: res.PollIntervalSeconds,+ })+}++// LarkInstallStatusResponse is the polling payload. `status` is one+// of "pending" | "success" | "error"; on success `installation_id`+// is populated, on error `error_reason` is a stable code (see+// lark.RegistrationReason*).+type LarkInstallStatusResponse struct {+ Status string `json:"status"`+ InstallationID string `json:"installation_id,omitempty"`+ ErrorReason string `json:"error_reason,omitempty"`+ ErrorMessage string `json:"error_message,omitempty"`+}++// GetLarkInstallStatus (GET /api/workspaces/{id}/lark/install/{sessionId}/status)+// returns the current state of an in-flight install session. Admin-+// only at the router. Unknown / cross-workspace / GC'd sessions return+// 404 — the frontend treats it as "session lost, please restart".+//+// On success this handler does NOT clean up the session — the+// frontend may poll once more after the dialog closes to confirm+// before the in-process GC sweep retires the entry; reading is+// idempotent.+func (h *Handler) GetLarkInstallStatus(w http.ResponseWriter, r *http.Request) {+ if h.LarkRegistration == nil {+ writeError(w, http.StatusServiceUnavailable, "lark install not configured")+ return+ }+ wsUUID, ok := parseUUIDOrBadRequest(w, chi.URLParam(r, "id"), "workspace id")+ if !ok {+ return+ }+ sessionID := strings.TrimSpace(chi.URLParam(r, "sessionId"))+ if sessionID == "" {+ writeError(w, http.StatusBadRequest, "session id is required")+ return+ }+ state, err := h.LarkRegistration.GetSession(wsUUID, sessionID)+ if err != nil {+ if errors.Is(err, lark.ErrRegistrationSessionNotFound) {+ writeError(w, http.StatusNotFound, "install session not found")+ return+ }+ writeError(w, http.StatusInternalServerError, "failed to load install session")+ return+ }+ resp := LarkInstallStatusResponse{+ Status: string(state.Status),+ ErrorReason: state.ErrorReason,+ ErrorMessage: state.ErrorMessage,+ }+ if state.InstallationID.Valid {+ resp.InstallationID = uuidToString(state.InstallationID)+ // Successful install — emit the lark_installation:created+ // event so listeners (Settings tab, agent detail page) refresh+ // without waiting for the frontend's cache invalidation.+ // Idempotent: the event handler keys on installation_id, and+ // a duplicate emit is a no-op refresh.+ if state.Status == lark.RegistrationStatusSuccess {+ h.publish(protocol.EventLarkInstallationCreated, uuidToString(wsUUID), "system", "", map[string]any{+ "installation_id": resp.InstallationID,+ })+ }+ }+ writeJSON(w, http.StatusOK, resp)+}diff --git a/server/internal/handler/lark_test.go b/server/internal/handler/lark_test.gonew file mode 100644index 0000000000..87f6cd19fb--- /dev/null+++ b/server/internal/handler/lark_test.go@@ -0,0 +1,162 @@+package handler++import (+ "encoding/json"+ "log/slog"+ "net/http"+ "net/http/httptest"+ "strings"+ "testing"++ "github.com/multica-ai/multica/server/internal/integrations/lark"+)++// Lark-handler unit tests focus on the no-config short-circuits —+// verifying that a self-host deployment without MULTICA_LARK_SECRET_KEY+// does NOT serve revoke / redeem / install, and that list degrades+// gracefully to an empty response so the Integrations tab still+// renders. Happy-path flows (begin device-flow + poll status; token+// mint + redeem) need a real DB and land alongside the WS hub+// integration tests in a follow-up commit.++func TestRevokeLarkInstallation_NotConfigured(t *testing.T) {+ h := &Handler{}+ req := httptest.NewRequest(http.MethodDelete, "/api/workspaces/x/lark/installations/y", nil)+ w := httptest.NewRecorder()+ h.RevokeLarkInstallation(w, req)+ if w.Code != http.StatusServiceUnavailable {+ t.Fatalf("expected 503, got %d", w.Code)+ }+}++func TestRedeemLarkBindingToken_NotConfigured(t *testing.T) {+ h := &Handler{}+ req := httptest.NewRequest(http.MethodPost, "/api/lark/binding/redeem", strings.NewReader(`{"token":"x"}`))+ w := httptest.NewRecorder()+ h.RedeemLarkBindingToken(w, req)+ if w.Code != http.StatusServiceUnavailable {+ t.Fatalf("expected 503, got %d", w.Code)+ }+}++func TestBeginLarkInstall_NotConfigured(t *testing.T) {+ // When the device-flow registration service is nil (no at-rest+ // key, or the stub APIClient is the only one wired), the begin+ // endpoint must short-circuit to 503 — silently returning a+ // "configured: false" envelope would hide a real misconfiguration+ // from the operator. The UI hides the bind button in that case+ // so this should not be reached through the normal flow.+ h := &Handler{}+ req := httptest.NewRequest(http.MethodPost, "/api/workspaces/x/lark/install/begin?agent_id=y", nil)+ w := httptest.NewRecorder()+ h.BeginLarkInstall(w, req)+ if w.Code != http.StatusServiceUnavailable {+ t.Fatalf("expected 503, got %d body=%s", w.Code, w.Body.String())+ }+}++func TestGetLarkInstallStatus_NotConfigured(t *testing.T) {+ h := &Handler{}+ req := httptest.NewRequest(http.MethodGet, "/api/workspaces/x/lark/install/sess_y/status", nil)+ w := httptest.NewRecorder()+ h.GetLarkInstallStatus(w, req)+ if w.Code != http.StatusServiceUnavailable {+ t.Fatalf("expected 503, got %d", w.Code)+ }+}++func TestListLarkInstallations_NotConfiguredReturnsEmpty(t *testing.T) {+ // Listing is intentionally a "soft" endpoint: when lark is not+ // configured we return an empty list + configured:false rather+ // than a 503, so the Integrations tab renders normally with a+ // "not connected" empty state instead of an error banner.+ h := &Handler{}+ req := httptest.NewRequest(http.MethodGet, "/api/workspaces/x/lark/installations", nil)+ w := httptest.NewRecorder()+ h.ListLarkInstallations(w, req)+ if w.Code != http.StatusOK {+ t.Fatalf("expected 200, got %d body=%s", w.Code, w.Body.String())+ }+ var resp struct {+ Installations []any `json:"installations"`+ Configured bool `json:"configured"`+ InstallSupported bool `json:"install_supported"`+ }+ if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {+ t.Fatalf("decode: %v", err)+ }+ if resp.Configured {+ t.Fatalf("configured should be false when LarkInstallations is nil")+ }+ if resp.InstallSupported {+ t.Fatalf("install_supported should be false when LarkInstallations is nil")+ }+ if len(resp.Installations) != 0 {+ t.Fatalf("expected empty installations list, got %d", len(resp.Installations))+ }+}++// TestListLarkInstallations_StubClientReportsInstallNotSupported pins+// the front-half of the "don't expose a doomed install flow"+// guarantee: even when the at-rest key + registration service are set,+// install_supported flips false if the underlying APIClient is the+// stub. The stub cannot complete the post-poll GetBotInfo call that+// finalizes a device-flow install, so the UI must hide install entry+// points until a real client is wired.+func TestListLarkInstallations_StubClientReportsInstallNotSupported(t *testing.T) {+ stubLogger := slog.New(slog.NewTextHandler(httptest.NewRecorder(), nil))+ h := &Handler{+ LarkAPIClient: lark.NewStubAPIClient(stubLogger),+ }+ req := httptest.NewRequest(http.MethodGet, "/api/workspaces/x/lark/installations", nil)+ w := httptest.NewRecorder()+ h.ListLarkInstallations(w, req)+ if w.Code != http.StatusOK {+ t.Fatalf("expected 200, got %d", w.Code)+ }+ var resp struct {+ Configured bool `json:"configured"`+ InstallSupported bool `json:"install_supported"`+ }+ if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {+ t.Fatalf("decode: %v", err)+ }+ if resp.InstallSupported {+ t.Fatalf("install_supported must be false while only stub APIClient is wired")+ }+}++// TestListLarkInstallations_NotConfigured_HardCodedInstallSupportedFalse+// pins the invariant for the early-return branch: when+// LarkInstallations is nil (the deployment has no at-rest encryption+// key wired), the response MUST return both configured:false AND+// install_supported:false regardless of what APIClient is in place.+// A real APIClient on a not-configured deployment must not flip+// install_supported via the APIClient path — that path is not+// consulted in the early-return branch.+func TestListLarkInstallations_NotConfigured_HardCodedInstallSupportedFalse(t *testing.T) {+ stubLogger := slog.New(slog.NewTextHandler(httptest.NewRecorder(), nil))+ h := &Handler{+ LarkInstallations: nil, // triggers the not-configured early return.+ LarkAPIClient: lark.NewStubAPIClient(stubLogger),+ }+ req := httptest.NewRequest(http.MethodGet, "/api/workspaces/x/lark/installations", nil)+ w := httptest.NewRecorder()+ h.ListLarkInstallations(w, req)+ if w.Code != http.StatusOK {+ t.Fatalf("expected 200, got %d", w.Code)+ }+ var resp struct {+ Configured bool `json:"configured"`+ InstallSupported bool `json:"install_supported"`+ }+ if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {+ t.Fatalf("decode: %v", err)+ }+ if resp.Configured {+ t.Fatalf("configured must be false when LarkInstallations is nil")+ }+ if resp.InstallSupported {+ t.Fatalf("install_supported must be false in the early-return branch even with a non-nil APIClient")+ }+}diff --git a/server/internal/integrations/lark/audit.go b/server/internal/integrations/lark/audit.gonew file mode 100644index 0000000000..73eba9c812--- /dev/null+++ b/server/internal/integrations/lark/audit.go@@ -0,0 +1,45 @@+package lark++import (+ "context"++ "github.com/jackc/pgx/v5/pgtype"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++// dbAuditLogger is the concrete AuditLogger implementation backed by+// lark_inbound_audit. It deliberately holds no caches and no+// indirection — the RecordLarkInboundDrop query rejects any column+// that could carry a message body, and this struct does too.+type dbAuditLogger struct {+ queries *db.Queries+}++// NewAuditLogger returns an AuditLogger that writes drop events to the+// lark_inbound_audit table. The interface signature does not accept a+// message body, mirroring §4.7 of the design (non-content audit only).+func NewAuditLogger(queries *db.Queries) AuditLogger {+ return &dbAuditLogger{queries: queries}+}++func (l *dbAuditLogger) RecordDrop(ctx context.Context, p AuditDropParams) error {+ return l.queries.RecordLarkInboundDrop(ctx, db.RecordLarkInboundDropParams{+ EventType: p.EventType,+ DropReason: string(p.Reason),+ InstallationID: p.InstallationID,+ LarkChatID: textIfNonEmpty(string(p.ChatID)),+ LarkEventID: textIfNonEmpty(p.LarkEventID),+ LarkMessageID: textIfNonEmpty(p.LarkMessageID),+ })+}++// textIfNonEmpty returns a Valid pgtype.Text for non-empty strings and+// a NULL pgtype.Text otherwise. Avoids storing literal empty strings+// in the audit table, which would mask the difference between "the+// event lacked this field" and "the field was deliberately empty".+func textIfNonEmpty(s string) pgtype.Text {+ if s == "" {+ return pgtype.Text{}+ }+ return pgtype.Text{String: s, Valid: true}+}diff --git a/server/internal/integrations/lark/binding_token.go b/server/internal/integrations/lark/binding_token.gonew file mode 100644index 0000000000..2f1c2d7ca1--- /dev/null+++ b/server/internal/integrations/lark/binding_token.go@@ -0,0 +1,291 @@+package lark++import (+ "context"+ "crypto/rand"+ "crypto/sha256"+ "encoding/base64"+ "encoding/hex"+ "errors"+ "fmt"+ "time"++ "github.com/jackc/pgx/v5"+ "github.com/jackc/pgx/v5/pgconn"+ "github.com/jackc/pgx/v5/pgtype"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++// BindingToken is the public shape of a freshly minted token. The raw+// token is returned to the caller exactly once — it is the unguessable+// secret embedded in the binding URL the Bot replies with. After this+// call returns, only the hash exists server-side; the raw value+// cannot be recovered from the DB.+type BindingToken struct {+ Raw string+ ExpiresAt time.Time+}++// RedeemedBindingToken is the row returned to the caller after a+// successful redemption. The redemption path uses these fields to+// write the lark_user_binding row.+type RedeemedBindingToken struct {+ WorkspaceID pgtype.UUID+ InstallationID pgtype.UUID+ LarkOpenID OpenID+}++// InstallerBinder is the narrow surface RegistrationService needs to+// record the installer's lark_user_binding row in the same business+// step as the installation insert. Without this step the first inbound+// message from the installer would be dropped as `unbound_user` and+// the Bot would reply "you're not bound, click here…" to the person+// who just authorized the install seconds ago.+//+// Implementations MUST be idempotent on (installation_id, lark_open_id):+// a re-install by the same user should not error.+//+// `qtx` is the *db.Queries handle to run the bind against. The caller+// opens the transaction so the installation insert and the binding+// write commit together; nil means "use the service's own+// (non-transactional) queries handle".+type InstallerBinder interface {+ BindInstallerTx(ctx context.Context, qtx *db.Queries, p InstallerBindParams) error+}++// InstallerBindParams carries the inputs InstallerBinder needs. Kept+// as a struct so adding union_id (Phase 2) does not break callers.+type InstallerBindParams struct {+ WorkspaceID pgtype.UUID+ InstallationID pgtype.UUID+ MulticaUserID pgtype.UUID // the installer's Multica account+ LarkOpenID OpenID // the installer's per-installation open_id+}++// BindingTokenService mints and redeems binding tokens for the+// "you're not bound yet, click here" flow. The TTL is fixed at+// BindingTokenTTL (15 min); the DB CHECK enforces the same cap so a+// misconfigured caller cannot quietly mint a longer-lived token.+//+// Redemption (RedeemAndBind) is transactional: consuming the token+// and inserting the lark_user_binding row commit together, so a+// failed bind never burns a token, and a successful bind never+// leaves a consumed-but-unused token behind.+type BindingTokenService struct {+ queries *db.Queries+ tx TxStarter+ now func() time.Time+}++// NewBindingTokenService constructs the default service. The clock+// is injectable so tests can pin time for deterministic expiry+// behavior; production callers use NewBindingTokenServiceWithClock+// with time.Now.+func NewBindingTokenService(queries *db.Queries, tx TxStarter) *BindingTokenService {+ return NewBindingTokenServiceWithClock(queries, tx, time.Now)+}++// NewBindingTokenServiceWithClock is the seam for tests; production+// callers should use NewBindingTokenService.+func NewBindingTokenServiceWithClock(queries *db.Queries, tx TxStarter, now func() time.Time) *BindingTokenService {+ return &BindingTokenService{queries: queries, tx: tx, now: now}+}++// Mint creates a new single-use binding token and returns the raw+// secret + expiry. The raw value MUST be sent over a secure channel+// to the intended recipient — Lark DMs are encrypted in transit by+// the platform — and never logged. Mint is the only function in this+// package that produces a raw token; subsequent reads are by hash.+func (s *BindingTokenService) Mint(ctx context.Context, workspaceID, installationID pgtype.UUID, openID OpenID) (BindingToken, error) {+ raw, err := randomToken(32)+ if err != nil {+ return BindingToken{}, fmt.Errorf("generate token: %w", err)+ }+ hash := hashToken(raw)+ expiresAt := s.now().Add(BindingTokenTTL)++ if _, err := s.queries.CreateLarkBindingToken(ctx, db.CreateLarkBindingTokenParams{+ TokenHash: hash,+ WorkspaceID: workspaceID,+ InstallationID: installationID,+ LarkOpenID: string(openID),+ ExpiresAt: pgtype.Timestamptz{Time: expiresAt, Valid: true},+ }); err != nil {+ return BindingToken{}, fmt.Errorf("persist token: %w", err)+ }+ return BindingToken{Raw: raw, ExpiresAt: expiresAt}, nil+}++// RedeemAndBind atomically consumes a raw token and writes the+// lark_user_binding row in a single DB transaction. The redeemer's+// identity is the supplied multicaUserID (taken from the session by+// the handler, never from the token), so a stolen token cannot bind+// a Lark open_id to an attacker's account.+//+// Failure modes are returned as typed errors:+//+// - ErrBindingTokenInvalid: token doesn't exist / already consumed /+// expired. Same opaque error for all three to avoid a timing+// oracle for replay races.+//+// - ErrBindingAlreadyAssigned: a binding already exists for this+// (installation, open_id), pointing at a DIFFERENT Multica user.+// The token is NOT consumed in this case — we roll back so the+// correct holder of the existing binding is not disrupted and+// ops can still revoke the surplus token explicitly. Account+// transfer must go through an explicit unbind, not a redemption.+//+// - ErrBindingNotWorkspaceMember: the redeemer is not a member of+// the token's workspace, which trips the composite FK to+// member(workspace_id, user_id). Rolled back identically.+//+// On the happy path the consume + bind commit together: a successful+// return guarantees both the consumed_at write and the binding row+// landed; a returned error guarantees neither did.+func (s *BindingTokenService) RedeemAndBind(ctx context.Context, raw string, multicaUserID pgtype.UUID) (RedeemedBindingToken, error) {+ if s.tx == nil {+ return RedeemedBindingToken{}, errors.New("lark: BindingTokenService missing TxStarter")+ }+ tx, err := s.tx.Begin(ctx)+ if err != nil {+ return RedeemedBindingToken{}, fmt.Errorf("begin tx: %w", err)+ }+ defer tx.Rollback(ctx)+ qtx := s.queries.WithTx(tx)++ row, err := qtx.ConsumeLarkBindingToken(ctx, hashToken(raw))+ if err != nil {+ if errors.Is(err, pgx.ErrNoRows) {+ return RedeemedBindingToken{}, ErrBindingTokenInvalid+ }+ return RedeemedBindingToken{}, fmt.Errorf("consume token: %w", err)+ }++ _, err = qtx.CreateLarkUserBinding(ctx, db.CreateLarkUserBindingParams{+ WorkspaceID: row.WorkspaceID,+ MulticaUserID: multicaUserID,+ InstallationID: row.InstallationID,+ LarkOpenID: row.LarkOpenID,+ })+ if err != nil {+ // pgx.ErrNoRows here means the conflict row exists but its+ // multica_user_id differs from ours, so the WHERE clause on+ // the ON CONFLICT DO UPDATE rejected the rebind. See the+ // comment on CreateLarkUserBinding in queries/lark.sql.+ if errors.Is(err, pgx.ErrNoRows) {+ return RedeemedBindingToken{}, ErrBindingAlreadyAssigned+ }+ // 23503 is foreign_key_violation. The relevant FK here is+ // lark_user_binding_member_fk (workspace_id, multica_user_id)+ // → member; tripping it means the redeemer is not a member+ // of the token's workspace.+ var pgErr *pgconn.PgError+ if errors.As(err, &pgErr) && pgErr.Code == "23503" {+ return RedeemedBindingToken{}, ErrBindingNotWorkspaceMember+ }+ return RedeemedBindingToken{}, fmt.Errorf("create binding: %w", err)+ }++ if err := tx.Commit(ctx); err != nil {+ return RedeemedBindingToken{}, fmt.Errorf("commit: %w", err)+ }+ return RedeemedBindingToken{+ WorkspaceID: row.WorkspaceID,+ InstallationID: row.InstallationID,+ LarkOpenID: OpenID(row.LarkOpenID),+ }, nil+}++// BindInstallerTx is the auto-binding path for the device-flow+// install: the user who just authorized the install is recorded as+// bound to their own open_id, so the first inbound message in the+// bot's DM arrives at a `bound` identity check and the user is NOT+// prompted with a redundant "click here to bind" card.+//+// `qtx` is the RegistrationService's transaction-scoped queries+// handle. The service opens a transaction that wraps the+// lark_installation insert and this binding write so a half-applied+// install (installation row without the installer binding) cannot+// land. When `qtx` is nil the service's own (non-transactional)+// queries handle is used, which is the right behavior for tests that+// don't need atomicity.+//+// Token redemption deliberately does NOT share this code path:+// - RedeemAndBind consumes a server-minted token in the same tx as+// the binding insert; that's how anti-replay works.+// - BindInstallerTx is invoked from the device-flow success hook+// where the authoritative proof of identity is the Lark-validated+// polling response (open_id returned alongside the freshly minted+// client_id / client_secret). There is no token to consume, and+// inventing one would only widen the attack surface.+//+// The underlying CreateLarkUserBinding query is idempotent on+// (installation_id, lark_open_id) when multica_user_id matches (the+// ON CONFLICT DO UPDATE gating spelled out on the SQL), so a+// re-install by the same user is a no-op metadata refresh. A+// re-install by a DIFFERENT user surfaces as ErrBindingAlreadyAssigned+// — the registration caller treats that as a hard error and the+// frontend surfaces it as "this Lark account is bound elsewhere",+// preventing one workspace admin from silently rebinding another's+// PersonalAgent install.+func (s *BindingTokenService) BindInstallerTx(ctx context.Context, qtx *db.Queries, p InstallerBindParams) error {+ q := qtx+ if q == nil {+ q = s.queries+ }+ _, err := q.CreateLarkUserBinding(ctx, db.CreateLarkUserBindingParams{+ WorkspaceID: p.WorkspaceID,+ MulticaUserID: p.MulticaUserID,+ InstallationID: p.InstallationID,+ LarkOpenID: string(p.LarkOpenID),+ })+ if err != nil {+ if errors.Is(err, pgx.ErrNoRows) {+ return ErrBindingAlreadyAssigned+ }+ var pgErr *pgconn.PgError+ if errors.As(err, &pgErr) && pgErr.Code == "23503" {+ return ErrBindingNotWorkspaceMember+ }+ return fmt.Errorf("bind installer: %w", err)+ }+ return nil+}++// ErrBindingTokenInvalid is returned by RedeemAndBind when the token+// hash does not exist, the token has already been consumed, or it+// has expired. The caller must NOT distinguish those sub-cases —+// that distinction enables timing oracles for token replay races and+// adds no product value (the user sees the same "link invalid or+// expired, please request a new one" copy either way).+var ErrBindingTokenInvalid = errors.New("binding token invalid or expired")++// ErrBindingAlreadyAssigned is returned by RedeemAndBind when a+// lark_user_binding row already exists for the (installation,+// open_id) pair and points at a different Multica user. Account+// transfer must go through an explicit unbind flow; a binding token+// cannot be used to grab an already-bound open_id from another user.+var ErrBindingAlreadyAssigned = errors.New("lark open_id is already bound to a different user")++// ErrBindingNotWorkspaceMember is returned by RedeemAndBind when the+// redeemer is not (or no longer) a member of the token's workspace,+// detected as a foreign-key violation against member(workspace_id,+// user_id). Translated to 403 at the HTTP boundary.+var ErrBindingNotWorkspaceMember = errors.New("redeemer is not a workspace member")++func randomToken(n int) (string, error) {+ buf := make([]byte, n)+ if _, err := rand.Read(buf); err != nil {+ return "", err+ }+ // URL-safe so the token embeds cleanly in the binding URL+ // without escaping. RawURLEncoding drops `=` padding which is+ // optional for decoders and would otherwise look ugly in+ // user-visible URLs.+ return base64.RawURLEncoding.EncodeToString(buf), nil+}++func hashToken(raw string) string {+ sum := sha256.Sum256([]byte(raw))+ return hex.EncodeToString(sum[:])+}diff --git a/server/internal/integrations/lark/binding_token_test.go b/server/internal/integrations/lark/binding_token_test.gonew file mode 100644index 0000000000..4b1dafd30e--- /dev/null+++ b/server/internal/integrations/lark/binding_token_test.go@@ -0,0 +1,101 @@+package lark++import (+ "context"+ "errors"+ "strings"+ "testing"++ "github.com/jackc/pgx/v5/pgtype"+)++// These tests cover the pure-Go halves of BindingTokenService — token+// generation entropy/encoding, deterministic hashing — without+// touching the database. DB-backed mint/redeem invariants (single use,+// expiry) are covered by the DB CHECK on lark_binding_token plus the+// ConsumeLarkBindingToken query, which require an integration test+// against a real Postgres and are added in a follow-up.++func TestRandomTokenIsUnique(t *testing.T) {+ seen := map[string]struct{}{}+ for i := 0; i < 256; i++ {+ tok, err := randomToken(32)+ if err != nil {+ t.Fatalf("randomToken: %v", err)+ }+ if _, dup := seen[tok]; dup {+ t.Fatalf("randomToken returned a duplicate after %d iterations: %q", i, tok)+ }+ seen[tok] = struct{}{}+ }+}++func TestRandomTokenURLSafe(t *testing.T) {+ tok, err := randomToken(32)+ if err != nil {+ t.Fatalf("randomToken: %v", err)+ }+ // RawURLEncoding alphabet: A-Z a-z 0-9 - _+ for _, r := range tok {+ ok := (r >= 'A' && r <= 'Z') || (r >= 'a' && r <= 'z') || (r >= '0' && r <= '9') || r == '-' || r == '_'+ if !ok {+ t.Fatalf("token contains non-url-safe rune %q in %q", r, tok)+ }+ }+ if strings.Contains(tok, "=") {+ t.Fatalf("RawURLEncoding should drop padding, got %q", tok)+ }+}++// TestRedeemAndBindRequiresTxStarter guards the constructor-misuse+// path: if a future refactor wires up BindingTokenService without a+// TxStarter (e.g. for a legacy code path that only needed Mint),+// RedeemAndBind must fail fast with a clear error rather than panic+// on the nil dereference at s.tx.Begin. The atomicity contract+// documented above depends on that transaction existing.+func TestRedeemAndBindRequiresTxStarter(t *testing.T) {+ svc := &BindingTokenService{}+ _, err := svc.RedeemAndBind(context.Background(), "tok", pgtype.UUID{})+ if err == nil {+ t.Fatal("expected error when TxStarter is nil, got nil")+ }+ if !strings.Contains(err.Error(), "missing TxStarter") {+ t.Fatalf("expected missing-TxStarter error, got %v", err)+ }+}++// TestBindingErrorSentinelsAreDistinct guards against accidentally+// collapsing the three rejection sentinels (e.g. someone making+// ErrBindingNotWorkspaceMember an alias of ErrBindingTokenInvalid to+// "hide" the workspace-membership signal). The HTTP handler maps+// each to a distinct status code (410/409/403); if errors.Is started+// matching the wrong sentinel, the response code would silently+// regress without any other test catching it.+func TestBindingErrorSentinelsAreDistinct(t *testing.T) {+ if errors.Is(ErrBindingAlreadyAssigned, ErrBindingTokenInvalid) ||+ errors.Is(ErrBindingTokenInvalid, ErrBindingAlreadyAssigned) {+ t.Fatal("ErrBindingAlreadyAssigned and ErrBindingTokenInvalid must not alias")+ }+ if errors.Is(ErrBindingNotWorkspaceMember, ErrBindingTokenInvalid) ||+ errors.Is(ErrBindingTokenInvalid, ErrBindingNotWorkspaceMember) {+ t.Fatal("ErrBindingNotWorkspaceMember and ErrBindingTokenInvalid must not alias")+ }+ if errors.Is(ErrBindingAlreadyAssigned, ErrBindingNotWorkspaceMember) ||+ errors.Is(ErrBindingNotWorkspaceMember, ErrBindingAlreadyAssigned) {+ t.Fatal("ErrBindingAlreadyAssigned and ErrBindingNotWorkspaceMember must not alias")+ }+}++func TestHashTokenDeterministic(t *testing.T) {+ a := hashToken("hello")+ b := hashToken("hello")+ if a != b {+ t.Fatalf("hashToken non-deterministic: %q vs %q", a, b)+ }+ if a == hashToken("hello ") {+ t.Fatalf("hashToken collided trivially with whitespace variant")+ }+ if len(a) != 64 {+ t.Fatalf("expected sha256 hex (64 chars), got %d chars", len(a))+ }+}diff --git a/server/internal/integrations/lark/chat.go b/server/internal/integrations/lark/chat.gonew file mode 100644index 0000000000..38bc01680f--- /dev/null+++ b/server/internal/integrations/lark/chat.go@@ -0,0 +1,123 @@+package lark++import (+ "context"++ "github.com/jackc/pgx/v5/pgtype"+)++// ChatSessionService is the channel-aware chat-session entry point for+// Lark. It exists deliberately apart from the HTTP `SendChatMessage`+// handler because that handler's single-creator semantics+// (chat_session.creator_id == request user_id) make sense for the+// browser/desktop client — one human, one session — but break for+// group chat_sessions where many Lark users converse with one Bot.+//+// Concrete implementation lands in a follow-up PR (MUL-2671). The+// interface is declared here so the migration + service boundary PR+// can establish the architectural cut without dragging in OAuth, WS,+// and card-patching code.+//+// Inbound contract (enforced by the implementation):+//+// - EnsureChatSession is the ONLY way Lark code creates / looks up a+// chat_session. Identity check MUST run before this call — the+// service treats every successful return as "the sender is a+// verified, workspace-bound user".+//+// - AppendUserMessage trusts that the caller has gated the message+// through identity + group-mention filters. Unbound users and+// non-addressed group messages do NOT come through here; they go+// to AuditDrop instead.+type ChatSessionService interface {+ // EnsureChatSession returns the chat_session bound to the given+ // (installation, lark_chat_id) pair, creating it on first contact.+ // `sender` must already be a verified lark_user_binding row — see+ // the contract note above. The returned UUID is the+ // chat_session.id; callers persist no other state.+ EnsureChatSession(ctx context.Context, p EnsureChatSessionParams) (pgtype.UUID, error)++ // AppendUserMessage appends the message to chat_session, dedups+ // via lark_inbound_message_dedup, and (when the message starts+ // with `/issue`) returns the parsed command so the caller can+ // dispatch through service.IssueService.Create.+ AppendUserMessage(ctx context.Context, p AppendUserMessageParams) (AppendResult, error)+}++// EnsureChatSessionParams carries the inputs for ChatSessionService.EnsureChatSession.+// Note `Sender` is the resolved Multica user UUID — the caller has+// already mapped lark_open_id → user via lark_user_binding.+type EnsureChatSessionParams struct {+ WorkspaceID pgtype.UUID+ InstallationID pgtype.UUID+ AgentID pgtype.UUID+ ChatID ChatID+ ChatType ChatType+ Sender pgtype.UUID+}++// AppendUserMessageParams carries the inputs for ChatSessionService.AppendUserMessage.+// Body is the (already-decoded) user-facing text. LarkMessageID is the+// Lark-side message id used for idempotency dedup.+//+// ClaimToken is the owner-fencing token returned by the dispatcher's+// ClaimLarkInboundDedup call. When ClaimToken.Valid is true,+// AppendUserMessage runs MarkLarkInboundDedupProcessed INSIDE its own+// chat_message+session transaction, gated on this token. A mismatched+// token (another worker re-claimed the row while we were running)+// returns ErrClaimLost and rolls back the entire transaction, so no+// second chat_message can land for the same Lark message_id. Pass an+// invalid (zero) UUID to skip the in-tx Mark — useful for tests and+// for callers that have already finalized dedup outside the+// transaction.+type AppendUserMessageParams struct {+ ChatSessionID pgtype.UUID+ Sender pgtype.UUID+ Body string+ InstallationID pgtype.UUID+ LarkMessageID string+ ClaimToken pgtype.UUID+}++// AppendResult reports what AppendUserMessage decided.+//+// Dedup is enforced by the Dispatcher's top-level dedup gate before+// AppendUserMessage runs, so a returned AppendResult always+// represents a freshly-stored message. Callers may safely act on+// IssueCommand without re-checking idempotency.+type AppendResult struct {+ // IssueCommand is non-nil when the first non-empty line begins+ // with `/issue`. The caller passes this to+ // service.IssueService.Create.+ IssueCommand *IssueCommand+ // DedupMarked is true when AppendUserMessage finalized the dedup+ // claim in its own transaction (i.e. ClaimToken was supplied and+ // the Mark succeeded). The dispatcher uses this to skip the+ // post-pipeline finalize, since the row is already in its+ // terminal state.+ DedupMarked bool+}++// IssueCommand is the parsed shape of a user-typed `/issue ...`+// command. Title is required; Description is the joined remainder of+// the message body (empty when only a title was given).+type IssueCommand struct {+ Title string+ Description string+}++// AuditLogger records dropped inbound events to lark_inbound_audit.+// The interface deliberately does not accept a message body — see the+// drop-audit policy in MUL-2671 §4.7.+type AuditLogger interface {+ RecordDrop(ctx context.Context, p AuditDropParams) error+}++type AuditDropParams struct {+ InstallationID pgtype.UUID // may be invalid for installation-less events+ ChatID ChatID+ EventType string+ LarkEventID string+ LarkMessageID string+ Reason DropReason+}diff --git a/server/internal/integrations/lark/chat_service.go b/server/internal/integrations/lark/chat_service.gonew file mode 100644index 0000000000..0fec349ec0--- /dev/null+++ b/server/internal/integrations/lark/chat_service.go@@ -0,0 +1,295 @@+package lark++import (+ "context"+ "errors"+ "fmt"+ "strings"++ "github.com/jackc/pgx/v5"+ "github.com/jackc/pgx/v5/pgconn"+ "github.com/jackc/pgx/v5/pgtype"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++// pgSQLStateUniqueViolation is the Postgres SQLSTATE for unique+// constraint violations. Spelled out as a literal rather than imported+// from pgerrcode to avoid pulling in another dependency for a single+// constant. See https://www.postgresql.org/docs/current/errcodes-appendix.html+const pgSQLStateUniqueViolation = "23505"++// ErrClaimLost signals that AppendUserMessage's in-tx dedup Mark+// matched zero rows — another worker re-claimed the lark_inbound_-+// message_dedup row while we were running (stale-reclaim race). The+// transaction is rolled back, no chat_message lands, and the+// Dispatcher treats this as a duplicate drop: the other worker is the+// sole writer for this Lark message_id.+var ErrClaimLost = errors.New("lark dedup claim lost to a concurrent reclaim")++// isUniqueViolation reports whether err is a Postgres unique-violation+// (SQLSTATE 23505). The lark_chat_session_binding+// UNIQUE (installation_id, lark_chat_id) constraint surfaces this+// code when two concurrent first messages on the same Lark chat race+// to create the binding row.+func isUniqueViolation(err error) bool {+ var pg *pgconn.PgError+ if errors.As(err, &pg) {+ return pg.Code == pgSQLStateUniqueViolation+ }+ return false+}++// TxStarter abstracts transaction creation. Re-declared in this+// package (rather than depending on internal/service) so the+// integrations layer does not back-reference into service — a circular+// dependency we want to avoid as both packages grow. Satisfied by+// *pgxpool.Pool.+type TxStarter interface {+ Begin(ctx context.Context) (pgx.Tx, error)+}++// chatSessionService is the concrete ChatSessionService. It enforces+// the architectural rules from doc.go:+//+// - EnsureChatSession only creates / looks up rows; identity must+// already be resolved by the caller (the sender argument is a+// trusted Multica user UUID).+//+// - AppendUserMessage runs message-write + session-touch in a single+// transaction so a session that has received a message has its+// `updated_at` advanced atomically. Per-Lark-message-id idempotency+// is enforced by the Dispatcher's two-phase dedup gate+// (ClaimLarkInboundDedup + Mark/Release) BEFORE AppendUserMessage+// runs — see Dispatcher.Handle. AppendUserMessage trusts the+// dispatcher's claim and does not re-check dedup itself; this is+// what lets the dispatcher safely Release the claim on infra+// failure (rolled-back tx → no chat_message → next replay+// re-processes).+type chatSessionService struct {+ queries *db.Queries+ txStarter TxStarter+}++// NewChatSessionService constructs a ChatSessionService backed by the+// supplied queries and tx starter. The tx starter is required;+// without it, AppendUserMessage cannot run dedup + insert atomically.+func NewChatSessionService(queries *db.Queries, tx TxStarter) ChatSessionService {+ return &chatSessionService{queries: queries, txStarter: tx}+}++// EnsureChatSession returns the chat_session.id bound to the given+// Lark chat. The implementation is the two-phase find-or-create+// expected by the interface contract:+//+// 1. Look up the existing lark_chat_session_binding.+// 2. If found, return its chat_session_id.+// 3. Otherwise, in one transaction: create chat_session ++// lark_chat_session_binding. Commit.+//+// The race between two concurrent first messages on the same Lark+// chat is resolved by the UNIQUE (installation_id, lark_chat_id)+// constraint on lark_chat_session_binding: the loser of the race+// catches the unique violation, re-reads the existing row, and+// returns its chat_session_id.+func (s *chatSessionService) EnsureChatSession(ctx context.Context, p EnsureChatSessionParams) (pgtype.UUID, error) {+ // Fast path: existing binding.+ existing, err := s.queries.GetLarkChatSessionBinding(ctx, db.GetLarkChatSessionBindingParams{+ InstallationID: p.InstallationID,+ LarkChatID: string(p.ChatID),+ })+ if err == nil {+ return existing.ChatSessionID, nil+ }+ if !errors.Is(err, pgx.ErrNoRows) {+ return pgtype.UUID{}, fmt.Errorf("lookup chat session binding: %w", err)+ }++ // Create path: chat_session + binding atomically.+ id, err := s.createSessionAndBinding(ctx, p)+ if err == nil {+ return id, nil+ }++ // Lost the race: another goroutine created the binding between our+ // lookup and our insert. Re-read and return the winner's session.+ if isUniqueViolation(err) {+ existing, lookupErr := s.queries.GetLarkChatSessionBinding(ctx, db.GetLarkChatSessionBindingParams{+ InstallationID: p.InstallationID,+ LarkChatID: string(p.ChatID),+ })+ if lookupErr == nil {+ return existing.ChatSessionID, nil+ }+ return pgtype.UUID{}, fmt.Errorf("race re-read after unique violation: %w", lookupErr)+ }+ return pgtype.UUID{}, err+}++func (s *chatSessionService) createSessionAndBinding(ctx context.Context, p EnsureChatSessionParams) (pgtype.UUID, error) {+ tx, err := s.txStarter.Begin(ctx)+ if err != nil {+ return pgtype.UUID{}, fmt.Errorf("begin tx: %w", err)+ }+ defer tx.Rollback(ctx)+ qtx := s.queries.WithTx(tx)++ session, err := qtx.CreateChatSession(ctx, db.CreateChatSessionParams{+ WorkspaceID: p.WorkspaceID,+ AgentID: p.AgentID,+ CreatorID: p.Sender,+ Title: defaultSessionTitle(p.ChatType),+ })+ if err != nil {+ return pgtype.UUID{}, fmt.Errorf("create chat session: %w", err)+ }++ if _, err := qtx.CreateLarkChatSessionBinding(ctx, db.CreateLarkChatSessionBindingParams{+ ChatSessionID: session.ID,+ InstallationID: p.InstallationID,+ LarkChatID: string(p.ChatID),+ LarkChatType: string(p.ChatType),+ }); err != nil {+ return pgtype.UUID{}, err+ }++ if err := tx.Commit(ctx); err != nil {+ return pgtype.UUID{}, fmt.Errorf("commit: %w", err)+ }+ return session.ID, nil+}++// AppendUserMessage writes the user message into chat_session and+// (when the body parses as `/issue …`) returns the parsed command so+// the caller can dispatch through IssueService.+//+// Idempotency is enforced as a two-step contract with the Dispatcher's+// ClaimLarkInboundDedup gate:+//+// 1. BEFORE this method is called, the Dispatcher claims an in-flight+// row in lark_inbound_message_dedup and gets back a `claim_token`.+// A replay whose previous attempt reached a durable outcome —+// processed_at IS NOT NULL — is dropped at that gate and never+// reaches AppendUserMessage at all.+//+// 2. INSIDE this method's chat_message+session transaction, when+// ClaimToken is supplied, we run MarkLarkInboundDedupProcessed+// gated on (message_id, claim_token, processed_at IS NULL). If+// another worker re-claimed the dedup row in the meantime — e.g.+// because we ran slowly past the 60-second staleness TTL — the+// row's claim_token has rotated, our UPDATE matches zero rows,+// and we return ErrClaimLost. The deferred Rollback then unwinds+// the chat_message + session writes, so no second chat_message+// lands for the same Lark message_id.+//+// Together these close the two windows that staleness-TTL alone left+// open (stale-reclaim race + Mark-window crash): the durable write+// and the dedup Mark commit (or roll back) atomically.+//+// Callers that pass an invalid (zero) ClaimToken get the legacy+// behavior — just write the message — and are responsible for+// finalizing the dedup row themselves. The dispatcher always passes+// the live token; tests use the zero value when they want to exercise+// the write path without modelling dedup.+func (s *chatSessionService) AppendUserMessage(ctx context.Context, p AppendUserMessageParams) (AppendResult, error) {+ tx, err := s.txStarter.Begin(ctx)+ if err != nil {+ return AppendResult{}, fmt.Errorf("begin tx: %w", err)+ }+ defer tx.Rollback(ctx)+ qtx := s.queries.WithTx(tx)++ // Parse the command BEFORE the insert, so the "/issue alone → use+ // previous user message" fallback queries from the message set+ // that does NOT yet include the message currently being appended.+ // Otherwise the previous-message lookup would self-reference.+ cmd, _ := parseIssueCommand(p.Body)+ if cmd != nil && cmd.Title == "" {+ prev, err := qtx.GetMostRecentUserChatMessage(ctx, p.ChatSessionID)+ if err == nil {+ cmd.Title = titleFromPreviousMessage(prev.Content)+ } else if !errors.Is(err, pgx.ErrNoRows) {+ return AppendResult{}, fmt.Errorf("previous message lookup: %w", err)+ }+ }++ if _, err := qtx.CreateChatMessage(ctx, db.CreateChatMessageParams{+ ChatSessionID: p.ChatSessionID,+ Role: "user",+ Content: p.Body,+ }); err != nil {+ return AppendResult{}, fmt.Errorf("create chat message: %w", err)+ }++ if err := qtx.TouchChatSession(ctx, p.ChatSessionID); err != nil {+ return AppendResult{}, fmt.Errorf("touch chat session: %w", err)+ }++ // In-tx dedup Mark, gated on the supplied claim token. The whole+ // point of doing this here — rather than after Commit — is that+ // the chat_message write and the Mark either commit atomically or+ // roll back atomically. A stale-reclaim by another worker rotated+ // claim_token, so our UPDATE matches zero rows; deferring to the+ // post-method Mark path would leave the chat_message in place+ // while another worker also wrote one.+ markedInTx := false+ if p.ClaimToken.Valid && p.LarkMessageID != "" {+ rows, err := qtx.MarkLarkInboundDedupProcessed(ctx, db.MarkLarkInboundDedupProcessedParams{+ InstallationID: p.InstallationID,+ MessageID: p.LarkMessageID,+ ClaimToken: p.ClaimToken,+ })+ if err != nil {+ return AppendResult{}, fmt.Errorf("mark dedup processed: %w", err)+ }+ if rows == 0 {+ // Another worker holds (or already finalized) this+ // claim. Roll back via the deferred Rollback — the+ // chat_message insert never commits.+ return AppendResult{}, ErrClaimLost+ }+ markedInTx = true+ }++ if err := tx.Commit(ctx); err != nil {+ return AppendResult{}, fmt.Errorf("commit: %w", err)+ }++ return AppendResult{IssueCommand: cmd, DedupMarked: markedInTx}, nil+}++// titleFromPreviousMessage extracts a sensible title from a prior+// chat message. The spec says the previous "user message" is the+// fallback; in practice the previous message itself might also be an+// `/issue ...` invocation (the user typed two commands in a row), in+// which case stripping the prefix yields the real intent.+func titleFromPreviousMessage(body string) string {+ if cmd, ok := parseIssueCommand(body); ok {+ return cmd.Title+ }+ // First non-empty line, trimmed. Multi-line free text "becomes"+ // the title via its first line; description fallback for the+ // previous-message path is out of scope (the user's intent was a+ // title alone).+ for _, line := range strings.Split(body, "\n") {+ t := strings.TrimSpace(line)+ if t != "" {+ return t+ }+ }+ return ""+}++// defaultSessionTitle gives a freshly created chat_session a+// reasonable display title. We do not derive from message content —+// the first message hasn't been appended yet — so we use a stable+// per-chat-type label that the front-end can localize later.+func defaultSessionTitle(t ChatType) string {+ switch t {+ case ChatTypeGroup:+ return "Lark group chat"+ case ChatTypeP2P:+ return "Lark direct message"+ default:+ return "Lark chat"+ }+}diff --git a/server/internal/integrations/lark/client.go b/server/internal/integrations/lark/client.gonew file mode 100644index 0000000000..d7aadc4075--- /dev/null+++ b/server/internal/integrations/lark/client.go@@ -0,0 +1,229 @@+package lark++import (+ "context"+ "errors"+ "log/slog"+)++// APIClient is the narrow surface this package needs from the Lark Open+// Platform HTTP API. It is intentionally defined here (rather than+// taken from a vendor SDK) so the rest of the package can be built and+// unit-tested without dragging Lark's transport into every test, and+// so we can swap implementations (real SDK, stub, fake) without+// touching call sites.+//+// All methods are scoped to a single installation — the caller has+// already authenticated the installation row and decrypted its+// app_secret. The client never reads `lark_installation` itself.+type APIClient interface {+ // IsConfigured reports whether this APIClient can reach Lark over+ // the network. It is the "HTTP outbound is wired" signal: the stub+ // returns false; the real Lark HTTP client returns true once+ // instantiated. Handlers consult this when deciding whether to+ // surface install / management UI that needs to talk to Lark.+ IsConfigured() bool++ // SendInteractiveCard posts an interactive card into a Lark chat+ // and returns Lark's message_id for the card. The patcher persists+ // this id in lark_outbound_card_message so subsequent patches can+ // target the same card.+ SendInteractiveCard(ctx context.Context, p SendCardParams) (string, error)++ // PatchInteractiveCard replaces the body of a previously-sent card.+ // The throttling decision belongs to the caller; this method just+ // performs the network call.+ PatchInteractiveCard(ctx context.Context, p PatchCardParams) error++ // SendTextMessage posts a plain text message into a Lark chat.+ // Used for the agent's chat reply when the body has no markdown+ // syntax — short prose / acknowledgments / pings. A plain text+ // bubble feels like a normal IM message; we deliberately keep+ // this path even after adding the markdown card variant because+ // wrapping a one-liner "Hello!" inside a card just adds visual+ // chrome the user doesn't want.+ SendTextMessage(ctx context.Context, p SendTextParams) (string, error)++ // SendMarkdownCard posts the agent's reply as a Lark interactive+ // card (schema 2.0) with a single `tag: "markdown"` body element.+ // This is the path the chat-reply router takes when the body+ // contains markdown syntax (fenced code blocks, headings, lists,+ // tables, etc.) — Lark renders the markdown into formatted text+ // rather than leaving raw `**bold**` / `# heading` characters in+ // the user's transcript. Returns the card's message_id.+ SendMarkdownCard(ctx context.Context, p SendMarkdownCardParams) (string, error)++ // SendBindingPromptCard is the dedicated "you need to bind"+ // outbound. Kept separate from SendInteractiveCard so the+ // abstraction stays stable when the production card template+ // changes — call sites in identity check don't have to know about+ // Lark's card schema.+ SendBindingPromptCard(ctx context.Context, p BindingPromptParams) error++ // GetBotInfo returns the Bot's per-installation `open_id` (the+ // `bot_open_id` we persist on lark_installation). RegistrationService+ // is the only caller — after the device-flow registration returns+ // fresh `client_id` / `client_secret`, the service mints a+ // tenant_access_token with those creds and calls+ // /open-apis/bot/v3/info to learn the Bot's identity. The result+ // is then frozen into lark_installation alongside the app_id /+ // app_secret in the same transaction as the installer-bind.+ GetBotInfo(ctx context.Context, creds InstallationCredentials) (BotInfo, error)+}++// BotInfo is the slice of /open-apis/bot/v3/info (+ a follow-up+// /open-apis/contact/v3/users lookup for the union_id) we care about:+// the Bot's per-installation `open_id` and its stable `union_id`.+//+// Both identifiers are persisted on lark_installation:+//+// - `open_id` is the per-app Lark identifier; it is what /bot/v3/info+// returns and what the OUTBOUND send paths use to address a user.+//+// - `union_id` is the cross-app stable identifier scoped to the Lark+// tenant. It is the only field that is consistent across the two+// WS perspectives in a multi-bot group chat — see MUL-2671 group-+// @-mention triage. The decoder matches inbound `mentions[].id`+// against `union_id` so the right bot's supervisor handles the+// event when several bots are bound to the same group.+//+// Everything else /bot/v3/info returns (display name, avatar,+// activate_status, ip_white_list) is intentionally dropped — those+// can be re-fetched downstream from the bot_open_id if a UI needs+// them, and freezing them in our schema would create a drift surface+// every time the operator edits the Bot on Lark's side.+type BotInfo struct {+ OpenID OpenID+ UnionID string+}++// SendCardParams is the input shape for posting a fresh card.+type SendCardParams struct {+ InstallationID InstallationCredentials+ ChatID ChatID+ // CardJSON is the raw Lark interactive card JSON body. We pass it+ // through opaque so the card-template package can evolve without+ // dragging this transport interface along.+ CardJSON string+}++// PatchCardParams is the input shape for updating an existing card.+type PatchCardParams struct {+ InstallationID InstallationCredentials+ LarkCardMessageID string+ CardJSON string+}++// SendTextParams is the input shape for posting a plain text message.+// Text is sent verbatim to Lark; the client handles JSON encoding of+// the `{"text": "..."}` content envelope Lark requires.+type SendTextParams struct {+ InstallationID InstallationCredentials+ ChatID ChatID+ Text string+}++// SendMarkdownCardParams is the input shape for posting an agent+// reply as a Lark interactive card with a markdown body element.+// Markdown is forwarded to Lark verbatim; the client builds the+// schema-2.0 card envelope around it.+type SendMarkdownCardParams struct {+ InstallationID InstallationCredentials+ ChatID ChatID+ // Markdown is the body. Lark schema-2.0 markdown supports GFM-ish:+ // **bold**, *italic*, `inline code`, fenced code blocks, headings,+ // ordered + unordered lists, links, tables, blockquotes, separators.+ Markdown string+ // Summary, when non-empty, is rendered as the single-line preview+ // Lark shows in the chat list / desktop notification. Empty falls+ // back to whatever Lark derives from the body.+ Summary string+}++// BindingPromptParams carries the data needed to render and send the+// member-binding prompt card (single CTA: open the binding URL).+type BindingPromptParams struct {+ InstallationID InstallationCredentials+ OpenID OpenID+ // BindURL is the absolute URL the user clicks. The token is+ // embedded in the URL by the caller; the client never sees it.+ BindURL string+}++// InstallationCredentials is the per-installation transport context the+// client needs to authenticate against Lark on behalf of a workspace's+// bot. Passing these explicitly to each call (rather than constructing+// per-installation clients) keeps lifecycle simple: the hub decrypts+// app_secret once and reuses the struct for every outbound call.+//+// The plaintext app_secret lives inside this struct exactly while a+// call is in flight; callers MUST NOT log or persist it.+type InstallationCredentials struct {+ AppID string+ AppSecret string+ TenantKey string+}++// ErrAPIClientNotConfigured is returned by the stub client to signal+// that a real Lark client has not been wired in yet. Call sites SHOULD+// treat this as an expected condition on self-host deployments without+// a Lark app — log a warning, fall back to "Lark integration not+// configured", and continue serving other workspace functionality.+var ErrAPIClientNotConfigured = errors.New("lark: API client not configured")++// stubAPIClient is the default APIClient used when no production client+// has been registered. It refuses every transport call with+// ErrAPIClientNotConfigured so a misconfigured deployment fails loudly+// instead of silently dropping cards or device-flow registration+// responses.+//+// We deliberately do NOT silently succeed: a stub that returned ""+// message IDs would let the inbound dispatcher record bogus+// lark_outbound_card_message rows pointing at nothing.+type stubAPIClient struct {+ log *slog.Logger+}++// NewStubAPIClient returns the default no-op APIClient. The hub+// constructs one of these when no real implementation has been+// supplied, so subsystems that depend on APIClient (outbound patcher,+// device-flow registration) can still wire up; their first call+// surfaces a clear error.+func NewStubAPIClient(log *slog.Logger) APIClient {+ if log == nil {+ log = slog.Default()+ }+ return &stubAPIClient{log: log}+}++func (s *stubAPIClient) IsConfigured() bool { return false }++func (s *stubAPIClient) SendInteractiveCard(ctx context.Context, p SendCardParams) (string, error) {+ s.log.Warn("lark stub client: SendInteractiveCard called", "chat_id", string(p.ChatID))+ return "", ErrAPIClientNotConfigured+}++func (s *stubAPIClient) PatchInteractiveCard(ctx context.Context, p PatchCardParams) error {+ s.log.Warn("lark stub client: PatchInteractiveCard called", "card_message_id", p.LarkCardMessageID)+ return ErrAPIClientNotConfigured+}++func (s *stubAPIClient) SendTextMessage(ctx context.Context, p SendTextParams) (string, error) {+ s.log.Warn("lark stub client: SendTextMessage called", "chat_id", string(p.ChatID))+ return "", ErrAPIClientNotConfigured+}++func (s *stubAPIClient) SendMarkdownCard(ctx context.Context, p SendMarkdownCardParams) (string, error) {+ s.log.Warn("lark stub client: SendMarkdownCard called", "chat_id", string(p.ChatID))+ return "", ErrAPIClientNotConfigured+}++func (s *stubAPIClient) SendBindingPromptCard(ctx context.Context, p BindingPromptParams) error {+ s.log.Warn("lark stub client: SendBindingPromptCard called", "open_id", string(p.OpenID))+ return ErrAPIClientNotConfigured+}++func (s *stubAPIClient) GetBotInfo(ctx context.Context, creds InstallationCredentials) (BotInfo, error) {+ s.log.Warn("lark stub client: GetBotInfo called", "app_id", creds.AppID)+ return BotInfo{}, ErrAPIClientNotConfigured+}diff --git a/server/internal/integrations/lark/dispatcher.go b/server/internal/integrations/lark/dispatcher.gonew file mode 100644index 0000000000..5088270bb4--- /dev/null+++ b/server/internal/integrations/lark/dispatcher.go@@ -0,0 +1,563 @@+package lark++import (+ "context"+ "errors"+ "fmt"++ "github.com/jackc/pgx/v5"+ "github.com/jackc/pgx/v5/pgtype"+ "github.com/multica-ai/multica/server/internal/service"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++// InboundMessage is the normalized shape the WebSocket adapter hands+// to the Dispatcher. The adapter (Phase 2 PR) translates the raw Lark+// event payload into this struct; the Dispatcher does NOT know what a+// Lark event JSON object looks like. This keeps event-schema changes+// from rippling into business logic.+//+// AddressedToBot is the adapter's verdict on whether a group-chat+// message is an interaction with the Bot (@-mention or reply to a+// Bot card). For p2p messages this field is ignored.+type InboundMessage struct {+ EventType string+ EventID string+ AppID string+ ChatID ChatID+ ChatType ChatType+ MessageID string+ SenderOpenID OpenID+ Body string+ AddressedToBot bool+}++// Outcome categorizes what the Dispatcher decided to do with an+// inbound message. The WS adapter inspects this and chooses what to+// reply with on the Lark side.+type Outcome string++const (+ // OutcomeDropped — the message was not ingested (identity failed,+ // dedup hit, group filter, etc.). DispatchResult.DropReason holds+ // the audit category.+ OutcomeDropped Outcome = "dropped"++ // OutcomeNeedsBinding — the open_id is unbound; the WS adapter+ // should mint a binding token via BindingTokenService and send+ // the "click here to bind" card. DispatchResult.SenderOpenID and+ // .InstallationID are populated so the adapter can target the+ // reply.+ OutcomeNeedsBinding Outcome = "needs_binding"++ // OutcomeIngested — the message landed in chat_session and an+ // agent task was enqueued. Empty IssueCommand means a plain chat+ // message; non-empty means /issue ran (see IssueID for the new+ // issue's UUID).+ OutcomeIngested Outcome = "ingested"++ // OutcomeAgentOffline — the message landed in chat_session, but+ // the agent has no runtime bound at all (agent.runtime_id IS+ // NULL). The adapter should reply with "agent offline, will run+ // on next online." The chat_message row remains so the agent+ // picks it up on resume.+ //+ // IMPORTANT: this is NOT triggered when a daemon is merely+ // disconnected. If agent.runtime_id IS set, the chat task is+ // enqueued and waits for the daemon to claim it on next online;+ // that path returns OutcomeIngested with a TaskID.+ OutcomeAgentOffline Outcome = "agent_offline"++ // OutcomeAgentArchived — the message landed in chat_session, but+ // the agent has been archived. The adapter should reply with a+ // distinct copy ("this agent has been archived; ask an admin to+ // unarchive or rebind"). Kept separate from OutcomeAgentOffline+ // because the user-facing remediation differs.+ OutcomeAgentArchived Outcome = "agent_archived"+)++// DispatchResult is the typed return from Dispatcher.Handle. Callers+// (the WS adapter) consume this to drive their outbound side; nothing+// here implies the adapter MUST reply, only that it CAN.+type DispatchResult struct {+ Outcome Outcome+ DropReason DropReason+ InstallationID pgtype.UUID+ ChatSessionID pgtype.UUID+ SenderOpenID OpenID+ TaskID pgtype.UUID+ IssueID pgtype.UUID+ IssueNumber int32+ // IssueIdentifier is the workspace-qualified human key for the+ // created issue ("MUL-42"). Populated only when /issue produced a+ // new row. The OutcomeReplier uses this verbatim in the "Created+ // [MUL-42]" confirmation message.+ IssueIdentifier string+ // IssueTitle is the title the user supplied on /issue, echoed back+ // in the confirmation message so the chat history reads naturally+ // even when the Multica deep link is not reachable.+ IssueTitle string+}++// IssueCreator is the narrow subset of service.IssueService the+// Dispatcher needs. Declared here as an interface so this package can+// be unit-tested without bringing the full service graph along.+type IssueCreator interface {+ Create(ctx context.Context, p service.IssueCreateParams, opts service.IssueCreateOpts) (service.IssueCreateResult, error)+}++// ChatTaskEnqueuer is the narrow subset of service.TaskService the+// Dispatcher needs. It exists for the same reason as IssueCreator:+// the Dispatcher is small enough that depending on the whole+// TaskService struct is gratuitous.+type ChatTaskEnqueuer interface {+ EnqueueChatTask(ctx context.Context, session db.ChatSession) (db.AgentTaskQueue, error)+}++// DispatcherQueries is the narrow subset of *db.Queries the Dispatcher+// needs for installation routing, identity lookup, dedup, and session+// reload. *db.Queries satisfies it directly; tests substitute a fake.+//+// Dedup is two-phase with owner fencing:+//+// - ClaimLarkInboundDedup mints a fresh claim_token UUID on insert+// and on stale-reclaim re-take. The token is the dispatcher's+// ownership receipt for the row.+//+// - MarkLarkInboundDedupProcessed and ReleaseLarkInboundDedup are+// fenced on (message_id, claim_token, processed_at IS NULL). A+// stale-reclaim that rotates the token invalidates earlier+// finalizers, so a slow-but-alive worker whose claim was taken+// over cannot stomp the new holder's row. Both queries return+// rowsAffected; zero means "your token is no longer the live one"+// and the dispatcher treats it as a no-op (not an error — the+// other worker is responsible for the row now).+//+// - AppendUserMessage invokes the Mark INSIDE its chat_message tx+// when a claim token is supplied, so the durable write and the+// Mark commit atomically. That closes the "crashed between+// commit and Mark" window. See lark_inbound_message_dedup comment+// in 109_lark_integration.up.sql for the full invariant set.+type DispatcherQueries interface {+ GetLarkInstallationByAppID(ctx context.Context, appID string) (db.LarkInstallation, error)+ GetLarkUserBindingByOpenID(ctx context.Context, arg db.GetLarkUserBindingByOpenIDParams) (db.LarkUserBinding, error)+ GetChatSession(ctx context.Context, id pgtype.UUID) (db.ChatSession, error)+ ClaimLarkInboundDedup(ctx context.Context, arg db.ClaimLarkInboundDedupParams) (db.LarkInboundMessageDedup, error)+ MarkLarkInboundDedupProcessed(ctx context.Context, arg db.MarkLarkInboundDedupProcessedParams) (int64, error)+ ReleaseLarkInboundDedup(ctx context.Context, arg db.ReleaseLarkInboundDedupParams) (int64, error)+ // GetWorkspace is needed to read IssuePrefix so the /issue+ // confirmation message can render the workspace-qualified key+ // ("MUL-42"). A lookup failure is non-fatal — we degrade to+ // emitting just the issue number — so callers handle the error+ // inline rather than aborting the whole dispatch.+ GetWorkspace(ctx context.Context, id pgtype.UUID) (db.Workspace, error)+}++// Dispatcher is the single per-message entry point on the inbound+// path. It owns the order in which identity check, group filter,+// dedup, ingest, /issue, and task enqueue happen — the WS adapter+// MUST NOT bypass it. That ordering is the invariant that keeps the+// design's §4.3 safety property ("unbound users never reach+// chat_session") true at runtime.+type Dispatcher struct {+ Queries DispatcherQueries+ Chat ChatSessionService+ Audit AuditLogger+ IssueService IssueCreator+ TaskService ChatTaskEnqueuer+}++// Handle processes one inbound Lark message end-to-end. It never+// returns an error for "this message was dropped" — those are+// reported via Outcome + DropReason and a non-nil err is reserved for+// real infrastructure failures (DB down, etc.) that the WS adapter+// should retry.+//+// Dedup is two-phase. After the installation lookup, ClaimLarkInbound-+// Dedup acquires an in-flight claim on msg.MessageID. After the rest+// of the pipeline runs, the claim is finalized exactly once:+//+// - MarkLarkInboundDedupProcessed — a durable outcome was reached+// (audit drop row persisted, OR chat_message + session touched).+// Future replays of this message_id are dropped as duplicates.+//+// - ReleaseLarkInboundDedup — an infra error occurred BEFORE any+// durable side effect. The claim row is deleted so the WS+// adapter's retry can re-acquire it immediately; otherwise the+// message would be permanently swallowed as a duplicate even+// though it never actually landed in chat_session.+func (d *Dispatcher) Handle(ctx context.Context, msg InboundMessage) (DispatchResult, error) {+ // 1. Route to installation. The app_id is the only identifier+ // that ties an event to its installation row. These two drop+ // branches run BEFORE the dedup claim because they have no+ // valid installation row to attach to — see the spec note on+ // lark_inbound_audit allowing a NULL installation_id.+ inst, err := d.Queries.GetLarkInstallationByAppID(ctx, msg.AppID)+ if err != nil {+ if errors.Is(err, pgx.ErrNoRows) {+ _ = d.Audit.RecordDrop(ctx, AuditDropParams{+ EventType: msg.EventType,+ LarkEventID: msg.EventID,+ LarkMessageID: msg.MessageID,+ ChatID: msg.ChatID,+ Reason: DropReasonInvalidEvent,+ })+ return DispatchResult{Outcome: OutcomeDropped, DropReason: DropReasonInvalidEvent}, nil+ }+ return DispatchResult{}, fmt.Errorf("load installation: %w", err)+ }+ if InstallationStatus(inst.Status) != InstallationActive {+ return d.drop(ctx, msg, inst.ID, DropReasonRevokedInstallation), nil+ }++ // 2. Two-phase dedup claim with owner fencing. Spec §4.3 puts this+ // before group filter and identity check so a WebSocket+ // reconnect that replays an event cannot:+ // a) re-trigger the binding prompt for an unbound user, or+ // b) re-write the not_addressed_in_group / unbound_user audit+ // rows, or+ // c) re-touch the chat_session for a bound message.+ //+ // The Claim returns claim_token; subsequent Mark / Release calls+ // are fenced on (message_id, claim_token), and AppendUserMessage+ // invokes the Mark INSIDE its chat_message tx, so the durable+ // write + Mark commit atomically. Stale-reclaim by another+ // worker rotates the token, which invalidates our same-tx Mark+ // (zero rows → ErrClaimLost → tx rollback).+ //+ // Empty MessageID means the event has no Lark message_id at all+ // (non-message events, malformed payloads); skipping dedup is+ // the safe default — we have no key to deduplicate by, and no+ // claim to finalize at the end.+ var claimToken pgtype.UUID+ claimed := false+ if msg.MessageID != "" {+ claim, err := d.Queries.ClaimLarkInboundDedup(ctx, db.ClaimLarkInboundDedupParams{+ InstallationID: inst.ID,+ MessageID: msg.MessageID,+ })+ if err != nil {+ if errors.Is(err, pgx.ErrNoRows) {+ // Either the row is processed_at IS NOT NULL+ // (terminal) or another worker is actively+ // processing. Either way, the right behavior is to+ // drop without re-doing the work.+ return d.drop(ctx, msg, inst.ID, DropReasonDuplicate), nil+ }+ return DispatchResult{}, fmt.Errorf("dedup claim: %w", err)+ }+ claimToken = claim.ClaimToken+ claimed = true+ }++ res, finalize, err := d.processClaimed(ctx, msg, inst, claimToken)++ if claimed {+ d.applyFinalize(ctx, inst.ID, msg.MessageID, claimToken, finalize)+ }++ // ErrClaimLost is the dispatcher's signal that another worker+ // holds the claim. Surface it as a duplicate drop to the caller —+ // nothing else needs to happen, and the audit row was already+ // written by the in-tx rollback path's caller (see processClaimed).+ if errors.Is(err, ErrClaimLost) {+ return d.drop(ctx, msg, inst.ID, DropReasonDuplicate), nil+ }++ return res, err+}++// dedupFinalize captures the dispatcher's instruction to applyFinalize+// after processClaimed returns. The three states correspond to the+// three terminal positions in the inbound pipeline:+//+// - finalizeMark: a durable side effect landed OUTSIDE+// AppendUserMessage's tx (audit drop row, or a post-AppendUser-+// Message error that left the chat_message committed). Token-+// fenced Mark locks the row terminal.+//+// - finalizeRelease: the run did not reach durability. Delete the+// in-flight row so the WS adapter's retry can re-claim it+// immediately instead of waiting for the 60s staleness TTL.+//+// - finalizeNone: AppendUserMessage already finalized the row in+// its own tx (success → Mark in-tx; ErrClaimLost → another worker+// owns it). The dispatcher does not touch the row again.+type dedupFinalize int++const (+ finalizeNone dedupFinalize = iota+ finalizeMark+ finalizeRelease+)++// processClaimed runs the post-dedup pipeline. It returns the typed+// dispatch result, a dedupFinalize directive telling the caller how to+// land the claim row, and any error.+//+// Boundary contract per step:+//+// - Group filter / unbound-user drop → audit row written →+// finalizeMark.+// - EnsureChatSession error → tx rolled back, no durable side effect+// → finalizeRelease.+// - AppendUserMessage success → chat_message committed AND+// dedup row already Marked in the same tx → finalizeNone.+// - AppendUserMessage error → tx rolled back, no chat_message →+// finalizeRelease (ErrClaimLost is treated specially by Handle).+// - Post-AppendUserMessage error (issue create, session reload,+// task enqueue) → chat_message already committed but the+// in-tx Mark also already committed → finalizeNone.+func (d *Dispatcher) processClaimed(ctx context.Context, msg InboundMessage, inst db.LarkInstallation, claimToken pgtype.UUID) (DispatchResult, dedupFinalize, error) {+ // 3. Group-mention filter (group chats only). We do this BEFORE+ // identity check so that an unbound user's idle group chatter+ // never produces an "you need to bind" reply card spam — the+ // Bot is not addressed, so we say nothing.+ if msg.ChatType == ChatTypeGroup && !msg.AddressedToBot {+ return d.drop(ctx, msg, inst.ID, DropReasonNotAddressedInGroup), finalizeMark, nil+ }++ // 4. Identity check. A row in lark_user_binding means the open_id+ // maps to a current workspace member (the composite FK to+ // member cascades the binding away on membership revocation).+ binding, err := d.Queries.GetLarkUserBindingByOpenID(ctx, db.GetLarkUserBindingByOpenIDParams{+ InstallationID: inst.ID,+ LarkOpenID: string(msg.SenderOpenID),+ })+ if err != nil {+ if errors.Is(err, pgx.ErrNoRows) {+ _ = d.Audit.RecordDrop(ctx, AuditDropParams{+ InstallationID: inst.ID,+ ChatID: msg.ChatID,+ EventType: msg.EventType,+ LarkEventID: msg.EventID,+ LarkMessageID: msg.MessageID,+ Reason: DropReasonUnboundUser,+ })+ return DispatchResult{+ Outcome: OutcomeNeedsBinding,+ DropReason: DropReasonUnboundUser,+ InstallationID: inst.ID,+ SenderOpenID: msg.SenderOpenID,+ }, finalizeMark, nil+ }+ return DispatchResult{}, finalizeRelease, fmt.Errorf("load user binding: %w", err)+ }++ // 5. Resolve the chat_session. For group chats, the session+ // creator is the INSTALLER (stable workspace identity that+ // won't cascade-delete when individual group members churn);+ // for p2p, the sender is the one and only human in the chat+ // so we use them.+ sessionCreator := binding.MulticaUserID+ if msg.ChatType == ChatTypeGroup {+ sessionCreator = inst.InstallerUserID+ }+ sessionID, err := d.Chat.EnsureChatSession(ctx, EnsureChatSessionParams{+ WorkspaceID: inst.WorkspaceID,+ InstallationID: inst.ID,+ AgentID: inst.AgentID,+ ChatID: msg.ChatID,+ ChatType: msg.ChatType,+ Sender: sessionCreator,+ })+ if err != nil {+ // chat_session create + lark_chat_session_binding create are+ // in a single tx; an error here means the tx rolled back and+ // nothing landed. Safe to release the dedup claim.+ return DispatchResult{}, finalizeRelease, fmt.Errorf("ensure chat session: %w", err)+ }++ // 6. Append message + in-tx dedup Mark — the durable transition+ // point. After this returns nil the chat_message AND the dedup+ // Mark have committed atomically; any subsequent failure path+ // must return finalizeNone (the row is already terminal,+ // re-Marking is a no-op but re-Releasing would undo nothing+ // and we don't want to call DELETE on a Marked row).+ //+ // ErrClaimLost = our token was rotated by a stale-reclaim mid-+ // flight; the deferred Rollback in AppendUserMessage already+ // undid the chat_message insert, so Handle treats this as a+ // duplicate drop. finalizeNone — the other holder owns the row.+ appendRes, err := d.Chat.AppendUserMessage(ctx, AppendUserMessageParams{+ ChatSessionID: sessionID,+ Sender: binding.MulticaUserID,+ Body: msg.Body,+ InstallationID: inst.ID,+ LarkMessageID: msg.MessageID,+ ClaimToken: claimToken,+ })+ if err != nil {+ if errors.Is(err, ErrClaimLost) {+ return DispatchResult{}, finalizeNone, err+ }+ // AppendUserMessage's transaction either commits or rolls+ // back atomically; an error means rollback, so no+ // chat_message was written. Safe to release.+ return DispatchResult{}, finalizeRelease, fmt.Errorf("append user message: %w", err)+ }++ // Post-AppendUserMessage paths must NOT Release the claim, because+ // the chat_message + dedup Mark are already committed. Mark-again+ // is a no-op (the in-tx Mark already landed), so finalizeNone.+ postAppendFinalize := finalizeNone+ if !appendRes.DedupMarked {+ // Defensive: the dispatcher always passes a valid claim token,+ // but if a future caller wires AppendUserMessage with an+ // invalid token the Mark would not have run in-tx. Fall back+ // to the post-pipeline Mark so the row still terminates.+ postAppendFinalize = finalizeMark+ }++ res := DispatchResult{+ Outcome: OutcomeIngested,+ InstallationID: inst.ID,+ ChatSessionID: sessionID,+ SenderOpenID: msg.SenderOpenID,+ }++ // 7. /issue command, if present. chat_message is already durable+ // above; from here all error returns must signal finalizeNone+ // (or finalizeMark in the defensive fallback above).+ if appendRes.IssueCommand != nil {+ issueRes, err := d.createIssueFromCommand(ctx, inst, binding.MulticaUserID, sessionID, *appendRes.IssueCommand)+ if err != nil {+ return DispatchResult{}, postAppendFinalize, fmt.Errorf("create issue from command: %w", err)+ }+ res.IssueID = issueRes.Issue.ID+ res.IssueNumber = issueRes.Issue.Number+ res.IssueTitle = issueRes.Issue.Title+ // Render the workspace-qualified key ("MUL-42") so the+ // outbound confirmation reads like a Linear/Jira identifier+ // rather than a bare number. A workspace lookup failure here+ // degrades gracefully — we still surface the issue number,+ // just without the workspace prefix — so a Postgres blip on+ // the workspace row does not eat the "/issue created" signal.+ if ws, werr := d.Queries.GetWorkspace(ctx, inst.WorkspaceID); werr == nil && ws.IssuePrefix != "" {+ res.IssueIdentifier = fmt.Sprintf("%s-%d", ws.IssuePrefix, issueRes.Issue.Number)+ } else {+ res.IssueIdentifier = fmt.Sprintf("#%d", issueRes.Issue.Number)+ }+ }++ // 8. Enqueue the chat task that triggers the agent run. Only the+ // productizable rejections from EnqueueChatTask (agent+ // archived, agent has no runtime configured) are mapped to a+ // user-visible Outcome; real infra failures bubble up as+ // errors so the WS adapter can retry or page.+ //+ // Note: a daemon that's merely disconnected is NOT an error+ // here. As long as agent.runtime_id is set, the chat task is+ // enqueued and waits for the daemon to claim it on next+ // online; this path returns OutcomeIngested with a TaskID.+ session, err := d.Queries.GetChatSession(ctx, sessionID)+ if err != nil {+ return DispatchResult{}, postAppendFinalize, fmt.Errorf("reload chat session: %w", err)+ }+ task, err := d.TaskService.EnqueueChatTask(ctx, session)+ if err != nil {+ switch {+ case errors.Is(err, service.ErrChatTaskAgentNoRuntime):+ res.Outcome = OutcomeAgentOffline+ return res, postAppendFinalize, nil+ case errors.Is(err, service.ErrChatTaskAgentArchived):+ res.Outcome = OutcomeAgentArchived+ return res, postAppendFinalize, nil+ default:+ return DispatchResult{}, postAppendFinalize, fmt.Errorf("enqueue chat task: %w", err)+ }+ }+ res.TaskID = task.ID+ return res, postAppendFinalize, nil+}++// applyFinalize flips the in-flight claim row to its terminal state,+// token-fenced so a slow-but-alive worker whose claim was reclaimed+// cannot stomp the new holder's row.+//+// Best-effort by design for the I/O layer: a transport failure here+// cannot abort the outcome (the user's message is already in+// chat_session or the audit row already exists), and the worst case+// is a stuck in-flight row that the 60-second staleness fallback in+// ClaimLarkInboundDedup re-takes on retry. zero-rows-affected is the+// EXPECTED outcome whenever our token was rotated; it is not an error.+func (d *Dispatcher) applyFinalize(ctx context.Context, installationID pgtype.UUID, messageID string, claimToken pgtype.UUID, action dedupFinalize) {+ switch action {+ case finalizeMark:+ _, _ = d.Queries.MarkLarkInboundDedupProcessed(ctx, db.MarkLarkInboundDedupProcessedParams{+ InstallationID: installationID,+ MessageID: messageID,+ ClaimToken: claimToken,+ })+ case finalizeRelease:+ _, _ = d.Queries.ReleaseLarkInboundDedup(ctx, db.ReleaseLarkInboundDedupParams{+ InstallationID: installationID,+ MessageID: messageID,+ ClaimToken: claimToken,+ })+ case finalizeNone:+ // AppendUserMessage already finalized the row in-tx, or our+ // claim was lost to a concurrent reclaim. Do not touch it.+ }+}++func (d *Dispatcher) drop(ctx context.Context, msg InboundMessage, instID pgtype.UUID, reason DropReason) DispatchResult {+ _ = d.Audit.RecordDrop(ctx, AuditDropParams{+ InstallationID: instID,+ ChatID: msg.ChatID,+ EventType: msg.EventType,+ LarkEventID: msg.EventID,+ LarkMessageID: msg.MessageID,+ Reason: reason,+ })+ return DispatchResult{+ Outcome: OutcomeDropped,+ DropReason: reason,+ InstallationID: instID,+ }+}++func (d *Dispatcher) createIssueFromCommand(+ ctx context.Context,+ inst db.LarkInstallation,+ creatorUserID pgtype.UUID,+ sessionID pgtype.UUID,+ cmd IssueCommand,+) (service.IssueCreateResult, error) {+ // Empty title at this point means the /issue alone fallback found+ // no previous user message either. The product copy ("请填标题")+ // belongs in the WS adapter's reply card; we surface this to the+ // caller as ErrEmptyIssueTitle so the dispatcher can short-circuit+ // without paying the IssueService cost.+ if cmd.Title == "" {+ return service.IssueCreateResult{}, ErrEmptyIssueTitle+ }+ params := service.IssueCreateParams{+ WorkspaceID: inst.WorkspaceID,+ Title: cmd.Title,+ Description: pgtype.Text{String: cmd.Description, Valid: cmd.Description != ""},+ Status: "todo",+ Priority: "none",+ AssigneeType: pgtype.Text{String: "agent", Valid: true},+ AssigneeID: inst.AgentID,+ CreatorType: "member",+ CreatorID: creatorUserID,+ OriginType: pgtype.Text{String: originLarkChat, Valid: true},+ OriginID: sessionID,+ }+ return d.IssueService.Create(ctx, params, service.IssueCreateOpts{})+}++// originLarkChat is the issue.origin_type label written for issues+// created via the Lark `/issue` command. The analytics classifier in+// service.classifyOrigin currently maps unknown origin_type values to+// SourceManual with a warning — that is acceptable for MVP. A+// dedicated analytics source label can be added when product asks for+// it.+const originLarkChat = "lark_chat"++// ErrEmptyIssueTitle is returned by createIssueFromCommand when the+// caller invoked /issue with no title AND the previous-user-message+// fallback found nothing usable. The WS adapter translates this into+// the "please supply a title" reply card per §2.3.+var ErrEmptyIssueTitle = errors.New("issue title is empty")diff --git a/server/internal/integrations/lark/dispatcher_test.go b/server/internal/integrations/lark/dispatcher_test.gonew file mode 100644index 0000000000..f87671fb02--- /dev/null+++ b/server/internal/integrations/lark/dispatcher_test.go@@ -0,0 +1,1479 @@+package lark++import (+ "context"+ "errors"+ "testing"++ "github.com/jackc/pgx/v5"+ "github.com/jackc/pgx/v5/pgtype"+ "github.com/multica-ai/multica/server/internal/service"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++// fakeDedupRow is the test-side model of a lark_inbound_message_dedup+// row. It tracks the three pieces of state that drive the dispatcher's+// finalize logic: terminal flag (processed_at IS NOT NULL), the+// currently-live claim_token, and a counter of how many distinct+// claim_tokens have ever been minted for this message_id (used by+// tests to assert that a stale-reclaim actually rotated the token).+type fakeDedupRow struct {+ processed bool+ token pgtype.UUID+ // rotations is the number of times claim_token has been minted+ // for this row (1 = inserted, 2+ = stale-reclaimed N-1 times).+ rotations int+}++// fakeQueries is the unit-test seam for DispatcherQueries. Each field+// is the canned response the fake returns from the corresponding+// method; ErrNoRows variants pin specific failure modes.+//+// Dedup state mirrors lark_inbound_message_dedup with owner fencing:+// each row carries a current claim_token, and Mark/Release require a+// matching token to succeed (zero rows otherwise, exactly like the+// production query). Tests pre-seed terminal rows by writing+// processed=true; tests exercising the in-flight branch write+// processed=false. The default empty map means "first delivery for+// every message_id".+type fakeQueries struct {+ installationByApp db.LarkInstallation+ installationErr error+ userBinding db.LarkUserBinding+ userBindingErr error+ chatSession db.ChatSession+ chatSessionErr error+ workspace db.Workspace+ workspaceErr error+ dedup map[string]*fakeDedupRow+ dedupClaimErr error+ dedupReclaim bool // when true, in-flight rows are re-claimable (simulates staleness)+ nextTokenByte byte // monotonically incremented; ensures each minted token is distinct+ calledUserBinding int+ calledChatSession int+ calledInstallation int+ calledClaim int+ calledMark int+ calledRelease int+}++// mintToken produces a deterministic, distinct token per call so+// tests can compare them. Production uses gen_random_uuid(); the+// fake only needs uniqueness, not randomness.+func (f *fakeQueries) mintToken() pgtype.UUID {+ f.nextTokenByte+++ return validUUID(0xA0 + f.nextTokenByte)+}++func (f *fakeQueries) GetLarkInstallationByAppID(ctx context.Context, appID string) (db.LarkInstallation, error) {+ f.calledInstallation+++ return f.installationByApp, f.installationErr+}++func (f *fakeQueries) GetLarkUserBindingByOpenID(ctx context.Context, arg db.GetLarkUserBindingByOpenIDParams) (db.LarkUserBinding, error) {+ f.calledUserBinding+++ return f.userBinding, f.userBindingErr+}++func (f *fakeQueries) GetChatSession(ctx context.Context, id pgtype.UUID) (db.ChatSession, error) {+ f.calledChatSession+++ return f.chatSession, f.chatSessionErr+}++// ClaimLarkInboundDedup mirrors the production query's three outcomes:+//+// - Row not present → INSERT succeeds, mints a fresh claim_token →+// returns the row.+// - Row present, processed=false, dedupReclaim=true → staleness+// fallback re-takes the claim and ROTATES the claim_token →+// returns the row.+// - Row present otherwise → ON CONFLICT WHERE filter excludes the+// UPDATE → RETURNING returns 0 rows → pgx.ErrNoRows.+func (f *fakeQueries) ClaimLarkInboundDedup(ctx context.Context, arg db.ClaimLarkInboundDedupParams) (db.LarkInboundMessageDedup, error) {+ f.calledClaim+++ if f.dedupClaimErr != nil {+ return db.LarkInboundMessageDedup{}, f.dedupClaimErr+ }+ if f.dedup == nil {+ f.dedup = map[string]*fakeDedupRow{}+ }+ key := dedupKey(arg.InstallationID, arg.MessageID)+ row, exists := f.dedup[key]+ if !exists {+ token := f.mintToken()+ f.dedup[key] = &fakeDedupRow{token: token, rotations: 1}+ return db.LarkInboundMessageDedup{+ InstallationID: arg.InstallationID,+ MessageID: arg.MessageID,+ ClaimToken: token,+ }, nil+ }+ if !row.processed && f.dedupReclaim {+ // In-flight claim re-taken — rotate the token. This is what+ // fences the previous worker out: their saved claim_token no+ // longer matches the row's live one, so Mark/Release becomes+ // a no-op for them and (for the in-tx Mark) the chat_message+ // tx rolls back.+ row.token = f.mintToken()+ row.rotations+++ return db.LarkInboundMessageDedup{+ InstallationID: arg.InstallationID,+ MessageID: arg.MessageID,+ ClaimToken: row.token,+ }, nil+ }+ return db.LarkInboundMessageDedup{}, pgx.ErrNoRows+}++// dedupKey mirrors the production (installation_id, message_id) composite+// PK in the test map. Installations are not isolated by message_id alone:+// a Lark group with multiple bots installed delivers the SAME message_id+// to every bot's WS, and each one must be free to claim, evaluate+// AddressedToBot independently, and either ingest or drop as+// not_addressed_in_group.+func dedupKey(installationID pgtype.UUID, messageID string) string {+ var b [16]byte+ if installationID.Valid {+ b = installationID.Bytes+ }+ return string(b[:]) + "|" + messageID+}++// MarkLarkInboundDedupProcessed mirrors the production UPDATE: only+// the holder of the current claim_token can mark the row, and only+// while it is still in-flight (processed_at IS NULL). Mismatched token+// or already-terminal row returns 0 rows affected (and nil error) —+// the dispatcher relies on this for the in-tx ErrClaimLost path.+func (f *fakeQueries) MarkLarkInboundDedupProcessed(ctx context.Context, arg db.MarkLarkInboundDedupProcessedParams) (int64, error) {+ f.calledMark+++ if f.dedup == nil {+ return 0, nil+ }+ row, ok := f.dedup[dedupKey(arg.InstallationID, arg.MessageID)]+ if !ok {+ return 0, nil+ }+ if row.processed {+ return 0, nil+ }+ if row.token != arg.ClaimToken {+ return 0, nil+ }+ row.processed = true+ return 1, nil+}++// ReleaseLarkInboundDedup mirrors the production DELETE: only the+// holder of the current claim_token can release the row, and only+// while it is still in-flight.+func (f *fakeQueries) GetWorkspace(ctx context.Context, id pgtype.UUID) (db.Workspace, error) {+ return f.workspace, f.workspaceErr+}++func (f *fakeQueries) ReleaseLarkInboundDedup(ctx context.Context, arg db.ReleaseLarkInboundDedupParams) (int64, error) {+ f.calledRelease+++ if f.dedup == nil {+ return 0, nil+ }+ key := dedupKey(arg.InstallationID, arg.MessageID)+ row, ok := f.dedup[key]+ if !ok {+ return 0, nil+ }+ if row.processed {+ return 0, nil+ }+ if row.token != arg.ClaimToken {+ return 0, nil+ }+ delete(f.dedup, key)+ return 1, nil+}++// fakeChat is a stub ChatSessionService that records what the+// dispatcher asked of it and returns canned outcomes.+//+// When `queries` is non-nil and the dispatcher hands AppendUserMessage+// a valid ClaimToken, the stub mirrors the production in-tx Mark: it+// invokes fakeQueries.MarkLarkInboundDedupProcessed with the supplied+// token before returning success. This is what reproduces the+// stale-reclaim race in tests — if the token has been rotated by a+// concurrent Claim, the Mark matches zero rows and AppendUserMessage+// returns ErrClaimLost, exactly like the real chatSessionService's+// rolled-back transaction.+//+// `beforeAppend` is a hook fired at the top of AppendUserMessage, used+// by the stale-reclaim regression test to inject a concurrent reclaim+// between the dispatcher's Claim and AppendUserMessage's in-tx Mark.+type fakeChat struct {+ ensureID pgtype.UUID+ ensureErr error+ appendResult AppendResult+ appendErr error+ queries *fakeQueries // when set, runs the in-tx Mark+ beforeAppend func(AppendUserMessageParams) // race-injection hook+ calledEnsure int+ calledAppend int+ lastAppendParams AppendUserMessageParams+ lastEnsureParams EnsureChatSessionParams+}++func (f *fakeChat) EnsureChatSession(ctx context.Context, p EnsureChatSessionParams) (pgtype.UUID, error) {+ f.calledEnsure+++ f.lastEnsureParams = p+ return f.ensureID, f.ensureErr+}++func (f *fakeChat) AppendUserMessage(ctx context.Context, p AppendUserMessageParams) (AppendResult, error) {+ f.calledAppend+++ f.lastAppendParams = p+ if f.beforeAppend != nil {+ f.beforeAppend(p)+ }+ if f.appendErr != nil {+ return f.appendResult, f.appendErr+ }+ res := f.appendResult+ // Mirror chatSessionService.AppendUserMessage: when the dispatcher+ // supplies a claim token, Mark in-tx; zero rows ↔ stale-reclaim+ // rotated the token under our feet, surface ErrClaimLost.+ if f.queries != nil && p.ClaimToken.Valid && p.LarkMessageID != "" {+ rows, err := f.queries.MarkLarkInboundDedupProcessed(ctx, db.MarkLarkInboundDedupProcessedParams{+ InstallationID: p.InstallationID,+ MessageID: p.LarkMessageID,+ ClaimToken: p.ClaimToken,+ })+ if err != nil {+ return AppendResult{}, err+ }+ if rows == 0 {+ return AppendResult{}, ErrClaimLost+ }+ res.DedupMarked = true+ }+ return res, nil+}++type fakeAudit struct {+ drops []AuditDropParams+}++func (f *fakeAudit) RecordDrop(ctx context.Context, p AuditDropParams) error {+ f.drops = append(f.drops, p)+ return nil+}++type fakeIssueCreator struct {+ called int+ params service.IssueCreateParams+ result service.IssueCreateResult+ err error+}++func (f *fakeIssueCreator) Create(ctx context.Context, p service.IssueCreateParams, _ service.IssueCreateOpts) (service.IssueCreateResult, error) {+ f.called+++ f.params = p+ return f.result, f.err+}++type fakeEnqueuer struct {+ called int+ task db.AgentTaskQueue+ err error+}++func (f *fakeEnqueuer) EnqueueChatTask(ctx context.Context, _ db.ChatSession) (db.AgentTaskQueue, error) {+ f.called+++ return f.task, f.err+}++// validUUID builds a deterministic Valid pgtype.UUID from the supplied+// byte. Useful for distinguishing IDs in assertions.+func validUUID(b byte) pgtype.UUID {+ var u pgtype.UUID+ for i := range u.Bytes {+ u.Bytes[i] = b+ }+ u.Valid = true+ return u+}++func activeInstallation() db.LarkInstallation {+ return db.LarkInstallation{+ ID: validUUID(0x11),+ WorkspaceID: validUUID(0x22),+ AgentID: validUUID(0x33),+ InstallerUserID: validUUID(0x99),+ Status: string(InstallationActive),+ }+}++// seedDedupKey composes a fake-table key for the default activeInstallation+// fixture (installation_id = validUUID(0x11)). Pre-seeded dedup rows in+// dispatcher tests use this to satisfy the new (installation_id,+// message_id) composite PK.+func seedDedupKey(messageID string) string {+ return dedupKey(validUUID(0x11), messageID)+}++func boundUser() db.LarkUserBinding {+ return db.LarkUserBinding{+ ID: validUUID(0x44),+ WorkspaceID: validUUID(0x22),+ MulticaUserID: validUUID(0x55),+ InstallationID: validUUID(0x11),+ LarkOpenID: "ou_user_a",+ }+}++func TestDispatcher_UnknownAppDropped(t *testing.T) {+ queries := &fakeQueries{installationErr: pgx.ErrNoRows}+ audit := &fakeAudit{}+ d := &Dispatcher{Queries: queries, Audit: audit}++ res, err := d.Handle(context.Background(), InboundMessage{+ AppID: "missing",+ EventType: "im.message.receive_v1",+ })+ if err != nil {+ t.Fatalf("unexpected error: %v", err)+ }+ if res.Outcome != OutcomeDropped || res.DropReason != DropReasonInvalidEvent {+ t.Fatalf("unexpected outcome: %+v", res)+ }+ if len(audit.drops) != 1 || audit.drops[0].Reason != DropReasonInvalidEvent {+ t.Fatalf("expected one invalid_event audit row, got %+v", audit.drops)+ }+ if audit.drops[0].InstallationID.Valid {+ t.Fatalf("audit row should omit installation_id for unknown app: %+v", audit.drops[0])+ }+}++func TestDispatcher_RevokedInstallationDropped(t *testing.T) {+ inst := activeInstallation()+ inst.Status = string(InstallationRevoked)+ queries := &fakeQueries{installationByApp: inst}+ audit := &fakeAudit{}+ d := &Dispatcher{Queries: queries, Audit: audit}++ res, err := d.Handle(context.Background(), InboundMessage{AppID: "ok"})+ if err != nil {+ t.Fatalf("unexpected error: %v", err)+ }+ if res.DropReason != DropReasonRevokedInstallation {+ t.Fatalf("got drop reason %q", res.DropReason)+ }+ if len(audit.drops) != 1 || audit.drops[0].Reason != DropReasonRevokedInstallation {+ t.Fatalf("audit drops: %+v", audit.drops)+ }+}++func TestDispatcher_GroupWithoutMentionDropped(t *testing.T) {+ queries := &fakeQueries{installationByApp: activeInstallation()}+ audit := &fakeAudit{}+ d := &Dispatcher{Queries: queries, Audit: audit}++ res, _ := d.Handle(context.Background(), InboundMessage{+ AppID: "ok",+ ChatType: ChatTypeGroup,+ AddressedToBot: false,+ })+ if res.DropReason != DropReasonNotAddressedInGroup {+ t.Fatalf("got drop reason %q", res.DropReason)+ }+ if queries.calledUserBinding != 0 {+ t.Fatalf("identity check should be skipped before group filter, got %d calls", queries.calledUserBinding)+ }+}++func TestDispatcher_UnboundUserAsksForBinding(t *testing.T) {+ queries := &fakeQueries{+ installationByApp: activeInstallation(),+ userBindingErr: pgx.ErrNoRows,+ }+ audit := &fakeAudit{}+ d := &Dispatcher{Queries: queries, Audit: audit}++ res, _ := d.Handle(context.Background(), InboundMessage{+ AppID: "ok",+ ChatType: ChatTypeP2P,+ SenderOpenID: "ou_user_a",+ })+ if res.Outcome != OutcomeNeedsBinding {+ t.Fatalf("expected OutcomeNeedsBinding, got %q", res.Outcome)+ }+ if res.DropReason != DropReasonUnboundUser {+ t.Fatalf("expected unbound_user drop reason, got %q", res.DropReason)+ }+ if res.SenderOpenID != "ou_user_a" {+ t.Fatalf("sender propagation broken: %q", res.SenderOpenID)+ }+ if len(audit.drops) != 1 || audit.drops[0].Reason != DropReasonUnboundUser {+ t.Fatalf("expected one unbound_user audit row, got %+v", audit.drops)+ }+}++func TestDispatcher_PlainMessageEnqueuesTask(t *testing.T) {+ sessionID := validUUID(0x66)+ queries := &fakeQueries{+ installationByApp: activeInstallation(),+ userBinding: boundUser(),+ chatSession: db.ChatSession{ID: sessionID, AgentID: validUUID(0x33)},+ }+ chat := &fakeChat{+ ensureID: sessionID,+ appendResult: AppendResult{},+ }+ enq := &fakeEnqueuer{task: db.AgentTaskQueue{ID: validUUID(0x77)}}+ d := &Dispatcher{+ Queries: queries,+ Chat: chat,+ Audit: &fakeAudit{},+ TaskService: enq,+ }++ res, err := d.Handle(context.Background(), InboundMessage{+ AppID: "ok",+ ChatType: ChatTypeP2P,+ SenderOpenID: "ou_user_a",+ Body: "hi bot",+ MessageID: "msg-1",+ })+ if err != nil {+ t.Fatalf("unexpected error: %v", err)+ }+ if res.Outcome != OutcomeIngested {+ t.Fatalf("expected ingested, got %q", res.Outcome)+ }+ if !res.TaskID.Valid || res.TaskID != enq.task.ID {+ t.Fatalf("task id propagation broken: %+v", res.TaskID)+ }+ // For p2p the session creator should be the bound user, not the+ // installer — verifies the chat-type branch in Handle.+ if chat.lastEnsureParams.Sender != queries.userBinding.MulticaUserID {+ t.Fatalf("p2p session creator should be sender; got %+v", chat.lastEnsureParams.Sender)+ }+}++func TestDispatcher_GroupMessageUsesInstallerAsCreator(t *testing.T) {+ inst := activeInstallation()+ sessionID := validUUID(0x66)+ queries := &fakeQueries{+ installationByApp: inst,+ userBinding: boundUser(),+ chatSession: db.ChatSession{ID: sessionID, AgentID: inst.AgentID},+ }+ chat := &fakeChat{ensureID: sessionID, appendResult: AppendResult{}}+ d := &Dispatcher{+ Queries: queries,+ Chat: chat,+ Audit: &fakeAudit{},+ TaskService: &fakeEnqueuer{task: db.AgentTaskQueue{ID: validUUID(0x77)}},+ }++ _, _ = d.Handle(context.Background(), InboundMessage{+ AppID: "ok",+ ChatType: ChatTypeGroup,+ AddressedToBot: true,+ SenderOpenID: "ou_user_a",+ Body: "hey",+ MessageID: "msg-g",+ })+ if chat.lastEnsureParams.Sender != inst.InstallerUserID {+ t.Fatalf("group session creator should be installer; got %+v want %+v",+ chat.lastEnsureParams.Sender, inst.InstallerUserID)+ }+}++func TestDispatcher_DedupHitDoesNotEnqueue(t *testing.T) {+ // Pre-seed the dedup table so the top-level dedup gate trips on+ // the first Handle call — simulates a Lark reconnect replaying an+ // event we already processed in a previous run.+ queries := &fakeQueries{+ installationByApp: activeInstallation(),+ userBinding: boundUser(),+ dedup: map[string]*fakeDedupRow{seedDedupKey("msg-dup"): {processed: true, token: validUUID(0xAB)}},+ }+ chat := &fakeChat{+ ensureID: validUUID(0x66),+ }+ enq := &fakeEnqueuer{}+ audit := &fakeAudit{}+ d := &Dispatcher{+ Queries: queries,+ Chat: chat,+ Audit: audit,+ TaskService: enq,+ }++ res, _ := d.Handle(context.Background(), InboundMessage{+ AppID: "ok",+ ChatType: ChatTypeP2P,+ SenderOpenID: "ou_user_a",+ Body: "replay",+ MessageID: "msg-dup",+ })+ if res.Outcome != OutcomeDropped || res.DropReason != DropReasonDuplicate {+ t.Fatalf("expected duplicate drop, got %+v", res)+ }+ if enq.called != 0 {+ t.Fatalf("dedup hit must not enqueue task, called=%d", enq.called)+ }+ if chat.calledEnsure != 0 || chat.calledAppend != 0 {+ t.Fatalf("dedup hit must short-circuit before chat lookup; ensure=%d append=%d",+ chat.calledEnsure, chat.calledAppend)+ }+ if queries.calledUserBinding != 0 {+ t.Fatalf("dedup hit must short-circuit before identity check, got %d binding calls",+ queries.calledUserBinding)+ }+ if len(audit.drops) != 1 || audit.drops[0].Reason != DropReasonDuplicate {+ t.Fatalf("expected duplicate audit row, got %+v", audit.drops)+ }+}++// TestDispatcher_DedupBeforeGroupFilter pins the §4.3 ordering: a+// replayed group event that was NOT addressed to the Bot must NOT+// re-write a not_addressed_in_group audit row on every reconnect, and+// must NOT re-trigger any binding-prompt side effect. The top-level+// dedup gate is what guarantees this; before this fix the group+// filter ran first and unbounded replays produced unbounded audit+// noise + reply-card spam.+func TestDispatcher_DedupBeforeGroupFilter(t *testing.T) {+ queries := &fakeQueries{+ installationByApp: activeInstallation(),+ dedup: map[string]*fakeDedupRow{seedDedupKey("msg-replay"): {processed: true, token: validUUID(0xAB)}},+ }+ audit := &fakeAudit{}+ d := &Dispatcher{Queries: queries, Audit: audit}++ res, _ := d.Handle(context.Background(), InboundMessage{+ AppID: "ok",+ ChatType: ChatTypeGroup,+ AddressedToBot: false,+ MessageID: "msg-replay",+ })+ if res.DropReason != DropReasonDuplicate {+ t.Fatalf("dedup must beat group filter; got drop reason %q", res.DropReason)+ }+ if len(audit.drops) != 1 || audit.drops[0].Reason != DropReasonDuplicate {+ t.Fatalf("expected exactly one duplicate audit row, got %+v", audit.drops)+ }+}++// TestDispatcher_DedupIsScopedPerInstallation pins MUL-2671's multi-bot+// invariant: in a Lark group with TWO Multica bots installed, the+// same Lark message_id arrives at both WS supervisors and each one+// MUST be free to claim, evaluate AddressedToBot independently, and+// either ingest or drop. Before the (installation_id, message_id)+// composite PK landed, whichever WS claimed first would mark the+// shared row terminal and the bot that was actually @-ed would lose+// to dedup before its filter ran — every @ to the "second" bot+// silently disappeared.+func TestDispatcher_DedupIsScopedPerInstallation(t *testing.T) {+ otherInst := activeInstallation()+ otherInst.ID = validUUID(0x12) // distinct from the default 0x11+ queries := &fakeQueries{+ installationByApp: otherInst,+ // Pre-seed a terminal dedup row for installation 0x11 — that's+ // the OTHER bot's already-processed claim. The current Handle+ // runs under installation 0x12 (composite-key miss → fresh+ // claim → continues processing).+ dedup: map[string]*fakeDedupRow{+ dedupKey(validUUID(0x11), "msg-shared"): {processed: true, token: validUUID(0xAB)},+ },+ }+ audit := &fakeAudit{}+ d := &Dispatcher{Queries: queries, Audit: audit}++ res, _ := d.Handle(context.Background(), InboundMessage{+ AppID: "ok",+ ChatType: ChatTypeGroup,+ AddressedToBot: false, // simulate "not @-ed FROM this bot's perspective"+ MessageID: "msg-shared",+ })+ if res.DropReason != DropReasonNotAddressedInGroup {+ t.Fatalf("composite-key dedup miss must let group filter run, got drop reason %q", res.DropReason)+ }+ // And the new (0x12, msg-shared) row must now exist — only the+ // other installation's row was pre-seeded.+ if _, ok := queries.dedup[dedupKey(otherInst.ID, "msg-shared")]; !ok {+ t.Fatalf("expected a fresh claim row for installation 0x12; got %v", queries.dedup)+ }+}++// TestDispatcher_DedupBeforeIdentityCheck pins the same ordering for+// unbound users: a replayed event from an unbound open_id must not+// re-fire the OutcomeNeedsBinding path on every reconnect — that+// would spam the user with binding-prompt cards.+func TestDispatcher_DedupBeforeIdentityCheck(t *testing.T) {+ queries := &fakeQueries{+ installationByApp: activeInstallation(),+ userBindingErr: pgx.ErrNoRows, // unbound — would normally trigger OutcomeNeedsBinding+ dedup: map[string]*fakeDedupRow{seedDedupKey("msg-replay"): {processed: true, token: validUUID(0xAB)}},+ }+ audit := &fakeAudit{}+ d := &Dispatcher{Queries: queries, Audit: audit}++ res, _ := d.Handle(context.Background(), InboundMessage{+ AppID: "ok",+ ChatType: ChatTypeP2P,+ SenderOpenID: "ou_user_a",+ MessageID: "msg-replay",+ })+ if res.Outcome != OutcomeDropped || res.DropReason != DropReasonDuplicate {+ t.Fatalf("dedup must beat identity check; got %+v", res)+ }+ if queries.calledUserBinding != 0 {+ t.Fatalf("identity check must not run for a deduped replay, got %d calls",+ queries.calledUserBinding)+ }+}++func TestDispatcher_IssueCommandCreatesIssue(t *testing.T) {+ sessionID := validUUID(0x66)+ inst := activeInstallation()+ queries := &fakeQueries{+ installationByApp: inst,+ userBinding: boundUser(),+ chatSession: db.ChatSession{ID: sessionID, AgentID: inst.AgentID},+ workspace: db.Workspace{ID: inst.WorkspaceID, IssuePrefix: "MUL"},+ }+ chat := &fakeChat{+ ensureID: sessionID,+ appendResult: AppendResult{+ IssueCommand: &IssueCommand{Title: "ship it", Description: "ship the thing"},+ },+ }+ issueSvc := &fakeIssueCreator{result: service.IssueCreateResult{Issue: db.Issue{+ ID: validUUID(0x88),+ Number: 42,+ Title: "ship it",+ }}}+ d := &Dispatcher{+ Queries: queries,+ Chat: chat,+ Audit: &fakeAudit{},+ IssueService: issueSvc,+ TaskService: &fakeEnqueuer{task: db.AgentTaskQueue{ID: validUUID(0x77)}},+ }++ res, err := d.Handle(context.Background(), InboundMessage{+ AppID: "ok",+ ChatType: ChatTypeP2P,+ SenderOpenID: "ou_user_a",+ Body: "/issue ship it\nship the thing",+ MessageID: "msg-ic",+ })+ if err != nil {+ t.Fatalf("unexpected error: %v", err)+ }+ if issueSvc.called != 1 {+ t.Fatalf("expected IssueService.Create called once, got %d", issueSvc.called)+ }+ if issueSvc.params.Title != "ship it" || issueSvc.params.Description.String != "ship the thing" {+ t.Fatalf("wrong issue params: %+v", issueSvc.params)+ }+ if issueSvc.params.OriginType.String != originLarkChat {+ t.Fatalf("origin_type should be lark_chat, got %q", issueSvc.params.OriginType.String)+ }+ if !issueSvc.params.AssigneeType.Valid || issueSvc.params.AssigneeType.String != "agent" ||+ issueSvc.params.AssigneeID != inst.AgentID {+ t.Fatalf("assignee should default to the installation's agent: %+v", issueSvc.params)+ }+ if !res.IssueID.Valid || res.IssueNumber != 42 {+ t.Fatalf("issue id/number not propagated: %+v", res)+ }+ // IssueIdentifier and IssueTitle are how the OutcomeReplier knows+ // what to put in the "Created [MUL-42] ship it" confirmation+ // message. They MUST be populated whenever a /issue command+ // produced a row.+ if res.IssueIdentifier != "MUL-42" {+ t.Fatalf("issue identifier should reflect workspace prefix; got %q", res.IssueIdentifier)+ }+ if res.IssueTitle != "ship it" {+ t.Fatalf("issue title should be propagated; got %q", res.IssueTitle)+ }+}++// TestDispatcher_IssueIdentifierFallsBackToNumberOnWorkspaceLookupErr+// pins the degrade-gracefully behaviour: a Postgres blip on the+// workspace row should NOT silently drop the issue-created+// confirmation. We emit "#42" instead of "MUL-42" in that case so+// the user still sees that the issue was created.+func TestDispatcher_IssueIdentifierFallsBackToNumberOnWorkspaceLookupErr(t *testing.T) {+ sessionID := validUUID(0x66)+ inst := activeInstallation()+ queries := &fakeQueries{+ installationByApp: inst,+ userBinding: boundUser(),+ chatSession: db.ChatSession{ID: sessionID, AgentID: inst.AgentID},+ workspaceErr: errors.New("workspace lookup failed"),+ }+ chat := &fakeChat{+ ensureID: sessionID,+ appendResult: AppendResult{+ IssueCommand: &IssueCommand{Title: "fallback path", Description: ""},+ },+ }+ issueSvc := &fakeIssueCreator{result: service.IssueCreateResult{Issue: db.Issue{+ ID: validUUID(0x88),+ Number: 7,+ Title: "fallback path",+ }}}+ d := &Dispatcher{+ Queries: queries,+ Chat: chat,+ Audit: &fakeAudit{},+ IssueService: issueSvc,+ TaskService: &fakeEnqueuer{task: db.AgentTaskQueue{ID: validUUID(0x77)}},+ }++ res, err := d.Handle(context.Background(), InboundMessage{+ AppID: "ok",+ ChatType: ChatTypeP2P,+ SenderOpenID: "ou_user_a",+ Body: "/issue fallback path",+ MessageID: "msg-fallback",+ })+ if err != nil {+ t.Fatalf("workspace lookup error must NOT abort dispatch; got %v", err)+ }+ if res.IssueIdentifier != "#7" {+ t.Errorf("expected fallback identifier '#7'; got %q", res.IssueIdentifier)+ }+}++func TestDispatcher_EmptyTitleSurfacesError(t *testing.T) {+ sessionID := validUUID(0x66)+ inst := activeInstallation()+ queries := &fakeQueries{+ installationByApp: inst,+ userBinding: boundUser(),+ chatSession: db.ChatSession{ID: sessionID, AgentID: inst.AgentID},+ }+ chat := &fakeChat{+ ensureID: sessionID,+ appendResult: AppendResult{+ IssueCommand: &IssueCommand{Title: ""},+ },+ }+ issueSvc := &fakeIssueCreator{}+ d := &Dispatcher{+ Queries: queries,+ Chat: chat,+ Audit: &fakeAudit{},+ IssueService: issueSvc,+ TaskService: &fakeEnqueuer{},+ }++ _, err := d.Handle(context.Background(), InboundMessage{+ AppID: "ok",+ ChatType: ChatTypeP2P,+ SenderOpenID: "ou_user_a",+ Body: "/issue",+ MessageID: "msg-empty",+ })+ if !errors.Is(err, ErrEmptyIssueTitle) {+ t.Fatalf("expected ErrEmptyIssueTitle wrapped, got %v", err)+ }+ if issueSvc.called != 0 {+ t.Fatalf("IssueService.Create must not run when title is empty")+ }+}++func TestDispatcher_AgentOfflineFallsThroughCleanly(t *testing.T) {+ sessionID := validUUID(0x66)+ queries := &fakeQueries{+ installationByApp: activeInstallation(),+ userBinding: boundUser(),+ chatSession: db.ChatSession{ID: sessionID, AgentID: validUUID(0x33)},+ }+ chat := &fakeChat{ensureID: sessionID, appendResult: AppendResult{}}+ enq := &fakeEnqueuer{err: service.ErrChatTaskAgentNoRuntime}+ d := &Dispatcher{+ Queries: queries,+ Chat: chat,+ Audit: &fakeAudit{},+ TaskService: enq,+ }++ res, err := d.Handle(context.Background(), InboundMessage{+ AppID: "ok",+ ChatType: ChatTypeP2P,+ SenderOpenID: "ou_user_a",+ Body: "hi",+ MessageID: "msg-off",+ })+ if err != nil {+ t.Fatalf("offline path should not return error, got %v", err)+ }+ if res.Outcome != OutcomeAgentOffline {+ t.Fatalf("expected OutcomeAgentOffline, got %q", res.Outcome)+ }+ if res.ChatSessionID != sessionID {+ t.Fatalf("session id not propagated: %+v", res.ChatSessionID)+ }+}++func TestDispatcher_AgentArchivedSurfacesDistinctOutcome(t *testing.T) {+ sessionID := validUUID(0x66)+ queries := &fakeQueries{+ installationByApp: activeInstallation(),+ userBinding: boundUser(),+ chatSession: db.ChatSession{ID: sessionID, AgentID: validUUID(0x33)},+ }+ chat := &fakeChat{ensureID: sessionID, appendResult: AppendResult{}}+ enq := &fakeEnqueuer{err: service.ErrChatTaskAgentArchived}+ d := &Dispatcher{+ Queries: queries,+ Chat: chat,+ Audit: &fakeAudit{},+ TaskService: enq,+ }++ res, err := d.Handle(context.Background(), InboundMessage{+ AppID: "ok",+ ChatType: ChatTypeP2P,+ SenderOpenID: "ou_user_a",+ Body: "hi",+ MessageID: "msg-arch",+ })+ if err != nil {+ t.Fatalf("archived path should not return error, got %v", err)+ }+ if res.Outcome != OutcomeAgentArchived {+ t.Fatalf("expected OutcomeAgentArchived, got %q", res.Outcome)+ }+}++func TestDispatcher_InfraFailureSurfacesError(t *testing.T) {+ // A DB / load / create failure from TaskService.EnqueueChatTask is+ // NOT a productizable state — the WS adapter must see a real+ // error so it can retry or page, not an "offline" card that+ // silently hides the outage.+ sessionID := validUUID(0x66)+ queries := &fakeQueries{+ installationByApp: activeInstallation(),+ userBinding: boundUser(),+ chatSession: db.ChatSession{ID: sessionID, AgentID: validUUID(0x33)},+ }+ chat := &fakeChat{ensureID: sessionID, appendResult: AppendResult{}}+ infraErr := errors.New("create chat task: connection refused")+ enq := &fakeEnqueuer{err: infraErr}+ d := &Dispatcher{+ Queries: queries,+ Chat: chat,+ Audit: &fakeAudit{},+ TaskService: enq,+ }++ _, err := d.Handle(context.Background(), InboundMessage{+ AppID: "ok",+ ChatType: ChatTypeP2P,+ SenderOpenID: "ou_user_a",+ Body: "hi",+ MessageID: "msg-infra",+ })+ if err == nil {+ t.Fatalf("infra failure should surface as error, got nil")+ }+ if !errors.Is(err, infraErr) {+ t.Fatalf("infra error should propagate (errors.Is), got %v", err)+ }+}++// TestDispatcher_EnsureChatSessionFailureReleasesClaim is the+// regression for the dedup-blocker Elon flagged in PR #3277: the+// pre-fix Dispatcher inserted the dedup row before EnsureChatSession,+// so an infra error in EnsureChatSession would leave a permanent+// dedup row behind and the WS adapter's retry would be mis-classified+// as a duplicate — the user's message would be silently lost.+//+// With the two-phase claim/Release contract, the first attempt's+// claim is released, and the retry must observe a fresh first+// delivery: identity check + EnsureChatSession + AppendUserMessage+// run normally, no duplicate drop.+func TestDispatcher_EnsureChatSessionFailureReleasesClaim(t *testing.T) {+ sessionID := validUUID(0x66)+ queries := &fakeQueries{+ installationByApp: activeInstallation(),+ userBinding: boundUser(),+ chatSession: db.ChatSession{ID: sessionID, AgentID: validUUID(0x33)},+ }+ chat := &fakeChat{+ ensureID: sessionID,+ ensureErr: errors.New("ensure chat session: connection refused"),+ }+ d := &Dispatcher{+ Queries: queries,+ Chat: chat,+ Audit: &fakeAudit{},+ TaskService: &fakeEnqueuer{task: db.AgentTaskQueue{ID: validUUID(0x77)}},+ }++ // First attempt — infra error in EnsureChatSession.+ _, err := d.Handle(context.Background(), InboundMessage{+ AppID: "ok",+ ChatType: ChatTypeP2P,+ SenderOpenID: "ou_user_a",+ Body: "hi",+ MessageID: "msg-retry",+ })+ if err == nil {+ t.Fatalf("first attempt should surface ensure-chat-session error, got nil")+ }+ if queries.calledMark != 0 {+ t.Fatalf("must not mark processed when no durable side effect landed; calledMark=%d", queries.calledMark)+ }+ if queries.calledRelease != 1 {+ t.Fatalf("must release the claim on pre-durable infra error; calledRelease=%d", queries.calledRelease)+ }+ if _, present := queries.dedup[seedDedupKey("msg-retry")]; present {+ t.Fatalf("release must delete the in-flight claim row; dedup=%+v", queries.dedup)+ }++ // Retry — same message_id, ensure succeeds this time. The claim+ // was released, so the retry must be able to re-claim and run+ // the full ingest pipeline. The bug being regressed would have+ // caused a DropReasonDuplicate here.+ chat.ensureErr = nil+ res, err := d.Handle(context.Background(), InboundMessage{+ AppID: "ok",+ ChatType: ChatTypeP2P,+ SenderOpenID: "ou_user_a",+ Body: "hi",+ MessageID: "msg-retry",+ })+ if err != nil {+ t.Fatalf("retry should succeed, got %v", err)+ }+ if res.Outcome != OutcomeIngested {+ t.Fatalf("retry must ingest; got outcome=%q reason=%q", res.Outcome, res.DropReason)+ }+ if chat.calledAppend != 1 {+ t.Fatalf("retry must reach AppendUserMessage; calledAppend=%d", chat.calledAppend)+ }+ if queries.calledMark != 1 {+ t.Fatalf("retry must mark processed; calledMark=%d", queries.calledMark)+ }+ if row, ok := queries.dedup[seedDedupKey("msg-retry")]; !ok || !row.processed {+ t.Fatalf("retry must finalize claim as processed; dedup=%+v", queries.dedup)+ }++ // A third attempt with the same message_id (post-success replay)+ // must now be a duplicate-drop — the Mark from the retry is the+ // terminal state.+ queries.calledClaim = 0+ chat.calledAppend = 0+ res, err = d.Handle(context.Background(), InboundMessage{+ AppID: "ok",+ ChatType: ChatTypeP2P,+ SenderOpenID: "ou_user_a",+ Body: "hi",+ MessageID: "msg-retry",+ })+ if err != nil {+ t.Fatalf("post-success replay should not error, got %v", err)+ }+ if res.Outcome != OutcomeDropped || res.DropReason != DropReasonDuplicate {+ t.Fatalf("post-success replay must duplicate-drop; got %+v", res)+ }+ if chat.calledAppend != 0 {+ t.Fatalf("post-success replay must not re-append; calledAppend=%d", chat.calledAppend)+ }+}++// TestDispatcher_AppendUserMessageFailureReleasesClaim is the+// regression for the second variant of the dedup blocker: an infra+// error from AppendUserMessage (e.g. tx commit failure) must also+// release the claim so a retry can re-ingest. AppendUserMessage's+// transaction is atomic — an error means rollback, no chat_message+// landed.+func TestDispatcher_AppendUserMessageFailureReleasesClaim(t *testing.T) {+ sessionID := validUUID(0x66)+ queries := &fakeQueries{+ installationByApp: activeInstallation(),+ userBinding: boundUser(),+ chatSession: db.ChatSession{ID: sessionID, AgentID: validUUID(0x33)},+ }+ chat := &fakeChat{+ ensureID: sessionID,+ appendErr: errors.New("create chat message: connection refused"),+ }+ d := &Dispatcher{+ Queries: queries,+ Chat: chat,+ Audit: &fakeAudit{},+ TaskService: &fakeEnqueuer{task: db.AgentTaskQueue{ID: validUUID(0x77)}},+ }++ // First attempt — append fails.+ _, err := d.Handle(context.Background(), InboundMessage{+ AppID: "ok",+ ChatType: ChatTypeP2P,+ SenderOpenID: "ou_user_a",+ Body: "hi",+ MessageID: "msg-append-retry",+ })+ if err == nil {+ t.Fatalf("first attempt should surface append error, got nil")+ }+ if queries.calledMark != 0 {+ t.Fatalf("must not mark processed when AppendUserMessage rolled back; calledMark=%d", queries.calledMark)+ }+ if queries.calledRelease != 1 {+ t.Fatalf("must release the claim; calledRelease=%d", queries.calledRelease)+ }++ // Retry — same message_id, append succeeds.+ chat.appendErr = nil+ res, err := d.Handle(context.Background(), InboundMessage{+ AppID: "ok",+ ChatType: ChatTypeP2P,+ SenderOpenID: "ou_user_a",+ Body: "hi",+ MessageID: "msg-append-retry",+ })+ if err != nil {+ t.Fatalf("retry should succeed, got %v", err)+ }+ if res.Outcome != OutcomeIngested {+ t.Fatalf("retry must ingest; got %+v", res)+ }+ if chat.calledAppend != 2 {+ t.Fatalf("expected exactly two append attempts (1 failed + 1 retry); calledAppend=%d", chat.calledAppend)+ }+}++// TestDispatcher_DurableErrorMarksClaim pins the inverse of the+// release path: when AppendUserMessage has succeeded (chat_message+// committed) but a downstream step returns an error, the dispatcher+// MUST mark the claim processed. Otherwise a replay would re-process+// the message and write a second chat_message row.+func TestDispatcher_DurableErrorMarksClaim(t *testing.T) {+ sessionID := validUUID(0x66)+ queries := &fakeQueries{+ installationByApp: activeInstallation(),+ userBinding: boundUser(),+ chatSession: db.ChatSession{ID: sessionID, AgentID: validUUID(0x33)},+ }+ chat := &fakeChat{+ ensureID: sessionID,+ appendResult: AppendResult{},+ }+ infraErr := errors.New("create chat task: connection refused")+ d := &Dispatcher{+ Queries: queries,+ Chat: chat,+ Audit: &fakeAudit{},+ TaskService: &fakeEnqueuer{err: infraErr},+ }++ _, err := d.Handle(context.Background(), InboundMessage{+ AppID: "ok",+ ChatType: ChatTypeP2P,+ SenderOpenID: "ou_user_a",+ Body: "hi",+ MessageID: "msg-durable-err",+ })+ if !errors.Is(err, infraErr) {+ t.Fatalf("expected infra error to propagate, got %v", err)+ }+ if queries.calledRelease != 0 {+ t.Fatalf("must not release: chat_message already committed; calledRelease=%d", queries.calledRelease)+ }+ if queries.calledMark != 1 {+ t.Fatalf("must mark processed: chat_message committed before the enqueue error; calledMark=%d", queries.calledMark)+ }+ if row, ok := queries.dedup[seedDedupKey("msg-durable-err")]; !ok || !row.processed {+ t.Fatalf("dedup row must end up processed=true; got %+v", queries.dedup)+ }+}++// TestDispatcher_DropMarksClaim pins that audit-drop branches (group+// filter, unbound user) finalize their claim as processed, so a+// reconnect replay does NOT re-write the audit row or re-fire any+// binding-prompt side effect. This is the "no audit / card spam"+// invariant from §4.3.+func TestDispatcher_DropMarksClaim(t *testing.T) {+ queries := &fakeQueries{+ installationByApp: activeInstallation(),+ userBindingErr: pgx.ErrNoRows,+ }+ audit := &fakeAudit{}+ d := &Dispatcher{Queries: queries, Audit: audit}++ _, _ = d.Handle(context.Background(), InboundMessage{+ AppID: "ok",+ ChatType: ChatTypeP2P,+ SenderOpenID: "ou_user_a",+ MessageID: "msg-unbound",+ })+ if queries.calledMark != 1 {+ t.Fatalf("unbound-user drop must mark claim processed; calledMark=%d", queries.calledMark)+ }+ if queries.calledRelease != 0 {+ t.Fatalf("unbound-user drop must not release; calledRelease=%d", queries.calledRelease)+ }+}++// TestDispatcher_EmptyMessageIDSkipsDedup pins that non-message+// events (no MessageID) bypass dedup entirely — there is no key to+// deduplicate by, and the dispatcher must not call Claim / Mark /+// Release for them.+func TestDispatcher_EmptyMessageIDSkipsDedup(t *testing.T) {+ queries := &fakeQueries{+ installationByApp: activeInstallation(),+ }+ d := &Dispatcher{Queries: queries, Audit: &fakeAudit{}}++ _, _ = d.Handle(context.Background(), InboundMessage{+ AppID: "ok",+ ChatType: ChatTypeGroup, // group filter drops it+ // MessageID intentionally empty+ })+ if queries.calledClaim != 0 || queries.calledMark != 0 || queries.calledRelease != 0 {+ t.Fatalf("empty MessageID must skip dedup entirely; claim=%d mark=%d release=%d",+ queries.calledClaim, queries.calledMark, queries.calledRelease)+ }+}++// TestDispatcher_InFlightClaimDropsReplay covers the "another worker+// is processing" branch: a fresh in-flight claim (processed=false,+// not yet stale) must duplicate-drop a concurrent replay, NOT+// re-process. This is the protection against two replicas+// simultaneously consuming the same Lark event during a brief+// double-leased window.+func TestDispatcher_InFlightClaimDropsReplay(t *testing.T) {+ queries := &fakeQueries{+ installationByApp: activeInstallation(),+ userBinding: boundUser(),+ // In-flight claim (processed=false) and reclaim disabled+ // (simulates "the row is fresh — not stale yet").+ dedup: map[string]*fakeDedupRow{seedDedupKey("msg-inflight"): {processed: false, token: validUUID(0xAB)}},+ }+ chat := &fakeChat{}+ d := &Dispatcher{+ Queries: queries,+ Chat: chat,+ Audit: &fakeAudit{},+ TaskService: &fakeEnqueuer{},+ }++ res, err := d.Handle(context.Background(), InboundMessage{+ AppID: "ok",+ ChatType: ChatTypeP2P,+ SenderOpenID: "ou_user_a",+ Body: "race",+ MessageID: "msg-inflight",+ })+ if err != nil {+ t.Fatalf("unexpected error: %v", err)+ }+ if res.Outcome != OutcomeDropped || res.DropReason != DropReasonDuplicate {+ t.Fatalf("in-flight claim must drop the replay; got %+v", res)+ }+ if chat.calledEnsure != 0 || chat.calledAppend != 0 {+ t.Fatalf("in-flight drop must short-circuit before chat lookup; ensure=%d append=%d",+ chat.calledEnsure, chat.calledAppend)+ }+}++// TestDispatcher_StaleInFlightClaimReclaimable covers the+// crash-recovery branch: an in-flight claim older than the staleness+// TTL must be re-takeable so a process crash mid-pipeline does not+// leave the message stuck forever.+func TestDispatcher_StaleInFlightClaimReclaimable(t *testing.T) {+ sessionID := validUUID(0x66)+ queries := &fakeQueries{+ installationByApp: activeInstallation(),+ userBinding: boundUser(),+ chatSession: db.ChatSession{ID: sessionID, AgentID: validUUID(0x33)},+ dedup: map[string]*fakeDedupRow{seedDedupKey("msg-stale"): {processed: false, token: validUUID(0xAB)}},+ dedupReclaim: true, // simulates received_at < now() - 60s+ }+ chat := &fakeChat{ensureID: sessionID, appendResult: AppendResult{}}+ d := &Dispatcher{+ Queries: queries,+ Chat: chat,+ Audit: &fakeAudit{},+ TaskService: &fakeEnqueuer{task: db.AgentTaskQueue{ID: validUUID(0x77)}},+ }++ res, err := d.Handle(context.Background(), InboundMessage{+ AppID: "ok",+ ChatType: ChatTypeP2P,+ SenderOpenID: "ou_user_a",+ Body: "after-crash retry",+ MessageID: "msg-stale",+ })+ if err != nil {+ t.Fatalf("stale-claim retry should succeed, got %v", err)+ }+ if res.Outcome != OutcomeIngested {+ t.Fatalf("stale-claim retry must ingest; got %+v", res)+ }+ if queries.calledMark != 1 {+ t.Fatalf("stale-claim retry must mark processed; calledMark=%d", queries.calledMark)+ }+}++// TestDispatcher_StaleReclaimRaceDoesNotDoubleWrite is the regression+// for Elon's first must-fix on PR #3277 dedup: worker A claims a+// dedup row at t=0 with token T_A, runs slowly past the 60-second+// staleness TTL, and is still alive. Worker B (a replay) sees the row+// as stale-reclaimable, takes the claim, rotates the token to T_B,+// and runs the full ingest pipeline. A subsequently reaches its in-tx+// Mark with the old T_A. WITHOUT owner fencing both A and B would+// commit a chat_message for the same Lark message_id — the bug Elon+// flagged. WITH owner fencing A's Mark matches zero rows, the in-tx+// Mark returns ErrClaimLost, A's chat_message+session transaction+// rolls back, and B is the sole writer.+//+// The test reproduces this by inverting the timeline: worker A is+// Handle()'s active call, and worker B is injected by the+// `beforeAppend` hook, which rotates the row's claim_token between+// the dispatcher's ClaimLarkInboundDedup call and AppendUserMessage's+// in-tx Mark. The hook fires exactly once so the second Handle()+// continues normally.+func TestDispatcher_StaleReclaimRaceDoesNotDoubleWrite(t *testing.T) {+ sessionID := validUUID(0x66)+ queries := &fakeQueries{+ installationByApp: activeInstallation(),+ userBinding: boundUser(),+ chatSession: db.ChatSession{ID: sessionID, AgentID: validUUID(0x33)},+ }+ chat := &fakeChat{ensureID: sessionID, appendResult: AppendResult{}}+ chat.queries = queries // model the production in-tx Mark+ d := &Dispatcher{+ Queries: queries,+ Chat: chat,+ Audit: &fakeAudit{},+ TaskService: &fakeEnqueuer{task: db.AgentTaskQueue{ID: validUUID(0x77)}},+ }++ // Inject worker B's reclaim. The hook fires while worker A's+ // AppendUserMessage is running with its original (now-stale)+ // token; ClaimLarkInboundDedup with dedupReclaim=true rotates the+ // row's claim_token to T_B. When fakeChat then attempts the in-tx+ // Mark with T_A it must match zero rows and return ErrClaimLost.+ raceFired := false+ originalToken := pgtype.UUID{}+ chat.beforeAppend = func(p AppendUserMessageParams) {+ if raceFired {+ return+ }+ raceFired = true+ originalToken = p.ClaimToken+ // Make the existing in-flight row reclaimable, then have+ // worker B re-Claim. This rotates claim_token under A's feet.+ queries.dedupReclaim = true+ if _, err := queries.ClaimLarkInboundDedup(context.Background(), db.ClaimLarkInboundDedupParams{+ InstallationID: p.InstallationID,+ MessageID: p.LarkMessageID,+ }); err != nil {+ t.Fatalf("worker-B reclaim setup failed: %v", err)+ }+ // Switch reclaim off so the dispatcher-level retry path (the+ // second Handle below) doesn't keep rotating the token.+ queries.dedupReclaim = false+ }++ res, err := d.Handle(context.Background(), InboundMessage{+ AppID: "ok",+ ChatType: ChatTypeP2P,+ SenderOpenID: "ou_user_a",+ Body: "slow-worker A",+ MessageID: "msg-race",+ })+ if err != nil {+ t.Fatalf("stale-reclaim race should surface as duplicate drop, not error; got %v", err)+ }+ if res.Outcome != OutcomeDropped || res.DropReason != DropReasonDuplicate {+ t.Fatalf("worker A must observe duplicate drop after losing claim; got %+v", res)+ }++ // Critical regression assertion: worker A must NOT have committed+ // a chat_message. AppendUserMessage was called (race hook fired),+ // but its in-tx Mark matched zero rows, so the tx rolled back.+ // The "chat_message committed" signal in this fake is appendResult+ // — fakeChat returning success would have made calledAppend bump+ // AND the row would have been marked under A's token; instead A+ // got ErrClaimLost. To pin "no double write" we check that the+ // row's processed_at was set by worker B's path (the rotated+ // token, T_B), not by worker A's old token (T_A).+ row, ok := queries.dedup[seedDedupKey("msg-race")]+ if !ok {+ t.Fatalf("dedup row must still exist after race; got %+v", queries.dedup)+ }+ if row.rotations < 2 {+ t.Fatalf("worker B's reclaim must have rotated the token; rotations=%d", row.rotations)+ }+ if row.token == originalToken {+ t.Fatalf("token must have rotated away from worker A's original; both=%v", originalToken)+ }++ // And the loser's audit row records duplicate (not double-ingest).+ if chat.calledAppend != 1 {+ t.Fatalf("worker A's append must have been attempted exactly once; calledAppend=%d", chat.calledAppend)+ }++ // A subsequent replay of the same message_id must still+ // duplicate-drop — the row is in the in-flight state belonging to+ // worker B's (uncompleted) run; the dispatcher cannot double-write+ // even if B's process never finishes. We simulate that by leaving+ // dedupReclaim=false so the row is treated as fresh in-flight.+ chat.beforeAppend = nil+ res2, err := d.Handle(context.Background(), InboundMessage{+ AppID: "ok",+ ChatType: ChatTypeP2P,+ SenderOpenID: "ou_user_a",+ Body: "third-arrival replay",+ MessageID: "msg-race",+ })+ if err != nil {+ t.Fatalf("post-race replay should not error, got %v", err)+ }+ if res2.Outcome != OutcomeDropped || res2.DropReason != DropReasonDuplicate {+ t.Fatalf("post-race replay must duplicate-drop; got %+v", res2)+ }+}++// TestDispatcher_InTxMarkPreventsPostCommitReclaim is the regression+// for Elon's second must-fix on PR #3277 dedup: in the previous+// design, a process that committed chat_message but crashed or failed+// before MarkLarkInboundDedupProcessed left the dedup row in-flight;+// 60 seconds later a retry would treat the row as stale, re-claim it,+// and write a second chat_message. The fix moves Mark INSIDE the+// chat_message+session transaction, so the durable write and the Mark+// commit (or roll back) atomically — there is no window where+// chat_message is committed but dedup is not.+//+// This test pins the invariant by simulating a successful in-tx Mark,+// then "crashing" (Handle returns without further bookkeeping), then+// replaying the same message_id and verifying it is duplicate-dropped+// regardless of the staleness TTL setting.+func TestDispatcher_InTxMarkPreventsPostCommitReclaim(t *testing.T) {+ sessionID := validUUID(0x66)+ queries := &fakeQueries{+ installationByApp: activeInstallation(),+ userBinding: boundUser(),+ chatSession: db.ChatSession{ID: sessionID, AgentID: validUUID(0x33)},+ }+ chat := &fakeChat{ensureID: sessionID, appendResult: AppendResult{}}+ chat.queries = queries+ d := &Dispatcher{+ Queries: queries,+ Chat: chat,+ Audit: &fakeAudit{},+ TaskService: &fakeEnqueuer{task: db.AgentTaskQueue{ID: validUUID(0x77)}},+ }++ res, err := d.Handle(context.Background(), InboundMessage{+ AppID: "ok",+ ChatType: ChatTypeP2P,+ SenderOpenID: "ou_user_a",+ Body: "first delivery",+ MessageID: "msg-atomic",+ })+ if err != nil {+ t.Fatalf("first delivery should succeed, got %v", err)+ }+ if res.Outcome != OutcomeIngested {+ t.Fatalf("first delivery must ingest; got %+v", res)+ }++ // AppendUserMessage's in-tx Mark fired; the dispatcher's post-+ // pipeline applyFinalize saw DedupMarked=true and skipped its+ // own Mark call. Total fakeQueries.MarkLarkInboundDedupProcessed+ // calls must therefore be exactly 1 — proves the in-tx path was+ // the sole writer.+ if queries.calledMark != 1 {+ t.Fatalf("expected exactly one Mark call (in-tx only, no post-finalize duplicate); calledMark=%d",+ queries.calledMark)+ }+ row, ok := queries.dedup[seedDedupKey("msg-atomic")]+ if !ok || !row.processed {+ t.Fatalf("dedup row must be terminal after in-tx Mark; got %+v", queries.dedup)+ }++ // Now simulate the dangerous scenario the OLD design failed: a+ // retry replays the same message_id AFTER the staleness TTL would+ // have expired. With the new design, processed_at IS NOT NULL+ // shadows the staleness check, so even with dedupReclaim=true the+ // Claim cannot re-acquire the row. The retry is a duplicate-drop.+ queries.dedupReclaim = true+ chat.calledAppend = 0+ res2, err := d.Handle(context.Background(), InboundMessage{+ AppID: "ok",+ ChatType: ChatTypeP2P,+ SenderOpenID: "ou_user_a",+ Body: "after-crash retry",+ MessageID: "msg-atomic",+ })+ if err != nil {+ t.Fatalf("post-mark retry should not error, got %v", err)+ }+ if res2.Outcome != OutcomeDropped || res2.DropReason != DropReasonDuplicate {+ t.Fatalf("post-mark retry must duplicate-drop; got %+v", res2)+ }+ if chat.calledAppend != 0 {+ t.Fatalf("post-mark retry must short-circuit before AppendUserMessage; calledAppend=%d",+ chat.calledAppend)+ }+ // The dedup row must remain processed=true and unrotated — the+ // Claim hit the terminal-row branch (no UPDATE), so claim_token+ // did NOT mint a new value.+ if row, ok := queries.dedup[seedDedupKey("msg-atomic")]; !ok || !row.processed {+ t.Fatalf("dedup row must stay terminal after replay; got %+v", queries.dedup)+ }+ if queries.dedup[seedDedupKey("msg-atomic")].rotations != 1 {+ t.Fatalf("claim_token must not rotate when the row is already processed; rotations=%d",+ queries.dedup[seedDedupKey("msg-atomic")].rotations)+ }+}++// TestDispatcher_InTxMarkSucceedsAndSkipsPostFinalize is a positive+// regression for the in-tx Mark path: when AppendUserMessage returns+// DedupMarked=true the dispatcher must NOT issue an additional Mark+// from applyFinalize. This is the contract that makes the new design+// safe — calling Mark twice is benign at the SQL layer (the+// processed_at IS NULL guard makes the second call a no-op), but the+// extra round-trip would defeat the "in-tx atomic finalize" goal.+func TestDispatcher_InTxMarkSucceedsAndSkipsPostFinalize(t *testing.T) {+ sessionID := validUUID(0x66)+ queries := &fakeQueries{+ installationByApp: activeInstallation(),+ userBinding: boundUser(),+ chatSession: db.ChatSession{ID: sessionID, AgentID: validUUID(0x33)},+ }+ chat := &fakeChat{ensureID: sessionID, appendResult: AppendResult{}}+ chat.queries = queries+ d := &Dispatcher{+ Queries: queries,+ Chat: chat,+ Audit: &fakeAudit{},+ TaskService: &fakeEnqueuer{task: db.AgentTaskQueue{ID: validUUID(0x77)}},+ }++ _, err := d.Handle(context.Background(), InboundMessage{+ AppID: "ok",+ ChatType: ChatTypeP2P,+ SenderOpenID: "ou_user_a",+ Body: "hi",+ MessageID: "msg-in-tx",+ })+ if err != nil {+ t.Fatalf("unexpected error: %v", err)+ }+ if queries.calledMark != 1 {+ t.Fatalf("exactly one Mark call expected (in-tx only); calledMark=%d", queries.calledMark)+ }+ // Verify the dispatcher did not also Release — applyFinalize must+ // be a no-op (finalizeNone) when AppendUserMessage marked in-tx.+ if queries.calledRelease != 0 {+ t.Fatalf("dispatcher must not release after successful in-tx Mark; calledRelease=%d",+ queries.calledRelease)+ }+}diff --git a/server/internal/integrations/lark/doc.go b/server/internal/integrations/lark/doc.gonew file mode 100644index 0000000000..07483b73a2--- /dev/null+++ b/server/internal/integrations/lark/doc.go@@ -0,0 +1,59 @@+// Package lark contains the Multica ↔ 飞书 (Lark) Bot integration.+//+// MVP scope is tracked in MUL-2671. After the migration / service+// boundary PRs landed, this package now covers:+//+// 1. DB schema + sqlc wrappers (migration 109_lark_integration.up.sql)+// 2. InstallationService (encrypted app_secret, workspace-scoped lookups)+// 3. BindingTokenService (15-minute single-use, transactional redeem+// that rejects cross-user rebinds in-DB)+// 4. ChatSessionService (channel-aware chat_session ensure / append+// with /issue command parsing)+// 5. Dispatcher (inbound pipeline: installation route → top-level+// message_id dedup → group filter → identity check → ensure+// session → append → /issue → enqueue chat task; typed outcomes+// for offline / archived; emit returns DispatchResult + error so+// the connector can post the matching Lark-side reply card)+// 6. AuditLogger (lark_inbound_audit; deliberately no body column)+// 7. APIClient interface + http_client.go (real Lark Open Platform+// transport for IM v1 send/patch + binding prompt + bot info;+// stubAPIClient refuses calls when no production client is wired)+// 8. Hub (WS lease + per-installation supervisor goroutines with+// exponential backoff + jitter; renewer cancels the connector's+// run ctx on lease loss to keep §4.4 ownership safe across+// replicas; EventConnector interface is the seam for the real+// wire protocol)+// 9. WSLongConnConnector (real long-conn over gorilla/websocket; the+// wire protocol is the binary Frame envelope from the official Go+// SDK — bootstrap via POST /callback/ws/endpoint, app-layer+// ping/pong, ACK responses on every data frame, ctx cancel breaks+// blocking ReadMessage via a watchdog goroutine for §4.4)+// 10. Patcher (subscribes to task / chat-done events; keeps the+// per-task Lark interactive card in sync; throttled patches ++// final/error bypass)+// 11. OutcomeReplier (outbound side of the EventEmitter contract:+// NeedsBinding mints a token + sends the binding prompt;+// AgentOffline / AgentArchived push status notice cards into the+// chat; Ingested is owned by the Patcher; Dropped is silent)+// 12. RegistrationService (RFC 8628 device-flow scan-to-install: opens+// a session against accounts.feishu.cn, polls in the background,+// and on success writes through InstallationService + auto-binds+// the installer via InstallerBinder so §2.1 "scan to bind, you're+// done" holds end-to-end)+//+// Architectural boundaries (frozen from Elon's 二审, MUL-2671 §4.8):+//+// 1. Issue creation goes through internal/service.IssueService.Create —+// this package never calls qtx.CreateIssue directly.+// 2. Inbound message ingestion uses ChatSessionService here, NOT the+// HTTP `SendChatMessage` handler. Group chat_sessions have multi-+// member creator semantics that the HTTP handler's single-creator+// guard rejects on purpose.+// 3. Outbound card-message mapping lives in `lark_outbound_card_message`+// (per task/message), never on `chat_session.metadata`.+// 4. Unbound users and non-workspace members never reach+// chat_session/chat_message. They land in `lark_inbound_audit` (no+// body) with a drop_reason and nothing else.+// 5. `app_secret` is encrypted at rest via internal/util/secretbox.+// The DB never sees plaintext.+package larkdiff --git a/server/internal/integrations/lark/http_client.go b/server/internal/integrations/lark/http_client.gonew file mode 100644index 0000000000..ad28f8d230--- /dev/null+++ b/server/internal/integrations/lark/http_client.go@@ -0,0 +1,645 @@+package lark++import (+ "bytes"+ "context"+ "encoding/json"+ "errors"+ "fmt"+ "io"+ "log/slog"+ "net/http"+ "net/url"+ "strings"+ "sync"+ "time"+)++// Real Lark/飞书 Open Platform HTTP APIClient.+//+// Scope: tenant_access_token acquisition + caching, IM v1 interactive-+// card send / patch, the dedicated binding-prompt outbound, AND the+// install-time Bot identity lookup (/open-apis/bot/v3/info) consumed+// by RegistrationService right after a successful device-flow grant.+// The PersonalAgent registration protocol itself is a separate client+// (RegistrationClient) because it speaks to a different host+// (accounts.feishu.cn) with a different auth model (no+// tenant_access_token — the response IS the credentials).+//+// Per-installation credentials flow in on each call via+// InstallationCredentials; the client never reads lark_installation+// directly. tenant_access_token is cached in-process keyed by app_id,+// honoring Lark's `expire` field minus a safety margin so callers+// never present a token that's about to lapse mid-flight.++const (+ // defaultLarkBaseURL is the production 飞书 (mainland) open-platform+ // host. Operators on the Lark international tenant set+ // MULTICA_LARK_HTTP_BASE_URL to https://open.larksuite.com; tests+ // substitute an httptest.Server URL.+ defaultLarkBaseURL = "https://open.feishu.cn"++ // tokenSafetyMargin is subtracted from Lark's `expire` so we+ // refresh before a token actually lapses. 60s comfortably exceeds+ // any in-flight HTTP timeout we set below.+ tokenSafetyMargin = 60 * time.Second++ // defaultRequestTimeout is the per-call HTTP timeout. Lark's API+ // is normally well under 1s; we leave headroom for cross-region+ // latency from a self-hosted Multica deployment to feishu.cn.+ defaultRequestTimeout = 10 * time.Second++ // Lark's "invalid tenant_access_token" / "tenant_access_token+ // expired" error codes. When we see either, drop the cached token+ // so the next call refreshes from /tenant_access_token/internal.+ // 99991663 = expired, 99991664 = invalid. Documented at:+ // open.feishu.cn/document/server-docs/api-call-guide/server-error-codes.+ codeTokenExpired = 99991663+ codeTokenInvalid = 99991664+)++// HTTPClientConfig configures the production Lark HTTP APIClient.+type HTTPClientConfig struct {+ // BaseURL is the Lark open-platform root, e.g.+ // "https://open.feishu.cn" or "https://open.larksuite.com". Empty+ // defaults to defaultLarkBaseURL. Trailing "/" is stripped.+ BaseURL string++ // HTTPClient is the transport used for every outbound call. Tests+ // substitute an *http.Client whose Transport routes to an+ // httptest.Server. Empty defaults to a fresh http.Client with+ // defaultRequestTimeout.+ HTTPClient *http.Client++ // Now is overridable for deterministic token-expiry tests.+ Now func() time.Time++ // Logger receives warnings about Lark error codes. Nil uses+ // slog.Default().+ Logger *slog.Logger+}++func (c HTTPClientConfig) withDefaults() HTTPClientConfig {+ if c.BaseURL == "" {+ c.BaseURL = defaultLarkBaseURL+ }+ c.BaseURL = strings.TrimRight(c.BaseURL, "/")+ if c.HTTPClient == nil {+ c.HTTPClient = &http.Client{Timeout: defaultRequestTimeout}+ }+ if c.Now == nil {+ c.Now = time.Now+ }+ if c.Logger == nil {+ c.Logger = slog.Default()+ }+ return c+}++// NewHTTPAPIClient constructs the real APIClient that speaks to Lark's+// open platform over HTTPS. Per-installation credentials flow in via+// each call's InstallationCredentials parameter; tokens are cached+// keyed by app_id so a single Multica server reuses Lark's+// tenant_access_token across calls to the same app.+func NewHTTPAPIClient(cfg HTTPClientConfig) APIClient {+ cfg = cfg.withDefaults()+ return &httpAPIClient{cfg: cfg, tokens: make(map[string]*cachedToken)}+}++type httpAPIClient struct {+ cfg HTTPClientConfig++ mu sync.Mutex+ tokens map[string]*cachedToken+}++type cachedToken struct {+ value string+ expiresAt time.Time+}++// IsConfigured reports true: once this client exists at all, the+// outbound transport path (send / patch / binding prompt / bot info)+// is wired. The stub returns false because every call there errors+// with ErrAPIClientNotConfigured; the real client is the inverse+// contract.+func (c *httpAPIClient) IsConfigured() bool { return true }++// tenantAccessToken returns a usable tenant_access_token for the+// given installation, reusing a cached token while it is alive (minus+// safety margin) and otherwise fetching a fresh one from Lark.+//+// Concurrent callers serialize on the per-client mutex during the+// uncached path; the cached path takes the mutex only for the lookup+// and releases before doing any I/O. Steady-state contention is+// therefore one map-read under the lock, not a per-call HTTP round+// trip.+func (c *httpAPIClient) tenantAccessToken(ctx context.Context, creds InstallationCredentials) (string, error) {+ if creds.AppID == "" {+ return "", errors.New("lark http client: missing app_id")+ }+ if creds.AppSecret == "" {+ return "", errors.New("lark http client: missing app_secret")+ }++ now := c.cfg.Now()+ c.mu.Lock()+ if t, ok := c.tokens[creds.AppID]; ok && t.expiresAt.After(now) {+ val := t.value+ c.mu.Unlock()+ return val, nil+ }+ c.mu.Unlock()++ // Self-built (internal) app endpoint. Marketplace / multi-tenant+ // apps would use /tenant_access_token/v3 with a different body+ // shape; PersonalAgent in this MVP is per-workspace self-built so+ // we stay on /internal.+ body := map[string]string{+ "app_id": creds.AppID,+ "app_secret": creds.AppSecret,+ }+ var resp struct {+ Code int `json:"code"`+ Msg string `json:"msg"`+ TenantAccessToken string `json:"tenant_access_token"`+ Expire int64 `json:"expire"`+ }+ if err := c.doJSON(ctx, http.MethodPost, "/open-apis/auth/v3/tenant_access_token/internal", "", body, &resp); err != nil {+ return "", fmt.Errorf("lark http client: tenant_access_token: %w", err)+ }+ if resp.Code != 0 || resp.TenantAccessToken == "" {+ return "", fmt.Errorf("lark http client: tenant_access_token: code=%d msg=%q", resp.Code, resp.Msg)+ }++ expire := time.Duration(resp.Expire) * time.Second+ // Clamp to >= 2× safety margin so a misbehaving upstream that+ // returns a sub-minute expire never makes us cache a token that+ // is already past its safe window.+ if expire < tokenSafetyMargin*2 {+ expire = tokenSafetyMargin * 2+ }+ expiresAt := c.cfg.Now().Add(expire - tokenSafetyMargin)++ c.mu.Lock()+ c.tokens[creds.AppID] = &cachedToken{value: resp.TenantAccessToken, expiresAt: expiresAt}+ c.mu.Unlock()++ return resp.TenantAccessToken, nil+}++// invalidateToken drops the cached token for an app_id. Called when+// Lark surfaces an expired / invalid token error code so the next+// call refreshes instead of looping on a stale entry.+func (c *httpAPIClient) invalidateToken(appID string) {+ c.mu.Lock()+ delete(c.tokens, appID)+ c.mu.Unlock()+}++// SendInteractiveCard posts a fresh interactive card into a chat and+// returns Lark's message_id so the Patcher can target subsequent+// patches at the same card.+func (c *httpAPIClient) SendInteractiveCard(ctx context.Context, p SendCardParams) (string, error) {+ if p.ChatID == "" {+ return "", errors.New("lark http client: missing chat_id")+ }+ if p.CardJSON == "" {+ return "", errors.New("lark http client: missing card json")+ }+ token, err := c.tenantAccessToken(ctx, p.InstallationID)+ if err != nil {+ return "", err+ }+ q := url.Values{}+ q.Set("receive_id_type", "chat_id")+ body := map[string]string{+ "receive_id": string(p.ChatID),+ "msg_type": "interactive",+ "content": p.CardJSON,+ }+ var resp struct {+ Code int `json:"code"`+ Msg string `json:"msg"`+ Data struct {+ MessageID string `json:"message_id"`+ } `json:"data"`+ }+ path := "/open-apis/im/v1/messages?" + q.Encode()+ if err := c.doJSON(ctx, http.MethodPost, path, token, body, &resp); err != nil {+ return "", fmt.Errorf("lark http client: send interactive card: %w", err)+ }+ if resp.Code != 0 || resp.Data.MessageID == "" {+ if isTokenError(resp.Code) {+ c.invalidateToken(p.InstallationID.AppID)+ }+ return "", fmt.Errorf("lark http client: send interactive card: code=%d msg=%q", resp.Code, resp.Msg)+ }+ return resp.Data.MessageID, nil+}++// SendTextMessage posts a plain text IM message into a Lark chat.+// This is the Patcher's primary outbound for agent chat replies —+// using a normal text bubble instead of an interactive card makes+// free-form replies feel like a native Lark conversation. The+// content envelope Lark expects is a JSON-encoded `{"text": "..."}`+// blob; we encode it here so callers pass raw text.+func (c *httpAPIClient) SendTextMessage(ctx context.Context, p SendTextParams) (string, error) {+ if p.ChatID == "" {+ return "", errors.New("lark http client: missing chat_id")+ }+ if p.Text == "" {+ return "", errors.New("lark http client: missing text")+ }+ token, err := c.tenantAccessToken(ctx, p.InstallationID)+ if err != nil {+ return "", err+ }+ // Lark's `text` msg_type expects content = JSON-encoded {"text": "..."}.+ // json.Marshal handles the escape of newlines / quotes / unicode so+ // the agent's reply round-trips intact.+ contentBytes, err := json.Marshal(map[string]string{"text": p.Text})+ if err != nil {+ return "", fmt.Errorf("lark http client: encode text content: %w", err)+ }+ q := url.Values{}+ q.Set("receive_id_type", "chat_id")+ body := map[string]string{+ "receive_id": string(p.ChatID),+ "msg_type": "text",+ "content": string(contentBytes),+ }+ var resp struct {+ Code int `json:"code"`+ Msg string `json:"msg"`+ Data struct {+ MessageID string `json:"message_id"`+ } `json:"data"`+ }+ path := "/open-apis/im/v1/messages?" + q.Encode()+ if err := c.doJSON(ctx, http.MethodPost, path, token, body, &resp); err != nil {+ return "", fmt.Errorf("lark http client: send text message: %w", err)+ }+ if resp.Code != 0 || resp.Data.MessageID == "" {+ if isTokenError(resp.Code) {+ c.invalidateToken(p.InstallationID.AppID)+ }+ return "", fmt.Errorf("lark http client: send text message: code=%d msg=%q", resp.Code, resp.Msg)+ }+ return resp.Data.MessageID, nil+}++// SendMarkdownCard posts the agent's reply as an interactive card+// using Lark's schema-2.0 envelope with a single `tag: "markdown"`+// body element. Lark's client renders the markdown into formatted+// text (bold, italics, lists, links, fenced code blocks, tables, …)+// rather than showing raw markdown characters as it does for+// `msg_type=text`. We deliberately keep `SendTextMessage` as a+// separate path for plain-prose replies — a card around a one-line+// "Hello!" adds visual chrome that the user doesn't want; the+// routing decision (markdown vs text) lives at the Patcher layer.+//+// Why schema 2.0 rather than the legacy schema with a `div` ++// `lark_md` text element: the legacy `lark_md` tag's markdown+// dialect is much narrower — no fenced code blocks (syntax+// highlighting), no tables, no heading sizes. Schema-2.0's+// `markdown` tag is closer to GFM.+func (c *httpAPIClient) SendMarkdownCard(ctx context.Context, p SendMarkdownCardParams) (string, error) {+ if p.ChatID == "" {+ return "", errors.New("lark http client: missing chat_id")+ }+ if p.Markdown == "" {+ return "", errors.New("lark http client: missing markdown body")+ }+ token, err := c.tenantAccessToken(ctx, p.InstallationID)+ if err != nil {+ return "", err+ }+ card := map[string]any{+ "schema": "2.0",+ "body": map[string]any{+ "elements": []any{+ map[string]any{"tag": "markdown", "content": p.Markdown},+ },+ },+ }+ if p.Summary != "" {+ card["config"] = map[string]any{+ "summary": map[string]any{"content": p.Summary},+ }+ }+ cardBytes, err := json.Marshal(card)+ if err != nil {+ return "", fmt.Errorf("lark http client: encode markdown card: %w", err)+ }+ q := url.Values{}+ q.Set("receive_id_type", "chat_id")+ body := map[string]string{+ "receive_id": string(p.ChatID),+ "msg_type": "interactive",+ "content": string(cardBytes),+ }+ var resp struct {+ Code int `json:"code"`+ Msg string `json:"msg"`+ Data struct {+ MessageID string `json:"message_id"`+ } `json:"data"`+ }+ path := "/open-apis/im/v1/messages?" + q.Encode()+ if err := c.doJSON(ctx, http.MethodPost, path, token, body, &resp); err != nil {+ return "", fmt.Errorf("lark http client: send markdown card: %w", err)+ }+ if resp.Code != 0 || resp.Data.MessageID == "" {+ if isTokenError(resp.Code) {+ c.invalidateToken(p.InstallationID.AppID)+ }+ return "", fmt.Errorf("lark http client: send markdown card: code=%d msg=%q", resp.Code, resp.Msg)+ }+ return resp.Data.MessageID, nil+}++// PatchInteractiveCard updates an existing card's body. Lark's+// message-patch endpoint replaces the whole card payload; callers+// (i.e. the Patcher) render the full updated card each time.+func (c *httpAPIClient) PatchInteractiveCard(ctx context.Context, p PatchCardParams) error {+ if p.LarkCardMessageID == "" {+ return errors.New("lark http client: missing card message id")+ }+ if p.CardJSON == "" {+ return errors.New("lark http client: missing card json")+ }+ token, err := c.tenantAccessToken(ctx, p.InstallationID)+ if err != nil {+ return err+ }+ body := map[string]string{"content": p.CardJSON}+ var resp struct {+ Code int `json:"code"`+ Msg string `json:"msg"`+ }+ path := "/open-apis/im/v1/messages/" + url.PathEscape(p.LarkCardMessageID)+ if err := c.doJSON(ctx, http.MethodPatch, path, token, body, &resp); err != nil {+ return fmt.Errorf("lark http client: patch interactive card: %w", err)+ }+ if resp.Code != 0 {+ if isTokenError(resp.Code) {+ c.invalidateToken(p.InstallationID.AppID)+ }+ return fmt.Errorf("lark http client: patch interactive card: code=%d msg=%q", resp.Code, resp.Msg)+ }+ return nil+}++// SendBindingPromptCard renders the member-binding card and posts it+// directly to the unbound user's open_id (not the chat). Keeping the+// card template inside this client — rather than the dispatcher —+// means the dispatcher never has to know about Lark's card schema.+func (c *httpAPIClient) SendBindingPromptCard(ctx context.Context, p BindingPromptParams) error {+ if p.OpenID == "" {+ return errors.New("lark http client: missing open_id")+ }+ if p.BindURL == "" {+ return errors.New("lark http client: missing bind url")+ }+ cardJSON, err := bindingPromptTemplate(p.BindURL)+ if err != nil {+ return fmt.Errorf("lark http client: render binding prompt: %w", err)+ }+ token, err := c.tenantAccessToken(ctx, p.InstallationID)+ if err != nil {+ return err+ }+ q := url.Values{}+ q.Set("receive_id_type", "open_id")+ body := map[string]string{+ "receive_id": string(p.OpenID),+ "msg_type": "interactive",+ "content": cardJSON,+ }+ var resp struct {+ Code int `json:"code"`+ Msg string `json:"msg"`+ }+ path := "/open-apis/im/v1/messages?" + q.Encode()+ if err := c.doJSON(ctx, http.MethodPost, path, token, body, &resp); err != nil {+ return fmt.Errorf("lark http client: send binding prompt: %w", err)+ }+ if resp.Code != 0 {+ if isTokenError(resp.Code) {+ c.invalidateToken(p.InstallationID.AppID)+ }+ return fmt.Errorf("lark http client: send binding prompt: code=%d msg=%q", resp.Code, resp.Msg)+ }+ return nil+}++// GetBotInfo calls /open-apis/bot/v3/info to learn the Bot's+// per-installation `open_id` and then /open-apis/contact/v3/users/+// {open_id}?user_id_type=open_id to resolve its stable `union_id`.+// RegistrationService is the only caller — right after the device-+// flow registration returns fresh `client_id` / `client_secret`, the+// service mints a tenant_access_token with those creds and calls+// this method so the installation row can be frozen with both Bot+// identifiers in the same transaction as the installer-bind.+//+// Why two API calls instead of one: /bot/v3/info does not return+// union_id in the public schema. The WS inbound decoder needs+// union_id to disambiguate which bot was @-mentioned in a multi-bot+// group chat (the per-app open_id field on mentions is structurally+// inverse across WS perspectives — see MUL-2671 triage), so we+// invest one extra HTTP round-trip at install time to capture it+// and avoid running the wrong supervisor for every event going+// forward.+//+// A missing union_id (contact lookup denied by app scope, or Lark+// returns an empty field) is NOT a hard failure here — the+// installation is still usable for p2p chats and the decoder can+// fall back to the (broken) open_id match path until the operator+// fixes scopes. We log a warning so the gap is visible.+//+// Other fields the upstream APIs return (display name, avatar, IP+// whitelist) are deliberately dropped; downstream reads can fetch+// them on demand from the bot_open_id, and freezing them into our+// schema would create a drift surface every time the operator edits+// the Bot on Lark's side.+func (c *httpAPIClient) GetBotInfo(ctx context.Context, creds InstallationCredentials) (BotInfo, error) {+ if creds.AppID == "" || creds.AppSecret == "" {+ return BotInfo{}, errors.New("lark http client: missing app credentials for GetBotInfo")+ }+ token, err := c.tenantAccessToken(ctx, creds)+ if err != nil {+ return BotInfo{}, err+ }+ var botResp struct {+ Code int `json:"code"`+ Msg string `json:"msg"`+ Bot struct {+ OpenID string `json:"open_id"`+ } `json:"bot"`+ }+ if err := c.doJSON(ctx, http.MethodGet, "/open-apis/bot/v3/info", token, nil, &botResp); err != nil {+ return BotInfo{}, fmt.Errorf("lark http client: bot info: %w", err)+ }+ if botResp.Code != 0 {+ if isTokenError(botResp.Code) {+ c.invalidateToken(creds.AppID)+ }+ return BotInfo{}, fmt.Errorf("lark http client: bot info: code=%d msg=%q", botResp.Code, botResp.Msg)+ }+ if botResp.Bot.OpenID == "" {+ return BotInfo{}, errors.New("lark http client: bot info: response missing open_id")+ }++ // Resolve union_id via the contact endpoint. Soft-fail: log and+ // return the BotInfo with empty UnionID. Callers (Registration-+ // Service.finishSuccess) accept the gap and persist what they+ // have.+ unionID, lookupErr := c.fetchBotUnionID(ctx, creds.AppID, token, botResp.Bot.OpenID)+ if lookupErr != nil {+ c.cfg.Logger.Warn("lark http client: bot union_id lookup failed; continuing without it",+ "app_id", creds.AppID,+ "bot_open_id", botResp.Bot.OpenID,+ "err", lookupErr)+ }+ return BotInfo{OpenID: OpenID(botResp.Bot.OpenID), UnionID: unionID}, nil+}++// fetchBotUnionID resolves a Bot's `union_id` from its `open_id` via+// /open-apis/contact/v3/users/{open_id}?user_id_type=open_id. Split+// out from GetBotInfo so the failure mode is explicit and the call+// sites that only need open_id don't pay for the second round-trip.+//+// Empty string + nil error is a valid outcome: Lark's user endpoint+// can return code=0 with no union_id field when the app's contact+// scope is restricted. Caller logs and continues; the decoder still+// works in single-bot deployments where open_id-based matching is+// unambiguous.+func (c *httpAPIClient) fetchBotUnionID(ctx context.Context, appID, token, openID string) (string, error) {+ if openID == "" {+ return "", errors.New("empty open_id")+ }+ q := url.Values{}+ q.Set("user_id_type", "open_id")+ path := "/open-apis/contact/v3/users/" + url.PathEscape(openID) + "?" + q.Encode()+ var resp struct {+ Code int `json:"code"`+ Msg string `json:"msg"`+ Data struct {+ User struct {+ UnionID string `json:"union_id"`+ } `json:"user"`+ } `json:"data"`+ }+ if err := c.doJSON(ctx, http.MethodGet, path, token, nil, &resp); err != nil {+ return "", fmt.Errorf("contact users: %w", err)+ }+ if resp.Code != 0 {+ // invalidateToken is keyed by app_id (the cache key on+ // httpAPIClient.tokens), NOT by the bearer string. Passing+ // the bearer would do nothing and a stale token would keep+ // being reused on every retry until natural TTL expiry.+ if isTokenError(resp.Code) {+ c.invalidateToken(appID)+ }+ return "", fmt.Errorf("contact users: code=%d msg=%q", resp.Code, resp.Msg)+ }+ return resp.Data.User.UnionID, nil+}++// doJSON encapsulates the verb + URL + auth-header + JSON+// encode/decode dance so each public method stays a thin shape-only+// adapter. token == "" skips the Authorization header (only the+// tenant_access_token endpoint takes that path).+func (c *httpAPIClient) doJSON(ctx context.Context, method, path, token string, body, out any) error {+ var rdr io.Reader+ if body != nil {+ buf, err := json.Marshal(body)+ if err != nil {+ return fmt.Errorf("marshal body: %w", err)+ }+ rdr = bytes.NewReader(buf)+ }+ req, err := http.NewRequestWithContext(ctx, method, c.cfg.BaseURL+path, rdr)+ if err != nil {+ return fmt.Errorf("new request: %w", err)+ }+ if body != nil {+ req.Header.Set("Content-Type", "application/json; charset=utf-8")+ }+ if token != "" {+ req.Header.Set("Authorization", "Bearer "+token)+ }+ resp, err := c.cfg.HTTPClient.Do(req)+ if err != nil {+ return fmt.Errorf("http do: %w", err)+ }+ defer resp.Body.Close()+ rawBody, err := io.ReadAll(resp.Body)+ if err != nil {+ return fmt.Errorf("read body: %w", err)+ }+ if resp.StatusCode < 200 || resp.StatusCode >= 300 {+ return fmt.Errorf("http %d: %s", resp.StatusCode, truncate(string(rawBody), 512))+ }+ if out != nil && len(rawBody) > 0 {+ if err := json.Unmarshal(rawBody, out); err != nil {+ return fmt.Errorf("decode body: %w (raw=%s)", err, truncate(string(rawBody), 256))+ }+ }+ return nil+}++func isTokenError(code int) bool {+ return code == codeTokenExpired || code == codeTokenInvalid+}++func truncate(s string, n int) string {+ if len(s) <= n {+ return s+ }+ return s[:n] + "…"+}++// bindingPromptTemplate renders the "you need to bind" interactive+// card. Single primary CTA pointing at the redemption URL; the rest+// of the body is plain-text Chinese copy matching the in-app voice.+//+// Kept here (not in defaultRenderer) so the binding card template can+// evolve independently of the streaming-status cards the Patcher+// renders — they have different lifecycles (binding card is one-shot,+// status cards are patched in place).+func bindingPromptTemplate(bindURL string) (string, error) {+ doc := map[string]any{+ "config": map[string]any{"wide_screen_mode": true},+ "header": map[string]any{+ "template": "blue",+ "title": map[string]any{"tag": "plain_text", "content": "Multica"},+ },+ "elements": []any{+ map[string]any{+ "tag": "div",+ "text": map[string]any{+ "tag": "lark_md",+ "content": "你还没有绑定 Multica 账户。点击下方按钮完成绑定后即可使用此 Agent。",+ },+ },+ map[string]any{+ "tag": "action",+ "actions": []any{+ map[string]any{+ "tag": "button",+ "text": map[string]any{"tag": "plain_text", "content": "去绑定"},+ "type": "primary",+ "url": bindURL,+ },+ },+ },+ },+ }+ raw, err := json.Marshal(doc)+ if err != nil {+ return "", err+ }+ return string(raw), nil+}diff --git a/server/internal/integrations/lark/http_client_test.go b/server/internal/integrations/lark/http_client_test.gonew file mode 100644index 0000000000..139bec7713--- /dev/null+++ b/server/internal/integrations/lark/http_client_test.go@@ -0,0 +1,1019 @@+package lark++import (+ "context"+ "encoding/json"+ "io"+ "net/http"+ "net/http/httptest"+ "strings"+ "sync/atomic"+ "testing"+ "time"+)++// larkFakeServer is a tiny in-memory stand-in for the Lark Open+// Platform. Tests register handlers per path; the server panics if a+// path is hit without a registration (a missed assertion is louder+// than a 404).+//+// The handler shape mirrors http.HandlerFunc so each test can encode+// its own response without inheriting boilerplate.+type larkFakeServer struct {+ t *testing.T+ mux *http.ServeMux+ srv *httptest.Server+ tokenN atomic.Int32+ sendN atomic.Int32+ patchN atomic.Int32+ bindN atomic.Int32+ authObs atomic.Value // last Authorization header seen across all paths+}++func newLarkFake(t *testing.T) *larkFakeServer {+ t.Helper()+ f := &larkFakeServer{t: t, mux: http.NewServeMux()}+ f.srv = httptest.NewServer(f)+ t.Cleanup(f.srv.Close)+ return f+}++func (f *larkFakeServer) URL() string { return f.srv.URL }++func (f *larkFakeServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {+ if a := r.Header.Get("Authorization"); a != "" {+ f.authObs.Store(a)+ }+ f.mux.ServeHTTP(w, r)+}++func (f *larkFakeServer) lastAuth() string {+ v, _ := f.authObs.Load().(string)+ return v+}++// stubToken installs a token endpoint that returns the supplied token+// with the supplied expire (seconds) and counts hits.+func (f *larkFakeServer) stubToken(token string, expireSec int64) {+ f.mux.HandleFunc("/open-apis/auth/v3/tenant_access_token/internal", func(w http.ResponseWriter, r *http.Request) {+ f.tokenN.Add(1)+ if r.Method != http.MethodPost {+ f.t.Errorf("token: want POST, got %s", r.Method)+ }+ var body map[string]string+ if err := json.NewDecoder(r.Body).Decode(&body); err != nil {+ f.t.Errorf("token: decode body: %v", err)+ }+ if body["app_id"] == "" || body["app_secret"] == "" {+ f.t.Errorf("token: missing app credentials: %v", body)+ }+ writeJSON(w, map[string]any{+ "code": 0,+ "msg": "ok",+ "tenant_access_token": token,+ "expire": expireSec,+ })+ })+}++// stubTokenError installs a token endpoint returning a Lark-style+// error code (non-zero `code` with HTTP 200).+func (f *larkFakeServer) stubTokenError(code int, msg string) {+ f.mux.HandleFunc("/open-apis/auth/v3/tenant_access_token/internal", func(w http.ResponseWriter, r *http.Request) {+ f.tokenN.Add(1)+ writeJSON(w, map[string]any{"code": code, "msg": msg})+ })+}++// stubSend installs the IM-send endpoint. resp is the response body+// (typically the standard {code, msg, data:{message_id}} shape).+func (f *larkFakeServer) stubSend(resp map[string]any, verify func(r *http.Request, body map[string]string)) {+ f.mux.HandleFunc("/open-apis/im/v1/messages", func(w http.ResponseWriter, r *http.Request) {+ f.sendN.Add(1)+ if r.Method != http.MethodPost {+ f.t.Errorf("send: want POST, got %s", r.Method)+ }+ var body map[string]string+ if err := json.NewDecoder(r.Body).Decode(&body); err != nil {+ f.t.Errorf("send: decode body: %v", err)+ }+ if verify != nil {+ verify(r, body)+ }+ writeJSON(w, resp)+ })+}++// stubPatch installs the IM-patch endpoint. The Lark route is+// /open-apis/im/v1/messages/<id>; ServeMux uses prefix matching when+// we register the parent path explicitly. We register the parent+// SEND path above already, so the patch path needs the full prefix.+func (f *larkFakeServer) stubPatch(resp map[string]any, verify func(r *http.Request, id string, body map[string]string)) {+ const prefix = "/open-apis/im/v1/messages/"+ f.mux.HandleFunc(prefix, func(w http.ResponseWriter, r *http.Request) {+ if r.Method != http.MethodPatch {+ f.t.Errorf("patch: want PATCH, got %s", r.Method)+ }+ id := strings.TrimPrefix(r.URL.Path, prefix)+ if id == "" {+ f.t.Errorf("patch: missing message id")+ }+ f.patchN.Add(1)+ var body map[string]string+ if err := json.NewDecoder(r.Body).Decode(&body); err != nil {+ f.t.Errorf("patch: decode body: %v", err)+ }+ if verify != nil {+ verify(r, id, body)+ }+ writeJSON(w, resp)+ })+}++func writeJSON(w http.ResponseWriter, body any) {+ w.Header().Set("Content-Type", "application/json")+ _ = json.NewEncoder(w).Encode(body)+}++// newTestClient returns an httpAPIClient pointed at the fake server,+// using the supplied clock so token expiry can be controlled+// deterministically.+func newTestClient(fake *larkFakeServer, now func() time.Time) *httpAPIClient {+ c := NewHTTPAPIClient(HTTPClientConfig{+ BaseURL: fake.URL(),+ Now: now,+ }).(*httpAPIClient)+ return c+}++func testCreds() InstallationCredentials {+ return InstallationCredentials{AppID: "cli_app_xx", AppSecret: "secret_xx"}+}++func TestHTTPClient_IsConfigured(t *testing.T) {+ c := NewHTTPAPIClient(HTTPClientConfig{})+ if !c.IsConfigured() {+ t.Fatalf("real client must report IsConfigured()=true")+ }+}++// TestHTTPClient_StubReportsNotConfigured pins that the stub never+// claims wired outbound — handlers gate install / management UI on+// this signal.+func TestHTTPClient_StubReportsNotConfigured(t *testing.T) {+ s := NewStubAPIClient(nil)+ if s.IsConfigured() {+ t.Errorf("stub IsConfigured must be false")+ }+}++// TestHTTPClient_SendInteractiveCard_DefaultRendererBodyHasUpdateMulti+// is the send-side half of the must-fix wire check: when the Patcher+// uses NewDefaultRenderer to produce a card and ships it via+// SendInteractiveCard, the actual HTTP body Lark receives must carry+// config.update_multi=true so the card is patchable downstream.+// Without this, the first send succeeds but every subsequent patch+// silently no-ops on Lark's side while local DB status still flips.+func TestHTTPClient_SendInteractiveCard_DefaultRendererBodyHasUpdateMulti(t *testing.T) {+ fake := newLarkFake(t)+ fake.stubToken("tok_um_send", 7200)+ var capturedContent string+ fake.stubSend(+ map[string]any{"code": 0, "data": map[string]string{"message_id": "om_send_um"}},+ func(_ *http.Request, body map[string]string) {+ capturedContent = body["content"]+ },+ )++ r := NewDefaultRenderer()+ render, err := r.Render(RenderInput{Kind: CardKindThinking, AgentName: "TestAgent"})+ if err != nil {+ t.Fatalf("render: %v", err)+ }++ c := newTestClient(fake, time.Now)+ if _, err := c.SendInteractiveCard(context.Background(), SendCardParams{+ InstallationID: testCreds(),+ ChatID: ChatID("oc_send_um"),+ CardJSON: render.JSON,+ }); err != nil {+ t.Fatalf("send: %v", err)+ }++ assertCardContentHasUpdateMulti(t, capturedContent)+}++// TestHTTPClient_PatchInteractiveCard_DefaultRendererBodyHasUpdateMulti+// is the patch-side half of the same wire check. Every PatchCardParams+// the Patcher produces goes through the default renderer; the body+// shipped over PATCH /open-apis/im/v1/messages/:id must still carry+// update_multi=true, otherwise Lark refuses to apply the patch to a+// card that was sent with update_multi=true (the two ends must agree).+func TestHTTPClient_PatchInteractiveCard_DefaultRendererBodyHasUpdateMulti(t *testing.T) {+ fake := newLarkFake(t)+ fake.stubToken("tok_um_patch", 7200)+ var capturedContent string+ fake.stubPatch(+ map[string]any{"code": 0, "msg": "ok"},+ func(_ *http.Request, _ string, body map[string]string) {+ capturedContent = body["content"]+ },+ )++ r := NewDefaultRenderer()+ render, err := r.Render(RenderInput{Kind: CardKindRunning, AgentName: "TestAgent"})+ if err != nil {+ t.Fatalf("render: %v", err)+ }++ c := newTestClient(fake, time.Now)+ if err := c.PatchInteractiveCard(context.Background(), PatchCardParams{+ InstallationID: testCreds(),+ LarkCardMessageID: "om_patch_um",+ CardJSON: render.JSON,+ }); err != nil {+ t.Fatalf("patch: %v", err)+ }++ assertCardContentHasUpdateMulti(t, capturedContent)+}++func assertCardContentHasUpdateMulti(t *testing.T, content string) {+ t.Helper()+ if content == "" {+ t.Fatalf("captured content empty — fake server did not receive the request body")+ }+ var doc map[string]any+ if err := json.Unmarshal([]byte(content), &doc); err != nil {+ t.Fatalf("card content is not valid JSON: %v (raw=%s)", err, content)+ }+ cfg, ok := doc["config"].(map[string]any)+ if !ok {+ t.Fatalf("card content missing config block (raw=%s)", content)+ }+ if v, _ := cfg["update_multi"].(bool); !v {+ t.Fatalf("config.update_multi must be true so the card is patchable on Lark's side; got config=%v (raw=%s)", cfg, content)+ }+}++func TestHTTPClient_SendInteractiveCard_HappyPath(t *testing.T) {+ fake := newLarkFake(t)+ fake.stubToken("tok_1", 7200)+ fake.stubSend(+ map[string]any{+ "code": 0,+ "msg": "ok",+ "data": map[string]string{"message_id": "om_msg_42"},+ },+ func(r *http.Request, body map[string]string) {+ if got := r.URL.Query().Get("receive_id_type"); got != "chat_id" {+ t.Errorf("receive_id_type: got %q want chat_id", got)+ }+ if body["receive_id"] != "oc_chat_1" {+ t.Errorf("receive_id: got %q", body["receive_id"])+ }+ if body["msg_type"] != "interactive" {+ t.Errorf("msg_type: got %q want interactive", body["msg_type"])+ }+ if !strings.Contains(body["content"], "\"tag\"") {+ t.Errorf("content not a card body: %q", body["content"])+ }+ },+ )++ c := newTestClient(fake, time.Now)+ msgID, err := c.SendInteractiveCard(context.Background(), SendCardParams{+ InstallationID: testCreds(),+ ChatID: ChatID("oc_chat_1"),+ CardJSON: `{"tag":"div","text":"hi"}`,+ })+ if err != nil {+ t.Fatalf("send: %v", err)+ }+ if msgID != "om_msg_42" {+ t.Errorf("message id: got %q want om_msg_42", msgID)+ }+ if got := fake.lastAuth(); got != "Bearer tok_1" {+ t.Errorf("Authorization header: got %q want Bearer tok_1", got)+ }+}++// TestHTTPClient_SendTextMessage_HappyPath pins the wire shape of the+// plain text outbound used for chat replies + /issue confirmations.+// Path, query, bearer auth, msg_type, and the double-JSON-encoded+// `content` envelope all matter — Lark rejects anything off-spec and+// the failures are silent-but-non-2xx, which is hard to debug+// in production without this kind of contract pin.+func TestHTTPClient_SendTextMessage_HappyPath(t *testing.T) {+ fake := newLarkFake(t)+ fake.stubToken("tok_text", 7200)+ fake.stubSend(+ map[string]any{+ "code": 0,+ "msg": "ok",+ "data": map[string]string{"message_id": "om_text_1"},+ },+ func(r *http.Request, body map[string]string) {+ if r.URL.Path != "/open-apis/im/v1/messages" {+ t.Errorf("path: got %q want /open-apis/im/v1/messages", r.URL.Path)+ }+ if got := r.URL.Query().Get("receive_id_type"); got != "chat_id" {+ t.Errorf("receive_id_type: got %q want chat_id", got)+ }+ if body["receive_id"] != "oc_chat_42" {+ t.Errorf("receive_id: got %q want oc_chat_42", body["receive_id"])+ }+ if body["msg_type"] != "text" {+ t.Errorf("msg_type: got %q want text (NOT interactive — chat replies are plain bubbles)", body["msg_type"])+ }+ // content is a JSON-encoded string Lark requires: the outer+ // HTTP body is JSON, and `content` is another JSON+ // document INSIDE it. Decode and inspect.+ var inner map[string]string+ if err := json.Unmarshal([]byte(body["content"]), &inner); err != nil {+ t.Fatalf("content is not valid inner JSON: %v (raw=%q)", err, body["content"])+ }+ if inner["text"] != "Hello world" {+ t.Errorf("inner content.text: got %q want Hello world", inner["text"])+ }+ },+ )++ c := newTestClient(fake, time.Now)+ msgID, err := c.SendTextMessage(context.Background(), SendTextParams{+ InstallationID: testCreds(),+ ChatID: ChatID("oc_chat_42"),+ Text: "Hello world",+ })+ if err != nil {+ t.Fatalf("send: %v", err)+ }+ if msgID != "om_text_1" {+ t.Errorf("message id: got %q want om_text_1", msgID)+ }+ if got := fake.lastAuth(); got != "Bearer tok_text" {+ t.Errorf("Authorization header: got %q want Bearer tok_text", got)+ }+}++// TestHTTPClient_SendMarkdownCard_HappyPath pins the wire shape of the+// schema-2.0 card we send for markdown chat replies. The MUST-haves:+// msg_type=interactive (not text), content is a JSON-encoded card+// envelope, the card has `schema: "2.0"` at the top level, and the+// body element is `{tag: "markdown", content: <agent's md verbatim>}`.+// Lark rejects malformed cards with a generic 9499xxxx code that's+// painful to root-cause in production, so we contract-pin every level.+func TestHTTPClient_SendMarkdownCard_HappyPath(t *testing.T) {+ fake := newLarkFake(t)+ fake.stubToken("tok_md", 7200)+ fake.stubSend(+ map[string]any{+ "code": 0,+ "msg": "ok",+ "data": map[string]string{"message_id": "om_md_1"},+ },+ func(r *http.Request, body map[string]string) {+ if r.URL.Path != "/open-apis/im/v1/messages" {+ t.Errorf("path: got %q want /open-apis/im/v1/messages", r.URL.Path)+ }+ if got := r.URL.Query().Get("receive_id_type"); got != "chat_id" {+ t.Errorf("receive_id_type: got %q want chat_id", got)+ }+ if body["msg_type"] != "interactive" {+ t.Errorf("msg_type: got %q want interactive (markdown cards ride the interactive endpoint)", body["msg_type"])+ }+ var card map[string]any+ if err := json.Unmarshal([]byte(body["content"]), &card); err != nil {+ t.Fatalf("content is not valid card JSON: %v (raw=%q)", err, body["content"])+ }+ if card["schema"] != "2.0" {+ t.Errorf("card.schema: got %v want \"2.0\"", card["schema"])+ }+ bodyDoc, _ := card["body"].(map[string]any)+ elements, _ := bodyDoc["elements"].([]any)+ if len(elements) != 1 {+ t.Fatalf("expected exactly one body element; got %d", len(elements))+ }+ el, _ := elements[0].(map[string]any)+ if el["tag"] != "markdown" {+ t.Errorf("element.tag: got %v want \"markdown\"", el["tag"])+ }+ if el["content"] != "# Heading\n- list" {+ t.Errorf("markdown body must be forwarded verbatim; got %q", el["content"])+ }+ },+ )++ c := newTestClient(fake, time.Now)+ msgID, err := c.SendMarkdownCard(context.Background(), SendMarkdownCardParams{+ InstallationID: testCreds(),+ ChatID: ChatID("oc_chat_42"),+ Markdown: "# Heading\n- list",+ })+ if err != nil {+ t.Fatalf("send markdown card: %v", err)+ }+ if msgID != "om_md_1" {+ t.Errorf("message id: got %q want om_md_1", msgID)+ }+ if got := fake.lastAuth(); got != "Bearer tok_md" {+ t.Errorf("Authorization header: got %q want Bearer tok_md", got)+ }+}++// TestHTTPClient_SendTextMessage_EncodesSpecialCharacters guards the+// inner JSON envelope's escaping. Lark's spec is "content MUST be a+// JSON-encoded string", which means newlines and quotes have to be+// double-escaped — once when we marshal the inner `{"text": ...}`,+// then once more implicitly when the outer body is encoded for the+// HTTP request. Forgetting either pass corrupts the text Lark renders+// (or worse, rejects the message with a body parse error).+func TestHTTPClient_SendTextMessage_EncodesSpecialCharacters(t *testing.T) {+ cases := []struct {+ name string+ text string+ }{+ {"multiline", "first line\nsecond line"},+ {"double_quote", `she said "hi"`},+ {"backslash", `path\to\file`},+ {"chinese", "你好,世界 🌏"},+ {"tab_and_newline", "col1\tcol2\nrow2"},+ {"json_lookalike", `{"fake": "json"}`},+ }+ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ fake := newLarkFake(t)+ fake.stubToken("tok", 7200)+ fake.stubSend(+ map[string]any{"code": 0, "data": map[string]string{"message_id": "om_x"}},+ func(r *http.Request, body map[string]string) {+ var inner map[string]string+ if err := json.Unmarshal([]byte(body["content"]), &inner); err != nil {+ t.Fatalf("content envelope not valid JSON after wire-encode round trip: %v (raw=%q)", err, body["content"])+ }+ if inner["text"] != tc.text {+ t.Errorf("text round-trip failed\n got: %q\n want: %q", inner["text"], tc.text)+ }+ },+ )+ c := newTestClient(fake, time.Now)+ if _, err := c.SendTextMessage(context.Background(), SendTextParams{+ InstallationID: testCreds(),+ ChatID: ChatID("oc_chat_1"),+ Text: tc.text,+ }); err != nil {+ t.Fatalf("send: %v", err)+ }+ })+ }+}++// TestHTTPClient_SendTextMessage_LarkErrorCode pins the failure path:+// non-zero `code` becomes a wrapped error; a missing message_id even+// with code=0 is still treated as failure (matches the success-card+// path so callers don't have to special-case the response shapes).+func TestHTTPClient_SendTextMessage_LarkErrorCode(t *testing.T) {+ fake := newLarkFake(t)+ fake.stubToken("tok", 7200)+ fake.stubSend(+ map[string]any{+ "code": 234567,+ "msg": "Permission denied",+ },+ nil,+ )+ c := newTestClient(fake, time.Now)+ _, err := c.SendTextMessage(context.Background(), SendTextParams{+ InstallationID: testCreds(),+ ChatID: ChatID("oc"),+ Text: "hi",+ })+ if err == nil {+ t.Fatal("expected error on non-zero Lark code")+ }+ if !strings.Contains(err.Error(), "234567") {+ t.Errorf("error should surface the Lark code; got %v", err)+ }+}++func TestHTTPClient_SendInteractiveCard_TokenCached(t *testing.T) {+ fake := newLarkFake(t)+ fake.stubToken("tok_cached", 7200)+ fake.stubSend(+ map[string]any{+ "code": 0,+ "data": map[string]string{"message_id": "om_msg_x"},+ },+ nil,+ )+ c := newTestClient(fake, time.Now)+ for i := 0; i < 3; i++ {+ if _, err := c.SendInteractiveCard(context.Background(), SendCardParams{+ InstallationID: testCreds(),+ ChatID: ChatID("oc_chat_1"),+ CardJSON: `{}`,+ }); err != nil {+ t.Fatalf("iter %d: %v", i, err)+ }+ }+ if got := fake.tokenN.Load(); got != 1 {+ t.Errorf("token endpoint hits: got %d want 1 (cached after first call)", got)+ }+ if got := fake.sendN.Load(); got != 3 {+ t.Errorf("send endpoint hits: got %d want 3", got)+ }+}++func TestHTTPClient_TokenRefreshAfterExpiry(t *testing.T) {+ fake := newLarkFake(t)+ fake.stubToken("tok_refresh", 120) // 120s expire → 60s usable after safety margin+ fake.stubSend(+ map[string]any{+ "code": 0,+ "data": map[string]string{"message_id": "om"},+ },+ nil,+ )++ now := time.Unix(1_700_000_000, 0)+ clock := &fakeClock{now: now}+ c := NewHTTPAPIClient(HTTPClientConfig{BaseURL: fake.URL(), Now: clock.Now}).(*httpAPIClient)++ // First call — fetches token.+ if _, err := c.SendInteractiveCard(context.Background(), SendCardParams{+ InstallationID: testCreds(),+ ChatID: ChatID("oc"),+ CardJSON: `{}`,+ }); err != nil {+ t.Fatalf("first send: %v", err)+ }+ if fake.tokenN.Load() != 1 {+ t.Fatalf("first call should have fetched a token, got tokenN=%d", fake.tokenN.Load())+ }++ // Advance past the cached token's expiry (token expire 120s,+ // safety margin 60s → cache valid for 60s of wall-clock).+ clock.Advance(90 * time.Second)++ if _, err := c.SendInteractiveCard(context.Background(), SendCardParams{+ InstallationID: testCreds(),+ ChatID: ChatID("oc"),+ CardJSON: `{}`,+ }); err != nil {+ t.Fatalf("post-expiry send: %v", err)+ }+ if got := fake.tokenN.Load(); got != 2 {+ t.Errorf("token endpoint hits after expiry: got %d want 2", got)+ }+}++func TestHTTPClient_SendInteractiveCard_LarkErrorCode(t *testing.T) {+ fake := newLarkFake(t)+ fake.stubToken("tok_e", 7200)+ fake.stubSend(map[string]any{"code": 230001, "msg": "no permission"}, nil)+ c := newTestClient(fake, time.Now)+ _, err := c.SendInteractiveCard(context.Background(), SendCardParams{+ InstallationID: testCreds(),+ ChatID: ChatID("oc"),+ CardJSON: `{}`,+ })+ if err == nil {+ t.Fatal("want error on non-zero code")+ }+ if !strings.Contains(err.Error(), "code=230001") {+ t.Errorf("error should surface code: %v", err)+ }+}++func TestHTTPClient_SendInteractiveCard_TokenExpired_InvalidatesCache(t *testing.T) {+ fake := newLarkFake(t)+ fake.stubToken("tok_first", 7200)+ // First send replies with expired-token. Second send (after the+ // client should have dropped its cache) reaches the token+ // endpoint again. We swap the send handler mid-test to model+ // this without race conditions: send fails first, second call+ // from the same fake gets the token-endpoint hit + a fresh send+ // reply. To keep the test small we simply assert tokenN+ // increments after the failing call when the caller retries.+ var sendCalls atomic.Int32+ fake.mux.HandleFunc("/open-apis/im/v1/messages", func(w http.ResponseWriter, r *http.Request) {+ fake.sendN.Add(1)+ n := sendCalls.Add(1)+ if n == 1 {+ writeJSON(w, map[string]any{"code": codeTokenExpired, "msg": "expired"})+ return+ }+ writeJSON(w, map[string]any{"code": 0, "data": map[string]string{"message_id": "om_ok"}})+ })++ c := newTestClient(fake, time.Now)+ _, err := c.SendInteractiveCard(context.Background(), SendCardParams{+ InstallationID: testCreds(),+ ChatID: ChatID("oc"),+ CardJSON: `{}`,+ })+ if err == nil {+ t.Fatal("first send must fail with token-expired")+ }+ if !strings.Contains(err.Error(), "code=99991663") {+ t.Errorf("error should mention token-expired code: %v", err)+ }++ // Caller's retry — should re-fetch the token, then succeed.+ msgID, err := c.SendInteractiveCard(context.Background(), SendCardParams{+ InstallationID: testCreds(),+ ChatID: ChatID("oc"),+ CardJSON: `{}`,+ })+ if err != nil {+ t.Fatalf("retry send: %v", err)+ }+ if msgID != "om_ok" {+ t.Errorf("retry message id: got %q", msgID)+ }+ if got := fake.tokenN.Load(); got != 2 {+ t.Errorf("token endpoint hits after invalidation: got %d want 2", got)+ }+}++func TestHTTPClient_PatchInteractiveCard_HappyPath(t *testing.T) {+ fake := newLarkFake(t)+ fake.stubToken("tok_p", 7200)+ fake.stubPatch(+ map[string]any{"code": 0, "msg": "ok"},+ func(r *http.Request, id string, body map[string]string) {+ if id != "om_msg_42" {+ t.Errorf("patch id: got %q want om_msg_42", id)+ }+ if !strings.Contains(body["content"], "updated") {+ t.Errorf("patch content: %q", body["content"])+ }+ },+ )+ c := newTestClient(fake, time.Now)+ if err := c.PatchInteractiveCard(context.Background(), PatchCardParams{+ InstallationID: testCreds(),+ LarkCardMessageID: "om_msg_42",+ CardJSON: `{"text":"updated"}`,+ }); err != nil {+ t.Fatalf("patch: %v", err)+ }+}++func TestHTTPClient_PatchInteractiveCard_LarkErrorCode(t *testing.T) {+ fake := newLarkFake(t)+ fake.stubToken("tok_p", 7200)+ fake.stubPatch(map[string]any{"code": 230002, "msg": "card not found"}, nil)+ c := newTestClient(fake, time.Now)+ err := c.PatchInteractiveCard(context.Background(), PatchCardParams{+ InstallationID: testCreds(),+ LarkCardMessageID: "om_msg_x",+ CardJSON: `{}`,+ })+ if err == nil || !strings.Contains(err.Error(), "code=230002") {+ t.Errorf("want code=230002 in error, got %v", err)+ }+}++func TestHTTPClient_SendBindingPromptCard_HappyPath(t *testing.T) {+ fake := newLarkFake(t)+ fake.stubToken("tok_b", 7200)++ var capturedBody map[string]string+ fake.mux.HandleFunc("/open-apis/im/v1/messages", func(w http.ResponseWriter, r *http.Request) {+ fake.bindN.Add(1)+ _ = json.NewDecoder(r.Body).Decode(&capturedBody)+ if got := r.URL.Query().Get("receive_id_type"); got != "open_id" {+ t.Errorf("receive_id_type: got %q want open_id", got)+ }+ writeJSON(w, map[string]any{"code": 0, "data": map[string]string{"message_id": "om_bind"}})+ })++ c := newTestClient(fake, time.Now)+ if err := c.SendBindingPromptCard(context.Background(), BindingPromptParams{+ InstallationID: testCreds(),+ OpenID: OpenID("ou_user_1"),+ BindURL: "https://multica.test/lark/bind?token=abc",+ }); err != nil {+ t.Fatalf("bind prompt: %v", err)+ }+ if capturedBody["receive_id"] != "ou_user_1" {+ t.Errorf("receive_id: got %q", capturedBody["receive_id"])+ }+ if !strings.Contains(capturedBody["content"], "multica.test/lark/bind") {+ t.Errorf("binding card should embed BindURL: %q", capturedBody["content"])+ }+ if !strings.Contains(capturedBody["content"], "去绑定") {+ t.Errorf("binding card should carry the localized CTA: %q", capturedBody["content"])+ }+}++func TestHTTPClient_TokenEndpointError(t *testing.T) {+ fake := newLarkFake(t)+ fake.stubTokenError(10003, "invalid app_id or app_secret")+ c := newTestClient(fake, time.Now)+ _, err := c.SendInteractiveCard(context.Background(), SendCardParams{+ InstallationID: testCreds(),+ ChatID: ChatID("oc"),+ CardJSON: `{}`,+ })+ if err == nil || !strings.Contains(err.Error(), "code=10003") {+ t.Errorf("want code=10003 surfaced, got %v", err)+ }+}++func TestHTTPClient_MissingAppCredentials(t *testing.T) {+ c := NewHTTPAPIClient(HTTPClientConfig{}).(*httpAPIClient)+ _, err := c.tenantAccessToken(context.Background(), InstallationCredentials{AppSecret: "x"})+ if err == nil || !strings.Contains(err.Error(), "app_id") {+ t.Errorf("want missing app_id error, got %v", err)+ }+ _, err = c.tenantAccessToken(context.Background(), InstallationCredentials{AppID: "x"})+ if err == nil || !strings.Contains(err.Error(), "app_secret") {+ t.Errorf("want missing app_secret error, got %v", err)+ }+}++func TestHTTPClient_MissingChatID_PreAuth(t *testing.T) {+ // chat_id validation must short-circuit BEFORE any auth round-trip+ // — otherwise a misuse leaks load to the token endpoint.+ fake := newLarkFake(t)+ c := newTestClient(fake, time.Now)+ _, err := c.SendInteractiveCard(context.Background(), SendCardParams{+ InstallationID: testCreds(),+ CardJSON: `{}`,+ })+ if err == nil || !strings.Contains(err.Error(), "chat_id") {+ t.Errorf("want missing chat_id error, got %v", err)+ }+ if got := fake.tokenN.Load(); got != 0 {+ t.Errorf("token endpoint must not be hit on bad input: got %d", got)+ }+}++func TestHTTPClient_MissingCardJSON(t *testing.T) {+ c := NewHTTPAPIClient(HTTPClientConfig{}).(*httpAPIClient)+ if _, err := c.SendInteractiveCard(context.Background(), SendCardParams{+ InstallationID: testCreds(),+ ChatID: ChatID("oc"),+ }); err == nil || !strings.Contains(err.Error(), "card json") {+ t.Errorf("send: want missing card json, got %v", err)+ }+ if err := c.PatchInteractiveCard(context.Background(), PatchCardParams{+ InstallationID: testCreds(),+ LarkCardMessageID: "om",+ }); err == nil || !strings.Contains(err.Error(), "card json") {+ t.Errorf("patch: want missing card json, got %v", err)+ }+}++func TestHTTPClient_PatchMissingID(t *testing.T) {+ c := NewHTTPAPIClient(HTTPClientConfig{}).(*httpAPIClient)+ err := c.PatchInteractiveCard(context.Background(), PatchCardParams{+ InstallationID: testCreds(),+ CardJSON: `{}`,+ })+ if err == nil || !strings.Contains(err.Error(), "card message id") {+ t.Errorf("want missing message id error, got %v", err)+ }+}++func TestHTTPClient_BindingPromptValidation(t *testing.T) {+ c := NewHTTPAPIClient(HTTPClientConfig{}).(*httpAPIClient)+ if err := c.SendBindingPromptCard(context.Background(), BindingPromptParams{+ InstallationID: testCreds(),+ BindURL: "https://x",+ }); err == nil || !strings.Contains(err.Error(), "open_id") {+ t.Errorf("want missing open_id, got %v", err)+ }+ if err := c.SendBindingPromptCard(context.Background(), BindingPromptParams{+ InstallationID: testCreds(),+ OpenID: "ou",+ }); err == nil || !strings.Contains(err.Error(), "bind url") {+ t.Errorf("want missing bind url, got %v", err)+ }+}++// TestHTTPClient_GetBotInfo_HappyPath drives the device-flow follow-up+// step: once RegistrationService has fresh client_id / client_secret+// from /oauth/v1/app/registration, it mints a tenant_access_token and+// asks /open-apis/bot/v3/info for the Bot's per-installation open_id,+// then resolves the bot's union_id via /open-apis/contact/v3/users/+// {open_id}?user_id_type=open_id. Both identifiers are persisted on+// the installation row; the union_id is what the WS decoder uses to+// route inbound @-mentions in multi-bot group chats (MUL-2671). The+// other fields on the bot/v3/info response (display name, avatar,+// IP whitelist) are deliberately dropped on the floor.+func TestHTTPClient_GetBotInfo_HappyPath(t *testing.T) {+ fake := newLarkFake(t)+ fake.stubToken("tok_bi", 7200)+ fake.mux.HandleFunc("/open-apis/bot/v3/info", func(w http.ResponseWriter, r *http.Request) {+ if r.Method != http.MethodGet {+ t.Errorf("bot info: want GET, got %s", r.Method)+ }+ if got := r.Header.Get("Authorization"); got != "Bearer tok_bi" {+ t.Errorf("bot info: Authorization=%q want Bearer tok_bi", got)+ }+ writeJSON(w, map[string]any{+ "code": 0,+ "msg": "ok",+ "bot": map[string]any{+ "open_id": "ou_bot_42",+ "app_name": "PersonalAgent",+ "avatar_url": "https://example/avatar.png",+ },+ })+ })+ fake.mux.HandleFunc("/open-apis/contact/v3/users/ou_bot_42", func(w http.ResponseWriter, r *http.Request) {+ if r.Method != http.MethodGet {+ t.Errorf("contact users: want GET, got %s", r.Method)+ }+ if got := r.URL.Query().Get("user_id_type"); got != "open_id" {+ t.Errorf("contact users: user_id_type=%q want open_id", got)+ }+ if got := r.Header.Get("Authorization"); got != "Bearer tok_bi" {+ t.Errorf("contact users: Authorization=%q want Bearer tok_bi", got)+ }+ writeJSON(w, map[string]any{+ "code": 0,+ "msg": "ok",+ "data": map[string]any{+ "user": map[string]any{+ "union_id": "on_bot_42_stable",+ },+ },+ })+ })++ c := NewHTTPAPIClient(HTTPClientConfig{BaseURL: fake.URL()})+ info, err := c.GetBotInfo(context.Background(), testCreds())+ if err != nil {+ t.Fatalf("GetBotInfo: %v", err)+ }+ if string(info.OpenID) != "ou_bot_42" {+ t.Errorf("OpenID: got %q want ou_bot_42", info.OpenID)+ }+ if info.UnionID != "on_bot_42_stable" {+ t.Errorf("UnionID: got %q want on_bot_42_stable", info.UnionID)+ }+}++// TestHTTPClient_GetBotInfo_UnionIDLookupSoftFails covers the case+// where /contact/v3/users returns a non-zero code (e.g. the app's+// contact scope was never approved). The install must still succeed+// with an empty UnionID so the operator can backfill later instead+// of the QR flow failing outright. The decoder transitional fallback+// keeps single-bot installs working in the gap.+func TestHTTPClient_GetBotInfo_UnionIDLookupSoftFails(t *testing.T) {+ fake := newLarkFake(t)+ fake.stubToken("tok_bi_softfail", 7200)+ fake.mux.HandleFunc("/open-apis/bot/v3/info", func(w http.ResponseWriter, r *http.Request) {+ writeJSON(w, map[string]any{+ "code": 0,+ "msg": "ok",+ "bot": map[string]any{"open_id": "ou_bot_softfail"},+ })+ })+ fake.mux.HandleFunc("/open-apis/contact/v3/users/ou_bot_softfail", func(w http.ResponseWriter, r *http.Request) {+ writeJSON(w, map[string]any{"code": 99991002, "msg": "no permission"})+ })+ c := NewHTTPAPIClient(HTTPClientConfig{BaseURL: fake.URL()})+ info, err := c.GetBotInfo(context.Background(), testCreds())+ if err != nil {+ t.Fatalf("GetBotInfo unexpectedly errored on soft-fail: %v", err)+ }+ if string(info.OpenID) != "ou_bot_softfail" {+ t.Errorf("OpenID: got %q want ou_bot_softfail", info.OpenID)+ }+ if info.UnionID != "" {+ t.Errorf("UnionID: got %q want empty (soft-fail leaves backfill to operator)", info.UnionID)+ }+}++// TestHTTPClient_GetBotInfo_LarkErrorCode surfaces a non-zero Lark+// error code (e.g. 230003 = bot disabled) as a wrapped error so+// RegistrationService can fail the install cleanly instead of+// recording a row with bot_open_id="".+func TestHTTPClient_GetBotInfo_LarkErrorCode(t *testing.T) {+ fake := newLarkFake(t)+ fake.stubToken("tok_bi_err", 7200)+ fake.mux.HandleFunc("/open-apis/bot/v3/info", func(w http.ResponseWriter, r *http.Request) {+ writeJSON(w, map[string]any{"code": 230003, "msg": "bot disabled"})+ })+ c := NewHTTPAPIClient(HTTPClientConfig{BaseURL: fake.URL()})+ _, err := c.GetBotInfo(context.Background(), testCreds())+ if err == nil || !strings.Contains(err.Error(), "code=230003") {+ t.Errorf("want code=230003 surfaced, got %v", err)+ }+}++// TestHTTPClient_GetBotInfo_MissingCredentials short-circuits before+// any HTTP round-trip when the caller hands in zero-value credentials.+// A misuse here should NOT leak load to Lark's token endpoint.+func TestHTTPClient_GetBotInfo_MissingCredentials(t *testing.T) {+ fake := newLarkFake(t)+ c := newTestClient(fake, time.Now)+ if _, err := c.GetBotInfo(context.Background(), InstallationCredentials{}); err == nil ||+ !strings.Contains(err.Error(), "missing app credentials") {+ t.Errorf("want missing credentials error, got %v", err)+ }+ if got := fake.tokenN.Load(); got != 0 {+ t.Errorf("token endpoint must not be hit on bad input: got %d", got)+ }+}++func TestHTTPClient_BadHTTPStatus(t *testing.T) {+ fake := newLarkFake(t)+ // Token returns success.+ fake.stubToken("tok", 7200)+ // Send replies with 500 + body — exercise the non-2xx branch.+ fake.mux.HandleFunc("/open-apis/im/v1/messages", func(w http.ResponseWriter, r *http.Request) {+ fake.sendN.Add(1)+ w.WriteHeader(500)+ _, _ = io.WriteString(w, "boom")+ })+ c := newTestClient(fake, time.Now)+ _, err := c.SendInteractiveCard(context.Background(), SendCardParams{+ InstallationID: testCreds(),+ ChatID: ChatID("oc"),+ CardJSON: `{}`,+ })+ if err == nil || !strings.Contains(err.Error(), "http 500") {+ t.Errorf("want http 500 surfaced, got %v", err)+ }+}++func TestHTTPClient_TokenExpire_ClampedToSafety(t *testing.T) {+ // Lark returns expire=10s — well under the safety margin. The+ // client must NOT cache a token that is already past its safe+ // window; instead it clamps to 2× safety margin so the cached+ // entry is at least usable for one safety margin of wall-clock.+ fake := newLarkFake(t)+ fake.stubToken("tok_short", 10)+ fake.stubSend(map[string]any{"code": 0, "data": map[string]string{"message_id": "om"}}, nil)++ now := time.Unix(1_700_000_000, 0)+ clock := &fakeClock{now: now}+ c := NewHTTPAPIClient(HTTPClientConfig{BaseURL: fake.URL(), Now: clock.Now}).(*httpAPIClient)++ if _, err := c.SendInteractiveCard(context.Background(), SendCardParams{+ InstallationID: testCreds(),+ ChatID: ChatID("oc"),+ CardJSON: `{}`,+ }); err != nil {+ t.Fatalf("send: %v", err)+ }+ clock.Advance(30 * time.Second) // still within clamped window+ if _, err := c.SendInteractiveCard(context.Background(), SendCardParams{+ InstallationID: testCreds(),+ ChatID: ChatID("oc"),+ CardJSON: `{}`,+ }); err != nil {+ t.Fatalf("send2: %v", err)+ }+ if got := fake.tokenN.Load(); got != 1 {+ t.Errorf("token endpoint hits within clamped window: got %d want 1", got)+ }+}++func TestBindingPromptTemplate_Shape(t *testing.T) {+ raw, err := bindingPromptTemplate("https://multica.test/bind?token=abc")+ if err != nil {+ t.Fatalf("template: %v", err)+ }+ var doc map[string]any+ if err := json.Unmarshal([]byte(raw), &doc); err != nil {+ t.Fatalf("template json: %v", err)+ }+ // Shape check — top-level keys exist and elements is non-empty.+ if _, ok := doc["config"]; !ok {+ t.Errorf("missing config")+ }+ if _, ok := doc["header"]; !ok {+ t.Errorf("missing header")+ }+ elements, ok := doc["elements"].([]any)+ if !ok || len(elements) < 2 {+ t.Fatalf("elements: want >=2, got %v", doc["elements"])+ }+ // Last element should be the action button carrying the URL.+ last, _ := elements[len(elements)-1].(map[string]any)+ if last["tag"] != "action" {+ t.Errorf("last element should be action: %v", last)+ }+ actions, _ := last["actions"].([]any)+ if len(actions) == 0 {+ t.Fatalf("no actions in card")+ }+ btn, _ := actions[0].(map[string]any)+ if btn["url"] != "https://multica.test/bind?token=abc" {+ t.Errorf("button url: got %v", btn["url"])+ }+}++// fakeClock is a minimal monotonic clock for tests that need to drive+// the cache TTL deterministically.+type fakeClock struct{ now time.Time }++func (c *fakeClock) Now() time.Time { return c.now }+func (c *fakeClock) Advance(d time.Duration) { c.now = c.now.Add(d) }diff --git a/server/internal/integrations/lark/hub.go b/server/internal/integrations/lark/hub.gonew file mode 100644index 0000000000..7250070776--- /dev/null+++ b/server/internal/integrations/lark/hub.go@@ -0,0 +1,894 @@+package lark++import (+ "context"+ cryptorand "crypto/rand"+ "crypto/sha256"+ "encoding/hex"+ "errors"+ "fmt"+ "log/slog"+ mathrand "math/rand/v2"+ "strconv"+ "sync"+ "time"++ "github.com/jackc/pgx/v5/pgtype"+ "github.com/multica-ai/multica/server/internal/util"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++// HubQueries is the narrow subset of *db.Queries the Hub needs for+// installation enumeration and lease management. *db.Queries satisfies+// it directly; tests substitute a fake.+type HubQueries interface {+ ListActiveLarkInstallations(ctx context.Context) ([]db.LarkInstallation, error)+ AcquireLarkWSLease(ctx context.Context, arg db.AcquireLarkWSLeaseParams) (db.LarkInstallation, error)+ ReleaseLarkWSLease(ctx context.Context, arg db.ReleaseLarkWSLeaseParams) error+}++// EventEmitter is the per-message callback the Hub hands to an+// EventConnector. Calling it dispatches the normalized inbound+// message and returns the typed outcome plus any infrastructure+// error from the Dispatcher.+//+// Connectors react to the return value to decide what to do on the+// Lark side:+//+// - A non-nil error is a real infrastructure failure (DB down,+// etc.) — the connector should reconnect (the Hub will retry+// under backoff) and surface the error to ops, NOT swallow it.+// - A nil error with OutcomeNeedsBinding tells the connector to+// send the binding-prompt card to the sender's open_id.+// - OutcomeAgentOffline / OutcomeAgentArchived tell the connector+// to send the respective copy as a Lark card; the chat_message+// row is already persisted, so the agent will pick the message+// up on resume.+// - OutcomeIngested means the message landed and (optionally) a+// task was enqueued; the connector emits a "thinking…" card and+// lets the outbound Patcher take over from there.+// - OutcomeDropped is informational only (the message was filtered+// for a legitimate reason); typical connectors do nothing.+//+// The Dispatcher's invariants (identity check, dedup, audit) are NOT+// the connector's concern — the connector only sees the verdict.+type EventEmitter func(ctx context.Context, msg InboundMessage) (DispatchResult, error)++// EventConnector is the per-installation transport. The Hub owns the+// lifecycle (when to start, when to stop, when to back off), and the+// connector owns the actual wire protocol — opening the Lark long+// connection, decoding events, normalizing them into InboundMessage.+//+// Run MUST block until either:+// - the ctx is cancelled (graceful shutdown / lease loss / revoke),+// in which case it returns nil; or+// - the connection ends and cannot be recovered locally, in which+// case it returns an error describing why. The Hub treats a+// non-nil return as "this attempt failed" and schedules a retry+// under exponential backoff.+//+// Implementations MUST be tolerant of repeated Run calls on different+// contexts — the Hub may call Run, return, and call Run again after+// backoff. Allocating per-call state is fine; persistent state lives in+// the connector struct.+//+// emit returns the Dispatcher's verdict + any infra error so the+// connector can post the corresponding Lark-side reply (binding card,+// offline card, etc.) and / or decide to disconnect on a hard failure.+// The connector MUST NOT bypass the Dispatcher by writing to the DB+// directly; emit is the only ingress path.+type EventConnector interface {+ Run(ctx context.Context, inst db.LarkInstallation, emit EventEmitter) error+}++// ConnectorFactory builds an EventConnector for a specific installation+// row. The factory exists so the Hub doesn't need to know about Lark+// SDK construction (auth, app credentials decryption) — call sites+// inject a factory configured with their APIClient + secretbox box.+type ConnectorFactory func(inst db.LarkInstallation) (EventConnector, error)++// HubConfig tunes the Hub's lifecycle loops. All fields have sensible+// production defaults via withDefaults; tests typically set Now and+// Logger to inject determinism.+type HubConfig struct {+ // LeaseTTL is how long a successful AcquireLarkWSLease grant is+ // valid before another server replica may steal it. Renewals+ // happen on a tighter interval (LeaseRenewInterval); the gap+ // between renew and TTL absorbs transient DB blips.+ LeaseTTL time.Duration++ // LeaseRenewInterval is the cadence at which the Hub re-acquires+ // the lease on connections it already owns. MUST be substantially+ // less than LeaseTTL so a single missed renewal does not yield+ // the lease.+ LeaseRenewInterval time.Duration++ // PollInterval is how often the Hub scans for new installations+ // (or ones whose lease has expired on another replica) to take+ // over.+ PollInterval time.Duration++ // MinBackoff / MaxBackoff bound the per-installation reconnect+ // schedule. The actual delay starts at MinBackoff, doubles after+ // each consecutive failure (capped at MaxBackoff), and resets on+ // any successful Run that lives at least ResetBackoffAfter.+ MinBackoff time.Duration+ MaxBackoff time.Duration+ ResetBackoffAfter time.Duration++ // LeaseReleaseTimeout caps how long a single ReleaseLarkWSLease+ // call may block. The release runs on a fresh context (not the+ // parent supervisor ctx, which is already cancelled by the time+ // we release on shutdown), so without an explicit deadline a+ // stalled DB pool could hang shutdown indefinitely. A bounded+ // timeout means a hung release falls back to the natural lease+ // TTL expiry on the next replica — slower than a clean release,+ // but still bounded.+ LeaseReleaseTimeout time.Duration++ // ShutdownTimeout bounds how long Hub.Wait blocks waiting for+ // supervisor goroutines to exit after their parent ctx is+ // cancelled. Hub.Wait itself does not enforce this — callers+ // pass it to WaitWithTimeout. Exposed on the config so main.go+ // and tests share the same default.+ ShutdownTimeout time.Duration++ // ReplyTimeout caps an OutcomeReplier.Reply call. The replier+ // runs in a detached goroutine off the ACK critical path —+ // dispatch returns the verdict to the connector immediately so+ // the ACK can be written, then the reply (a NeedsBinding card,+ // an offline notice, etc.) is best-effort under this deadline.+ // Lark's long-conn server expects a frame ACK within 3 seconds,+ // so this MUST stay strictly under 3s to keep the connector's+ // own ACK path comfortably bounded even if the dispatch itself+ // takes a few hundred ms (DB roundtrips, identity checks, etc.).+ // Zero defaults to 2.5s.+ ReplyTimeout time.Duration++ // Now returns the current time. Injected for tests; production+ // uses time.Now.+ Now func() time.Time++ // Logger optional; defaults to slog.Default.+ Logger *slog.Logger+}++func (c HubConfig) withDefaults() HubConfig {+ if c.LeaseTTL == 0 {+ c.LeaseTTL = 90 * time.Second+ }+ if c.LeaseRenewInterval == 0 {+ c.LeaseRenewInterval = 30 * time.Second+ }+ if c.PollInterval == 0 {+ c.PollInterval = 30 * time.Second+ }+ if c.MinBackoff == 0 {+ c.MinBackoff = 2 * time.Second+ }+ if c.MaxBackoff == 0 {+ c.MaxBackoff = 60 * time.Second+ }+ if c.ResetBackoffAfter == 0 {+ c.ResetBackoffAfter = 60 * time.Second+ }+ if c.LeaseReleaseTimeout == 0 {+ c.LeaseReleaseTimeout = 5 * time.Second+ }+ if c.ShutdownTimeout == 0 {+ c.ShutdownTimeout = 15 * time.Second+ }+ if c.ReplyTimeout == 0 {+ c.ReplyTimeout = 2500 * time.Millisecond+ }+ if c.Now == nil {+ c.Now = time.Now+ }+ if c.Logger == nil {+ c.Logger = slog.Default()+ }+ return c+}++// Hub owns the per-installation supervisor goroutines that keep a+// long-running Lark connection per active installation. It enforces+// the §4.4 multi-replica safety rule via the WS lease CAS — at most+// one Hub instance globally holds the lease for any installation, so+// duplicate event consumption across replicas is impossible.+//+// Lifecycle:+//+// hub := NewHub(queries, factory, dispatcher, HubConfig{})+// go hub.Run(ctx) // returns when ctx is cancelled+// ... ctx cancellation triggers ...+// hub.Wait() // joins on every per-installation goroutine+type Hub struct {+ queries HubQueries+ factory ConnectorFactory+ dispatcher *Dispatcher+ replier OutcomeReplier+ cfg HubConfig++ // nodeID is the per-process lease ownership token. The CAS+ // predicate on AcquireLarkWSLease treats matching tokens as+ // "this is us, renew" — so as long as nodeID is stable for the+ // Hub's lifetime, lease renewals don't ping-pong between replicas.+ nodeID string++ mu sync.Mutex+ // supervisors keys each in-flight supervisor goroutine by+ // installation_id, alongside a fingerprint of the credentials the+ // connector was started with. When the underlying lark_installation+ // row changes (re-scan creates a fresh bot → new app_id / new+ // encrypted secret), the next sweep detects the fingerprint drift+ // and forces a restart so the new connector picks up fresh+ // credentials. Without this, a stale connector keeps a WS open+ // against the OLD bot's app_id and the new bot silently goes dark.+ supervisors map[string]supervisorEntry+ // supervisorGen is the source of the monotonic gen counter stored+ // on each supervisorEntry. Bumped under mu when a new entry is+ // minted (initial start OR rotation restart).+ supervisorGen uint64+ wg sync.WaitGroup+ stopped bool+ stopChan chan struct{}++ // replyWg tracks in-flight outbound reply goroutines (NeedsBinding+ // card, offline notice, etc.). The replier is detached from the+ // inbound ACK critical path — the connector ACKs as soon as+ // dispatch returns — so reply goroutines may still be running when+ // the supervisor goroutines have already exited. Hub.Wait joins on+ // these too, with each goroutine bounded by ReplyTimeout, so a+ // hung outbound Lark HTTP call cannot block shutdown beyond the+ // timeout.+ replyWg sync.WaitGroup+}++// supervisorEntry is the per-installation state the Hub holds on each+// running supervisor goroutine. cancel terminates the goroutine+// (cascading into connector teardown + lease release); fingerprint is+// the credentials snapshot the connector was launched with, used by+// sweep to detect mid-life rotation (re-scan replaces the bot's+// app_id / app_secret) and force a restart; gen is a monotonic+// counter so the goroutine's deferred cleanup can tell its own entry+// apart from a successor entry that the rotation path already swapped+// in. Without the gen check, the old goroutine's defer would race to+// delete the new entry it knows nothing about.+type supervisorEntry struct {+ cancel context.CancelFunc+ fingerprint string+ gen uint64+}++// NewHub constructs a Hub bound to the supplied queries, connector+// factory and dispatcher. The Hub does not start any goroutines until+// Run is called. The replier (OutcomeReplier) handles the outbound+// side of the EventEmitter contract — NeedsBinding / AgentOffline /+// AgentArchived cards — and is best-effort: failures are logged and+// do not interrupt inbound processing. A nil replier falls back to+// the noop replier so callers that have not wired outbound replies+// yet still get the inbound pipeline running.+func NewHub(queries HubQueries, factory ConnectorFactory, dispatcher *Dispatcher, cfg HubConfig) *Hub {+ cfg = cfg.withDefaults()+ return &Hub{+ queries: queries,+ factory: factory,+ dispatcher: dispatcher,+ replier: NewNoopOutcomeReplier(cfg.Logger),+ cfg: cfg,+ nodeID: newNodeID(),+ supervisors: make(map[string]supervisorEntry),+ stopChan: make(chan struct{}),+ }+}++// SetOutcomeReplier installs the production replier on the Hub. Must+// be called BEFORE Run; setting it afterwards is a data race against+// the supervisor's emit goroutines. Nil resets back to the noop+// replier (useful for tests).+func (h *Hub) SetOutcomeReplier(r OutcomeReplier) {+ if r == nil {+ r = NewNoopOutcomeReplier(h.cfg.Logger)+ }+ h.replier = r+}++// NodeID exposes the per-process lease token. Useful for tests and+// for observability (so operators can correlate DB lease rows to a+// running replica).+func (h *Hub) NodeID() string { return h.nodeID }++// Run is the Hub's main loop. It scans installations every+// PollInterval, attempts to lease any that are not currently being+// supervised by this process, and reaps supervisors for installations+// that have been revoked or whose lease was lost. Returns when ctx is+// cancelled; the caller MUST then call Wait to join all supervisor+// goroutines before exiting.+func (h *Hub) Run(ctx context.Context) {+ defer close(h.stopChan)++ // First sweep immediately so a freshly-restarted server doesn't+ // wait a full PollInterval before picking up its installations.+ h.sweep(ctx)++ t := time.NewTicker(h.cfg.PollInterval)+ defer t.Stop()+ for {+ select {+ case <-ctx.Done():+ h.cancelAll()+ return+ case <-t.C:+ h.sweep(ctx)+ }+ }+}++// Wait blocks until every supervisor goroutine AND every detached+// reply goroutine the Hub started has exited. Call this AFTER+// cancelling Run's context; calling it before returns immediately if+// no goroutines are active.+//+// Prefer WaitWithTimeout in shutdown paths so a stuck supervisor+// (typically a hung lease release on a frozen DB pool) cannot block+// process exit indefinitely. Reply goroutines are independently+// bounded by ReplyTimeout, so even Wait() (unbounded) eventually+// returns once those deadlines elapse.+func (h *Hub) Wait() {+ h.wg.Wait()+ h.replyWg.Wait()+}++// WaitWithTimeout is the bounded variant of Wait. Returns true if all+// supervisor AND reply goroutines exited within the deadline, false if+// the timeout fired first. On timeout, the process owner should log+// the fact and proceed with exit; the orphaned goroutines will be+// reclaimed by the OS, any unreleased leases expire naturally after+// LeaseTTL on the next replica, and in-flight replies abort at their+// own ReplyTimeout (already strictly under 3s, so well under any+// reasonable ShutdownTimeout).+//+// A timeout <= 0 falls back to unbounded Wait, matching the legacy+// behavior.+func (h *Hub) WaitWithTimeout(timeout time.Duration) bool {+ if timeout <= 0 {+ h.Wait()+ return true+ }+ done := make(chan struct{})+ go func() {+ h.Wait()+ close(done)+ }()+ t := time.NewTimer(timeout)+ defer t.Stop()+ select {+ case <-done:+ return true+ case <-t.C:+ return false+ }+}++// ShutdownTimeout exposes the configured graceful-shutdown deadline so+// main.go can use the same value WaitWithTimeout is checked against+// without re-deriving it.+func (h *Hub) ShutdownTimeout() time.Duration { return h.cfg.ShutdownTimeout }++// sweep enumerates currently-active installations and starts a+// supervisor for any that this Hub does not yet supervise. Supervisors+// for revoked installations are cancelled. Supervisors whose+// underlying installation row has rotated credentials (re-scan in the+// device flow creates a fresh app_id / app_secret) are cancelled and+// replaced inline so the new connector picks up the fresh row instead+// of running indefinitely against stale credentials.+func (h *Hub) sweep(ctx context.Context) {+ rows, err := h.queries.ListActiveLarkInstallations(ctx)+ if err != nil {+ h.cfg.Logger.Warn("lark hub: list active installations failed", "error", err)+ return+ }+ active := make(map[string]struct{}, len(rows))+ for _, row := range rows {+ id := uuidString(row.ID)+ active[id] = struct{}{}+ h.maybeRestartOnRotation(id, row)+ h.startSupervisor(ctx, row)+ }+ // Reap supervisors whose installation is no longer active (revoked+ // since the last sweep). The supervisor will exit on the next+ // boundary, release its lease, and the goroutine returns.+ h.mu.Lock()+ for id, entry := range h.supervisors {+ if _, stillActive := active[id]; !stillActive {+ entry.cancel()+ delete(h.supervisors, id)+ }+ }+ h.mu.Unlock()+}++// maybeRestartOnRotation cancels an existing supervisor when its+// credentials fingerprint differs from the current row's. The new+// supervisor is started by the subsequent startSupervisor call within+// the same sweep iteration. We drop the map entry inline so the+// startSupervisor "skip if already supervised" guard does not race the+// cancel — the deleted entry's goroutine releases its lease as part of+// teardown, and the new supervisor's acquireLease takes over on its+// own clock.+func (h *Hub) maybeRestartOnRotation(id string, row db.LarkInstallation) {+ want := installationFingerprint(row)+ h.mu.Lock()+ entry, ok := h.supervisors[id]+ if !ok || entry.fingerprint == want {+ h.mu.Unlock()+ return+ }+ h.cfg.Logger.Info("lark hub: credentials rotated, restarting supervisor",+ "installation_id", id,+ "app_id", row.AppID,+ )+ entry.cancel()+ delete(h.supervisors, id)+ h.mu.Unlock()+}++func (h *Hub) startSupervisor(parent context.Context, inst db.LarkInstallation) {+ id := uuidString(inst.ID)+ h.mu.Lock()+ if h.stopped {+ h.mu.Unlock()+ return+ }+ if _, exists := h.supervisors[id]; exists {+ h.mu.Unlock()+ return+ }+ ctx, cancel := context.WithCancel(parent)+ h.supervisorGen+++ gen := h.supervisorGen+ h.supervisors[id] = supervisorEntry{+ cancel: cancel,+ fingerprint: installationFingerprint(inst),+ gen: gen,+ }+ h.wg.Add(1)+ h.mu.Unlock()+ go h.supervise(ctx, inst, id, gen)+}++// leaseToken composes the per-supervisor lease token. We pair the+// Hub-wide nodeID (so multi-replica observability still works — an+// operator inspecting lark_installation.ws_lease_token can map it+// back to a process) with the supervisor's gen so two supervisors+// inside the SAME Hub running back-to-back for the same installation+// (the rotation path) carry different tokens. That distinction is+// what stops an old supervisor's post-cancel releaseLease from+// CAS-matching and DELETE-ing the lease the successor just acquired.+//+// We use strconv.FormatUint rather than fmt.Sprintf because this is on+// the supervise hot path (called on every renew tick when its result+// would be ineligible to be cached) and we'd like to keep allocation+// pressure minimal.+func leaseToken(nodeID string, gen uint64) string {+ return nodeID + "-g" + strconv.FormatUint(gen, 10)+}++// installationFingerprint condenses the credentials-bearing columns of+// the installation row into an opaque string. Two rows with the same+// fingerprint are interchangeable as far as the connector is concerned;+// any byte difference here means the next sweep will tear the running+// supervisor down and start it again with the fresh credentials. We+// include app_id (which Lark rotates on every device-flow registration),+// bot_open_id (sanity — protects against an app_id reuse with a+// different bot identity), and a SHA-256 of the encrypted app_secret+// blob so a re-encrypt at rest also triggers a restart. The plaintext+// secret is never extracted; the encrypted ciphertext is fine to hash.+func installationFingerprint(inst db.LarkInstallation) string {+ sum := sha256.Sum256(inst.AppSecretEncrypted)+ return inst.AppID + "|" + inst.BotOpenID + "|" + hex.EncodeToString(sum[:])+}++// supervise owns one installation's connection lifecycle. It loops:+// acquire lease → spin up connector → renew lease while connector is+// running → on connector exit, back off → repeat. Returns (and the+// goroutine ends) when ctx is cancelled.+func (h *Hub) supervise(ctx context.Context, inst db.LarkInstallation, id string, gen uint64) {+ defer h.wg.Done()+ defer func() {+ // Only clear the supervisors map entry if it still belongs to+ // us — gen disambiguates "this entry is mine" from "the+ // rotation path already replaced me with a fresh supervisor."+ // Without the gen check, the old goroutine's defer would race+ // to delete the new entry it knows nothing about.+ h.mu.Lock()+ if entry, ok := h.supervisors[id]; ok && entry.gen == gen {+ delete(h.supervisors, id)+ }+ h.mu.Unlock()+ }()++ // Per-supervisor lease token: scopes the DB-level token fence to+ // THIS goroutine so a stale post-cancel release from a rotation+ // predecessor can't clobber a successor's just-acquired lease.+ // Embeds the Hub's nodeID for cross-replica observability and the+ // supervisor gen so the same Hub running multiple sequential+ // supervisors for the same installation (rotation) gets distinct+ // tokens for each.+ leaseTok := leaseToken(h.nodeID, gen)+ log := h.cfg.Logger.With(+ "installation_id", id,+ "node_id", h.nodeID,+ "lease_token", leaseTok,+ )+ backoff := h.cfg.MinBackoff++ for {+ if ctx.Err() != nil {+ return+ }++ // Try to claim the WS lease for this installation. If another+ // replica already owns a live lease, sleep until either the+ // lease expires or our context is cancelled.+ leased, err := h.acquireLease(ctx, inst.ID, leaseTok)+ if err != nil {+ log.Warn("lark hub: acquire lease error", "error", err)+ if sleep(ctx, h.cfg.LeaseRenewInterval) {+ return+ }+ continue+ }+ if !leased {+ // Another replica owns the lease. Wait LeaseRenewInterval+ // (less than LeaseTTL) and re-check; if they die, we'll+ // pick it up on the next iteration.+ if sleep(ctx, h.cfg.LeaseRenewInterval) {+ return+ }+ continue+ }++ // Lease acquired. Build a connector, run it under a child+ // context, and start the lease renewer in parallel. The+ // connector returns when its connection dies or our ctx is+ // cancelled; we always release the lease afterwards.+ conn, err := h.factory(inst)+ if err != nil {+ log.Error("lark hub: connector factory failed", "error", err)+ h.releaseLease(inst.ID, leaseTok)+ if sleep(ctx, backoff) {+ return+ }+ backoff = nextBackoff(backoff, h.cfg.MaxBackoff)+ continue+ }++ runCtx, runCancel := context.WithCancel(ctx)+ renewDone := make(chan struct{})+ go func() {+ defer close(renewDone)+ // renewLeaseUntil cancels runCtx itself on lease loss so the+ // connector exits even if its wire I/O is currently blocked.+ // This is what makes the "at most one active WS per+ // installation across replicas" invariant hold under lease+ // theft: A's renewer fails CAS the moment B steals the+ // lease, A's runCtx flips done, A's connector returns, and+ // only B is consuming events.+ h.renewLeaseUntil(runCtx, runCancel, inst.ID, leaseTok)+ }()++ startedAt := h.cfg.Now()+ runErr := conn.Run(runCtx, inst, func(emitCtx context.Context, msg InboundMessage) (DispatchResult, error) {+ return h.handleEvent(emitCtx, inst, log, msg)+ })+ runCancel()+ <-renewDone+ h.releaseLease(inst.ID, leaseTok)++ if ctx.Err() != nil {+ return+ }++ // If the connection lived long enough that we believe it was+ // "stable", reset the backoff so a single late failure does+ // not start us at the cap. Otherwise step up the backoff.+ uptime := h.cfg.Now().Sub(startedAt)+ if uptime >= h.cfg.ResetBackoffAfter {+ backoff = h.cfg.MinBackoff+ }+ if runErr != nil {+ log.Warn("lark hub: connector exited with error", "error", runErr, "uptime", uptime.String())+ } else {+ log.Info("lark hub: connector exited cleanly", "uptime", uptime.String())+ }+ if sleep(ctx, jitter(backoff)) {+ return+ }+ backoff = nextBackoff(backoff, h.cfg.MaxBackoff)+ }+}++// acquireLease tries to claim or renew the WS lease for an+// installation. Returns (true, nil) when the lease is owned by this+// supervisor after the call; (false, nil) when another replica or+// in-process predecessor holds a live lease; or (false, err) for+// transport / DB failures.+//+// token is a per-supervisor identifier (see leaseToken) — NOT the+// hub-wide nodeID. This is the load-bearing change for rotation+// safety: an old supervisor and its successor inside the same Hub+// each carry a distinct token, so the old supervisor's stale release+// can no longer match (and DELETE) the successor's just-acquired+// lease row.+func (h *Hub) acquireLease(ctx context.Context, instID pgtype.UUID, token string) (bool, error) {+ expires := h.cfg.Now().Add(h.cfg.LeaseTTL)+ _, err := h.queries.AcquireLarkWSLease(ctx, db.AcquireLarkWSLeaseParams{+ ID: instID,+ NewToken: pgtype.Text{String: token, Valid: true},+ NewExpiresAt: pgtype.Timestamptz{Time: expires, Valid: true},+ })+ if err == nil {+ return true, nil+ }+ if isNoRowsErr(err) {+ // CAS predicate didn't match — someone else (another replica+ // OR a sibling supervisor mid-rotation) holds the lease. We+ // back off and let the renewer / supervise loop re-poll on its+ // own clock.+ return false, nil+ }+ return false, err+}++// renewLeaseUntil re-acquires the lease on a tight cadence so a single+// missed renewal does not yield it. Exits when ctx is cancelled.+//+// Lease loss (acquireLease returns leased=false) MUST cancel the+// connector's run context — otherwise the supervise loop would+// release the lease but the connector goroutine could still be+// blocked on its wire I/O and continue consuming Lark events until+// its TCP read finally errored out. That window is exactly the+// "two replicas processing the same installation" failure mode the+// §4.4 ownership invariant rules out. Calling cancelRun here forces+// the connector's ctx to flip done immediately, so conn.Run returns+// in bounded time even when the underlying socket is silent.+//+// token MUST be the same per-supervisor token threaded through the+// initial acquireLease call. Otherwise the very first renewal would+// CAS-fail against the supervisor's own previous renew and tear the+// connector down on every renew interval.+func (h *Hub) renewLeaseUntil(ctx context.Context, cancelRun context.CancelFunc, instID pgtype.UUID, token string) {+ t := time.NewTicker(h.cfg.LeaseRenewInterval)+ defer t.Stop()+ for {+ select {+ case <-ctx.Done():+ return+ case <-t.C:+ leased, err := h.acquireLease(ctx, instID, token)+ if err != nil {+ h.cfg.Logger.Warn("lark hub: lease renewal error",+ "installation_id", uuidString(instID),+ "error", err,+ )+ continue+ }+ if !leased {+ h.cfg.Logger.Warn("lark hub: lease lost; tearing down connector",+ "installation_id", uuidString(instID),+ )+ cancelRun()+ return+ }+ }+ }+}++// releaseLease writes a token-fenced DELETE to lark_installation's+// lease columns so the next supervisor (this process or another+// replica) can pick up the installation without waiting for LeaseTTL+// to expire.+//+// The supervisor calls this from two places — factory-error retry and+// post-Run cleanup — and at shutdown the parent ctx is already done,+// so passing it through would short-circuit the DB call before it ever+// reached the pool. Instead we derive a fresh background ctx with a+// bounded LeaseReleaseTimeout: a healthy pool finishes in milliseconds,+// and a frozen pool can no longer hang shutdown indefinitely. The+// fallback when the bound trips is the same as a crash — the lease row+// stays put until its TTL elapses on the next replica.+//+// token MUST be the same per-supervisor token used to acquire. If a+// rotation has already replaced this supervisor and the successor has+// taken the lease with its own token, the DELETE's WHERE clause won't+// match this supervisor's stale token and the call no-ops instead of+// clobbering the successor's lease. That fence is the whole point of+// per-supervisor tokens.+func (h *Hub) releaseLease(instID pgtype.UUID, token string) {+ ctx, cancel := context.WithTimeout(context.Background(), h.cfg.LeaseReleaseTimeout)+ defer cancel()+ if err := h.queries.ReleaseLarkWSLease(ctx, db.ReleaseLarkWSLeaseParams{+ ID: instID,+ CurrentToken: pgtype.Text{String: token, Valid: true},+ }); err != nil {+ h.cfg.Logger.Warn("lark hub: release lease failed",+ "installation_id", uuidString(instID),+ "error", err,+ )+ }+}++// handleEvent is the seam between the connector (which emits normalized+// InboundMessage) and the inbound Dispatcher + outbound OutcomeReplier.+// We deliberately do not retry here — the Dispatcher classifies errors+// itself (productizable outcomes vs. infra failures), and infra+// failures propagate up to the connector, which decides whether to+// reconnect.+//+// CRITICAL: handleEvent MUST return promptly because the connector+// writes the frame ACK right after emit returns, and Lark's long-conn+// server expects an ACK within 3 seconds. The dispatcher itself is+// fast (one DB roundtrip + identity check) but the outbound replier+// can do real Lark HTTP calls — token mint, card send — each with+// its own multi-second client timeout. Running the replier inline+// would couple ACK latency to outbound HTTP, and if that HTTP stalls+// for >3s Lark treats the event as un-ACKed and re-pushes it; by then+// Dispatcher has already marked the dedup row terminal, so the retry+// gets dropped and the user never receives the binding prompt /+// offline notice.+//+// Fix: dispatch is synchronous (in the connector's read loop), the+// reply is detached. Each reply runs in its own goroutine under a+// fresh context bounded by ReplyTimeout (strictly under 3s). Hub.Wait+// joins on replyWg so shutdown still drains in-flight replies.+func (h *Hub) handleEvent(ctx context.Context, inst db.LarkInstallation, log *slog.Logger, msg InboundMessage) (DispatchResult, error) {+ if h.dispatcher == nil {+ log.Warn("lark hub: dispatcher not configured; dropping event",+ "event_id", msg.EventID,+ )+ return DispatchResult{}, ErrDispatcherNotConfigured+ }+ res, err := h.dispatcher.Handle(ctx, msg)+ if err != nil {+ log.Error("lark hub: dispatcher error",+ "event_id", msg.EventID,+ "error", err,+ )+ return res, err+ }+ log.Debug("lark hub: dispatch outcome",+ "event_id", msg.EventID,+ "outcome", string(res.Outcome),+ "drop_reason", string(res.DropReason),+ )+ h.scheduleReply(inst, msg, res, log)+ return res, nil+}++// scheduleReply detaches the OutcomeReplier from the ACK critical path.+// The reply goroutine uses a fresh context.Background() with a+// ReplyTimeout deadline so it is independent of the inbound emit ctx+// (which the connector cancels as soon as Run exits). A nil or noop+// replier short-circuits — no goroutine, no wg tracking.+//+// Why a fresh background ctx instead of inheriting from the emit ctx:+// the emit ctx is cancelled when the connector's runCtx fires, which+// can happen mid-reply on a normal reconnect cycle. Inheriting would+// kill the outbound reply for no reason — the binding card / offline+// notice is still wanted. ReplyTimeout is the only guard we need.+func (h *Hub) scheduleReply(inst db.LarkInstallation, msg InboundMessage, res DispatchResult, log *slog.Logger) {+ r := h.replier+ if r == nil {+ return+ }+ // Fast path: noop replier doesn't do any IO, run it inline so we+ // don't pay goroutine + waitgroup cost for a no-op. The exposed+ // type is unexported but the test seam uses NewNoopOutcomeReplier+ // which returns *noopReplier, so the type-assert is safe.+ if _, isNoop := r.(*noopReplier); isNoop {+ r.Reply(context.Background(), inst, msg, res)+ return+ }+ h.replyWg.Add(1)+ go func() {+ defer h.replyWg.Done()+ ctx, cancel := context.WithTimeout(context.Background(), h.cfg.ReplyTimeout)+ defer cancel()+ r.Reply(ctx, inst, msg, res)+ if ctx.Err() == context.DeadlineExceeded {+ log.Warn("lark hub: outbound reply timed out",+ "event_id", msg.EventID,+ "outcome", string(res.Outcome),+ "timeout", h.cfg.ReplyTimeout.String(),+ )+ }+ }()+}++// ErrDispatcherNotConfigured is surfaced to the connector when emit is+// called on a Hub that was constructed without a Dispatcher. Returning+// it (instead of silently dropping) lets the connector log and / or+// disconnect so the misconfiguration is visible in production.+var ErrDispatcherNotConfigured = errors.New("lark hub: dispatcher not configured")++func (h *Hub) cancelAll() {+ h.mu.Lock()+ h.stopped = true+ for id, entry := range h.supervisors {+ entry.cancel()+ delete(h.supervisors, id)+ }+ h.mu.Unlock()+}++// newNodeID returns a 16-byte hex random string unique to this process.+// The DB stores it in lark_installation.ws_lease_token; matching tokens+// on subsequent acquires are treated as renewals (same owner).+func newNodeID() string {+ buf := make([]byte, 16)+ if _, err := cryptorand.Read(buf); err != nil {+ // crypto/rand failure is catastrophic and rare; fall back to a+ // timestamp-derived token rather than panicking on boot.+ return fmt.Sprintf("nodeid-fallback-%d", time.Now().UnixNano())+ }+ return hex.EncodeToString(buf)+}++// nextBackoff doubles the current backoff up to max. Pure helper so+// the supervise loop reads top-to-bottom.+func nextBackoff(cur, max time.Duration) time.Duration {+ next := cur * 2+ if next > max {+ return max+ }+ return next+}++// jitter spreads reconnect storms (e.g. after a Lark-side outage)+// across the [0.5d, 1.5d) window, so 100 installations don't all+// retry on the same timer edge.+func jitter(d time.Duration) time.Duration {+ if d <= 0 {+ return d+ }+ delta := d / 2+ return d - delta + time.Duration(mathrand.Int64N(int64(2*delta)+1))+}++// sleep is a ctx-aware time.Sleep. Returns true iff the ctx was+// cancelled before the sleep completed — callers use the boolean to+// short-circuit shutdown.+func sleep(ctx context.Context, d time.Duration) bool {+ if d <= 0 {+ return ctx.Err() != nil+ }+ t := time.NewTimer(d)+ defer t.Stop()+ select {+ case <-ctx.Done():+ return true+ case <-t.C:+ return false+ }+}++// isNoRowsErr is the local equivalent of errors.Is(err, pgx.ErrNoRows)+// without importing pgx into this file. The CAS predicate on+// AcquireLarkWSLease surfaces "lease held by someone else" as a+// no-rows return, not a structured error type.+func isNoRowsErr(err error) bool {+ if err == nil {+ return false+ }+ // pgx.ErrNoRows is the sentinel; matching by message is+ // sufficient and avoids importing pgx purely for this comparison.+ return errors.Is(err, errPgxNoRows) || err.Error() == "no rows in result set"+}++// errPgxNoRows is initialized in hub_pgx.go to pgx.ErrNoRows so the+// no-rows check above works under both the real pgx import path and+// the string-matched fallback (test fakes return that string directly).+var errPgxNoRows error++func uuidString(u pgtype.UUID) string { return util.UUIDToString(u) }diff --git a/server/internal/integrations/lark/hub_pgx.go b/server/internal/integrations/lark/hub_pgx.gonew file mode 100644index 0000000000..4e309d3cfe--- /dev/null+++ b/server/internal/integrations/lark/hub_pgx.go@@ -0,0 +1,12 @@+package lark++import "github.com/jackc/pgx/v5"++func init() {+ // Bind the package-level sentinel used by hub.go's isNoRowsErr.+ // Keeping the pgx import isolated to this file means the rest of+ // hub.go (and the test seam against fake queries) doesn't need the+ // pgx import path; fakes can return errors.New("no rows in result+ // set") and still trigger the lease "held elsewhere" branch.+ errPgxNoRows = pgx.ErrNoRows+}diff --git a/server/internal/integrations/lark/hub_test.go b/server/internal/integrations/lark/hub_test.gonew file mode 100644index 0000000000..e5b5071cdd--- /dev/null+++ b/server/internal/integrations/lark/hub_test.go@@ -0,0 +1,1293 @@+package lark++import (+ "bytes"+ "context"+ "errors"+ "io"+ "log/slog"+ "sync"+ "sync/atomic"+ "testing"+ "time"++ "github.com/jackc/pgx/v5/pgtype"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++// fakeHubQueries is the unit-test seam for HubQueries. The lease state+// is held in memory so a single fake can play both "we hold the lease"+// and "another replica holds the lease" scenarios across one test.+type fakeHubQueries struct {+ mu sync.Mutex+ installations []db.LarkInstallation+ listErr error+ leaseOwner map[string]string // installation_id -> ws_lease_token+ leaseExpiresAt map[string]time.Time // installation_id -> expiry+ acquireErr error+ releaseErr error+ now func() time.Time+ acquireCount int32++ // releaseBlock, if non-nil, makes ReleaseLarkWSLease block until+ // either the channel is closed/sent on OR the caller's ctx fires.+ // Used to simulate a frozen DB pool so the bounded-release timeout+ // can be exercised without standing up real infrastructure.+ releaseBlock chan struct{}+ // releaseObservedCtxErr captures the ctx error (typically+ // context.DeadlineExceeded) the blocked release call observed+ // when its bounded ctx fired. Inspected by tests to prove the+ // bound actually fired instead of the test happening to win the+ // race naturally.+ releaseObservedCtxErr error+}++func newFakeHubQueries() *fakeHubQueries {+ return &fakeHubQueries{+ leaseOwner: make(map[string]string),+ leaseExpiresAt: make(map[string]time.Time),+ now: time.Now,+ }+}++func (f *fakeHubQueries) ListActiveLarkInstallations(ctx context.Context) ([]db.LarkInstallation, error) {+ f.mu.Lock()+ defer f.mu.Unlock()+ if f.listErr != nil {+ return nil, f.listErr+ }+ out := make([]db.LarkInstallation, len(f.installations))+ copy(out, f.installations)+ return out, nil+}++func (f *fakeHubQueries) AcquireLarkWSLease(ctx context.Context, arg db.AcquireLarkWSLeaseParams) (db.LarkInstallation, error) {+ atomic.AddInt32(&f.acquireCount, 1)+ f.mu.Lock()+ defer f.mu.Unlock()+ if f.acquireErr != nil {+ return db.LarkInstallation{}, f.acquireErr+ }+ id := uuidString(arg.ID)+ owner, hasOwner := f.leaseOwner[id]+ exp := f.leaseExpiresAt[id]+ now := f.now()+ // CAS: accept when no holder, holder expired, or holder is us.+ if !hasOwner || exp.Before(now) || owner == arg.NewToken.String {+ f.leaseOwner[id] = arg.NewToken.String+ f.leaseExpiresAt[id] = arg.NewExpiresAt.Time+ // Return the (synthetic) row — the supervise loop only checks+ // the error, not the row contents.+ return db.LarkInstallation{ID: arg.ID}, nil+ }+ // Live lease held by someone else.+ return db.LarkInstallation{}, errPgxNoRows+}++func (f *fakeHubQueries) ReleaseLarkWSLease(ctx context.Context, arg db.ReleaseLarkWSLeaseParams) error {+ f.mu.Lock()+ block := f.releaseBlock+ f.mu.Unlock()+ if block != nil {+ select {+ case <-block:+ // Released by the test — fall through to the normal path.+ case <-ctx.Done():+ f.mu.Lock()+ f.releaseObservedCtxErr = ctx.Err()+ f.mu.Unlock()+ return ctx.Err()+ }+ }+ f.mu.Lock()+ defer f.mu.Unlock()+ if f.releaseErr != nil {+ return f.releaseErr+ }+ id := uuidString(arg.ID)+ if f.leaseOwner[id] == arg.CurrentToken.String {+ delete(f.leaseOwner, id)+ delete(f.leaseExpiresAt, id)+ }+ return nil+}++// presetLease forcibly assigns a lease to a holder other than the hub+// under test. Used to verify "another replica owns it" branches.+func (f *fakeHubQueries) presetLease(id pgtype.UUID, token string, expires time.Time) {+ f.mu.Lock()+ defer f.mu.Unlock()+ f.leaseOwner[uuidString(id)] = token+ f.leaseExpiresAt[uuidString(id)] = expires+}++// fakeConnector counts how many times Run was invoked and behaves+// according to the script provided per-call. The default behavior+// (script nil) blocks on ctx.Done — useful for the "owns lease, stays+// connected" test.+type fakeConnector struct {+ mu sync.Mutex+ runs int+ script []func(ctx context.Context, emit EventEmitter) error+ emit EventEmitter+}++func (f *fakeConnector) Run(ctx context.Context, _ db.LarkInstallation, emit EventEmitter) error {+ f.mu.Lock()+ idx := f.runs+ f.runs+++ if idx < len(f.script) {+ fn := f.script[idx]+ f.mu.Unlock()+ return fn(ctx, emit)+ }+ f.mu.Unlock()+ // Default: hold until cancelled.+ f.emit = emit+ <-ctx.Done()+ return nil+}++func (f *fakeConnector) Runs() int {+ f.mu.Lock()+ defer f.mu.Unlock()+ return f.runs+}++func uuidFromString(t *testing.T, s string) pgtype.UUID {+ t.Helper()+ var u pgtype.UUID+ if err := u.Scan(s); err != nil {+ t.Fatalf("scan uuid %q: %v", s, err)+ }+ return u+}++func newDiscardLogger() *slog.Logger {+ return slog.New(slog.NewTextHandler(io.Discard, nil))+}++func TestHubAcquiresLeaseAndStartsSupervisor(t *testing.T) {+ q := newFakeHubQueries()+ instID := uuidFromString(t, "11111111-1111-1111-1111-111111111111")+ q.installations = []db.LarkInstallation{{ID: instID, Status: "active"}}++ conn := &fakeConnector{}+ factory := func(_ db.LarkInstallation) (EventConnector, error) { return conn, nil }++ hub := NewHub(q, factory, nil, HubConfig{+ LeaseTTL: 500 * time.Millisecond,+ LeaseRenewInterval: 50 * time.Millisecond,+ PollInterval: 10 * time.Millisecond,+ MinBackoff: 5 * time.Millisecond,+ MaxBackoff: 50 * time.Millisecond,+ ResetBackoffAfter: 1 * time.Second,+ Logger: newDiscardLogger(),+ })++ ctx, cancel := context.WithCancel(context.Background())+ go hub.Run(ctx)++ // Wait until the supervisor has started the connector at least once.+ if !waitFor(200*time.Millisecond, func() bool { return conn.Runs() >= 1 }) {+ t.Fatalf("expected connector to start; runs=%d", conn.Runs())+ }++ cancel()+ hub.Wait()++ // After shutdown the lease should be released so another replica+ // can take over without waiting for the TTL to elapse.+ q.mu.Lock()+ defer q.mu.Unlock()+ if _, ok := q.leaseOwner[uuidString(instID)]; ok {+ t.Fatalf("lease should be released after shutdown, got owner %q", q.leaseOwner[uuidString(instID)])+ }+}++func TestHubSkipsInstallationWhenAnotherReplicaHoldsLease(t *testing.T) {+ q := newFakeHubQueries()+ instID := uuidFromString(t, "22222222-2222-2222-2222-222222222222")+ q.installations = []db.LarkInstallation{{ID: instID, Status: "active"}}+ // Another replica already owns the lease for the next 10 seconds.+ q.presetLease(instID, "other-replica", time.Now().Add(10*time.Second))++ conn := &fakeConnector{}+ factory := func(_ db.LarkInstallation) (EventConnector, error) { return conn, nil }++ hub := NewHub(q, factory, nil, HubConfig{+ LeaseTTL: 500 * time.Millisecond,+ LeaseRenewInterval: 20 * time.Millisecond,+ PollInterval: 20 * time.Millisecond,+ MinBackoff: 5 * time.Millisecond,+ MaxBackoff: 20 * time.Millisecond,+ ResetBackoffAfter: 1 * time.Second,+ Logger: newDiscardLogger(),+ })++ ctx, cancel := context.WithCancel(context.Background())+ go hub.Run(ctx)++ // Give the hub plenty of opportunity to try to take over.+ time.Sleep(150 * time.Millisecond)++ if conn.Runs() != 0 {+ t.Fatalf("connector should not run while another replica owns lease; runs=%d", conn.Runs())+ }++ cancel()+ hub.Wait()+}++func TestHubReclaimsLeaseAfterAnotherReplicaExpires(t *testing.T) {+ q := newFakeHubQueries()+ instID := uuidFromString(t, "33333333-3333-3333-3333-333333333333")+ q.installations = []db.LarkInstallation{{ID: instID, Status: "active"}}+ // Set the other replica's lease to expire in 80ms so the hub+ // (which polls/renews on 20ms intervals) will pick it up.+ q.presetLease(instID, "other-replica", time.Now().Add(80*time.Millisecond))++ conn := &fakeConnector{}+ factory := func(_ db.LarkInstallation) (EventConnector, error) { return conn, nil }++ hub := NewHub(q, factory, nil, HubConfig{+ LeaseTTL: 500 * time.Millisecond,+ LeaseRenewInterval: 20 * time.Millisecond,+ PollInterval: 20 * time.Millisecond,+ MinBackoff: 5 * time.Millisecond,+ MaxBackoff: 20 * time.Millisecond,+ ResetBackoffAfter: 1 * time.Second,+ Logger: newDiscardLogger(),+ })++ ctx, cancel := context.WithCancel(context.Background())+ go hub.Run(ctx)++ if !waitFor(500*time.Millisecond, func() bool { return conn.Runs() >= 1 }) {+ t.Fatalf("expected connector to start after lease expiry; runs=%d", conn.Runs())+ }+ cancel()+ hub.Wait()+}++func TestHubReapsSupervisorWhenInstallationRevoked(t *testing.T) {+ q := newFakeHubQueries()+ instID := uuidFromString(t, "44444444-4444-4444-4444-444444444444")+ q.installations = []db.LarkInstallation{{ID: instID, Status: "active"}}++ conn := &fakeConnector{}+ factory := func(_ db.LarkInstallation) (EventConnector, error) { return conn, nil }++ hub := NewHub(q, factory, nil, HubConfig{+ LeaseTTL: 500 * time.Millisecond,+ LeaseRenewInterval: 20 * time.Millisecond,+ PollInterval: 20 * time.Millisecond,+ MinBackoff: 5 * time.Millisecond,+ MaxBackoff: 20 * time.Millisecond,+ ResetBackoffAfter: 1 * time.Second,+ Logger: newDiscardLogger(),+ })++ ctx, cancel := context.WithCancel(context.Background())+ go hub.Run(ctx)+ defer func() { cancel(); hub.Wait() }()++ if !waitFor(200*time.Millisecond, func() bool { return conn.Runs() >= 1 }) {+ t.Fatalf("expected connector to start; runs=%d", conn.Runs())+ }++ // Simulate revocation: the installation disappears from+ // ListActiveLarkInstallations. The Hub should cancel its+ // supervisor on the next sweep, which releases the lease.+ q.mu.Lock()+ q.installations = nil+ q.mu.Unlock()++ if !waitFor(500*time.Millisecond, func() bool {+ q.mu.Lock()+ defer q.mu.Unlock()+ _, stillHeld := q.leaseOwner[uuidString(instID)]+ return !stillHeld+ }) {+ t.Fatalf("expected lease to be released after revocation")+ }+}++// TestHubRestartsSupervisorOnCredentialsRotation pins the rotation+// invariant Bohan hit on the live env: re-scanning the same agent+// runs the device flow again, which mints a brand-new Lark bot with+// a fresh app_id / encrypted app_secret. The lark_installation row is+// updated in place (UNIQUE(agent_id)), but the running supervisor+// holds the OLD inst struct by value. Without a fingerprint-driven+// restart the connector keeps a WS open against the OLD bot's app_id+// and the new bot silently goes dark — exactly the "claude code 没反应"+// symptom Bohan reported.+//+// Repro: start the hub with installation A (app_id=app_one), wait for+// the connector factory to be called, then mutate the row to a new+// app_id (app_two). The next sweep MUST cancel the first supervisor+// and start a second one with the new credentials.+func TestHubRestartsSupervisorOnCredentialsRotation(t *testing.T) {+ q := newFakeHubQueries()+ instID := uuidFromString(t, "abcdabcd-abcd-abcd-abcd-abcdabcdabcd")+ q.installations = []db.LarkInstallation{{+ ID: instID,+ Status: "active",+ AppID: "app_one",+ BotOpenID: "bot_open_id_one",+ AppSecretEncrypted: []byte("encrypted_one"),+ }}++ type seenInst struct{ AppID string }+ var mu sync.Mutex+ var seen []seenInst+ factory := func(inst db.LarkInstallation) (EventConnector, error) {+ mu.Lock()+ seen = append(seen, seenInst{AppID: inst.AppID})+ mu.Unlock()+ return &fakeConnector{}, nil+ }++ hub := NewHub(q, factory, nil, HubConfig{+ LeaseTTL: 500 * time.Millisecond,+ LeaseRenewInterval: 50 * time.Millisecond,+ PollInterval: 20 * time.Millisecond,+ MinBackoff: 5 * time.Millisecond,+ MaxBackoff: 20 * time.Millisecond,+ ResetBackoffAfter: 1 * time.Second,+ Logger: newDiscardLogger(),+ })++ ctx, cancel := context.WithCancel(context.Background())+ go hub.Run(ctx)+ defer func() { cancel(); hub.Wait() }()++ if !waitFor(300*time.Millisecond, func() bool {+ mu.Lock()+ defer mu.Unlock()+ return len(seen) >= 1+ }) {+ t.Fatalf("expected initial connector start; got %d", len(seen))+ }++ // Rotate credentials in place — same installation_id, new app_id ++ // new encrypted secret. This is exactly what device-flow re-scan+ // produces.+ q.mu.Lock()+ q.installations[0].AppID = "app_two"+ q.installations[0].BotOpenID = "bot_open_id_two"+ q.installations[0].AppSecretEncrypted = []byte("encrypted_two")+ q.mu.Unlock()++ if !waitFor(500*time.Millisecond, func() bool {+ mu.Lock()+ defer mu.Unlock()+ for _, s := range seen {+ if s.AppID == "app_two" {+ return true+ }+ }+ return false+ }) {+ mu.Lock()+ got := append([]seenInst(nil), seen...)+ mu.Unlock()+ t.Fatalf("expected a second connector start with rotated app_id; got %+v", got)+ }+}++// TestHubDoesNotRestartSupervisorOnUnchangedRow pins the negative case:+// a sweep that observes an installation row identical to the fingerprint+// the supervisor was started with MUST NOT restart. Without this guard+// the rotation logic would degrade into a busy-loop, tearing the+// connector down on every poll tick.+func TestHubDoesNotRestartSupervisorOnUnchangedRow(t *testing.T) {+ q := newFakeHubQueries()+ instID := uuidFromString(t, "bcdebcde-bcde-bcde-bcde-bcdebcdebcde")+ q.installations = []db.LarkInstallation{{+ ID: instID,+ Status: "active",+ AppID: "app_stable",+ BotOpenID: "bot_stable",+ AppSecretEncrypted: []byte("stable"),+ }}++ starts := int32(0)+ factory := func(_ db.LarkInstallation) (EventConnector, error) {+ atomic.AddInt32(&starts, 1)+ return &fakeConnector{}, nil+ }++ hub := NewHub(q, factory, nil, HubConfig{+ LeaseTTL: 500 * time.Millisecond,+ LeaseRenewInterval: 50 * time.Millisecond,+ PollInterval: 10 * time.Millisecond,+ MinBackoff: 5 * time.Millisecond,+ MaxBackoff: 20 * time.Millisecond,+ ResetBackoffAfter: 1 * time.Second,+ Logger: newDiscardLogger(),+ })++ ctx, cancel := context.WithCancel(context.Background())+ go hub.Run(ctx)+ defer func() { cancel(); hub.Wait() }()++ // Wait until the supervisor has called the factory at least once.+ if !waitFor(200*time.Millisecond, func() bool { return atomic.LoadInt32(&starts) >= 1 }) {+ t.Fatalf("expected initial connector start; got %d", starts)+ }+ // Let several sweep ticks happen with an unchanged row.+ time.Sleep(120 * time.Millisecond)+ got := atomic.LoadInt32(&starts)+ if got > 2 {+ // Allow one extra start in case the fakeConnector returns+ // immediately and the supervise loop re-enters the connector+ // factory under backoff. More than that is the busy-loop bug.+ t.Fatalf("supervisor restarted unexpectedly on unchanged row: %d factory calls in 320ms", got)+ }+}++// TestHubRotationStaleReleaseDoesNotClearSuccessorLease pins the+// fix for Elon's review of HEAD be8d4cef. Before per-supervisor lease+// tokens, both old and new supervisors of the same Hub used the same+// hub-wide nodeID as their lease token. The rotation race went:+//+// 1. Old supervisor cancelled by maybeRestartOnRotation.+// 2. New supervisor started; acquireLease takes the lease.+// 3. Old supervisor finishes post-cancel unwind and calls+// releaseLease(nodeID).+// 4. DB row's CurrentToken still equals nodeID (because new+// supervisor wrote the SAME token). DELETE matches → DB row+// cleared → new supervisor's lease silently lost.+//+// Per-supervisor tokens (nodeID + "-g" + gen) make step 3's+// CurrentToken belong to the OLD supervisor, and the DB row's actual+// CurrentToken belongs to the NEW supervisor — so the DELETE no-ops+// and the successor keeps its lease.+//+// This test drives the lease state machine directly through the+// fakeHubQueries, simulating the exact ordering: old acquires+// (token_A) → rotation → new acquires (token_B) → old's stale+// release(token_A). The lease must remain held by token_B.+func TestHubRotationStaleReleaseDoesNotClearSuccessorLease(t *testing.T) {+ q := newFakeHubQueries()+ instID := uuidFromString(t, "deadbeef-dead-beef-dead-beefdeadbeef")+ expires := time.Now().Add(time.Minute)++ tokenA := leaseToken("node_xyz", 1)+ tokenB := leaseToken("node_xyz", 2)+ if tokenA == tokenB {+ t.Fatalf("per-supervisor tokens must differ; got %q for both", tokenA)+ }++ // Old supervisor acquires.+ if _, err := q.AcquireLarkWSLease(context.Background(), db.AcquireLarkWSLeaseParams{+ ID: instID,+ NewToken: pgtype.Text{String: tokenA, Valid: true},+ NewExpiresAt: pgtype.Timestamptz{Time: expires, Valid: true},+ }); err != nil {+ t.Fatalf("old acquire: %v", err)+ }+ q.mu.Lock()+ if got := q.leaseOwner[uuidString(instID)]; got != tokenA {+ t.Fatalf("after old acquire, owner = %q; want %q", got, tokenA)+ }+ q.mu.Unlock()++ // Rotation: new supervisor takes over. acquireLease's CAS in the+ // production query accepts "matching token" as a renewal — but+ // here we want to exercise the post-cancel succession where the+ // old lease is gone or being replaced. The fake's CAS also accepts+ // expired rows, so we simulate the old supervisor's lease having+ // been released cleanly (its renewal hasn't fired yet on rotation+ // boundary, but in production a rotation cancels the old loop and+ // the old supervisor's defer eventually calls releaseLease — let+ // the new supervisor acquire BEFORE that release lands).+ q.mu.Lock()+ delete(q.leaseOwner, uuidString(instID))+ delete(q.leaseExpiresAt, uuidString(instID))+ q.mu.Unlock()+ if _, err := q.AcquireLarkWSLease(context.Background(), db.AcquireLarkWSLeaseParams{+ ID: instID,+ NewToken: pgtype.Text{String: tokenB, Valid: true},+ NewExpiresAt: pgtype.Timestamptz{Time: expires, Valid: true},+ }); err != nil {+ t.Fatalf("new acquire: %v", err)+ }+ q.mu.Lock()+ if got := q.leaseOwner[uuidString(instID)]; got != tokenB {+ t.Fatalf("after new acquire, owner = %q; want %q", got, tokenB)+ }+ q.mu.Unlock()++ // Old supervisor's defer / cleanup fires AFTER new acquired.+ // Without per-supervisor tokens this would clobber tokenB's lease.+ if err := q.ReleaseLarkWSLease(context.Background(), db.ReleaseLarkWSLeaseParams{+ ID: instID,+ CurrentToken: pgtype.Text{String: tokenA, Valid: true},+ }); err != nil {+ t.Fatalf("old release: %v", err)+ }++ // Successor's lease must still be held by tokenB.+ q.mu.Lock()+ got, ok := q.leaseOwner[uuidString(instID)]+ q.mu.Unlock()+ if !ok {+ t.Fatalf("successor lease silently cleared by stale release — the rotation race is back")+ }+ if got != tokenB {+ t.Fatalf("after stale release, owner = %q; want %q (successor's token)", got, tokenB)+ }+}++// TestHubRotationEndToEndKeepsSuccessorLeased exercises the same+// rotation race through the live supervise loop — not just the lease+// state machine in isolation. Drives a hub through:+//+// 1. install row with credentials A → supervisor1 acquires lease(A)+// 2. credentials rotate to B → maybeRestartOnRotation cancels sup1+// 3. supervisor2 starts, acquires lease(B)+// 4. sup1's post-cancel releaseLease(A) runs; must NOT clear lease(B)+//+// Even with the timing being non-deterministic (real goroutines), the+// fake's lease map either ends up with sup2's token or empty — empty+// means the successor lost its lease and would never deliver events,+// which is exactly the bug Elon flagged. We assert the lease ends up+// held by sup2's token.+func TestHubRotationEndToEndKeepsSuccessorLeased(t *testing.T) {+ q := newFakeHubQueries()+ instID := uuidFromString(t, "feedfeed-feed-feed-feed-feedfeedfeed")+ q.installations = []db.LarkInstallation{{+ ID: instID,+ Status: "active",+ AppID: "app_one",+ BotOpenID: "bot_one",+ AppSecretEncrypted: []byte("secret_one"),+ }}++ // Use a fakeConnector that blocks on ctx.Done so the renewer keeps+ // running and refreshes the lease at each tick, mirroring+ // production timing for the rotation handoff.+ factoryCalls := int32(0)+ factory := func(_ db.LarkInstallation) (EventConnector, error) {+ atomic.AddInt32(&factoryCalls, 1)+ return &fakeConnector{}, nil+ }++ hub := NewHub(q, factory, nil, HubConfig{+ LeaseTTL: 500 * time.Millisecond,+ LeaseRenewInterval: 30 * time.Millisecond,+ PollInterval: 15 * time.Millisecond,+ MinBackoff: 5 * time.Millisecond,+ MaxBackoff: 20 * time.Millisecond,+ ResetBackoffAfter: 1 * time.Second,+ Logger: newDiscardLogger(),+ })++ ctx, cancel := context.WithCancel(context.Background())+ go hub.Run(ctx)+ defer func() { cancel(); hub.Wait() }()++ if !waitFor(300*time.Millisecond, func() bool { return atomic.LoadInt32(&factoryCalls) >= 1 }) {+ t.Fatalf("expected sup1 to start; got %d factory calls", factoryCalls)+ }+ q.mu.Lock()+ sup1Token := q.leaseOwner[uuidString(instID)]+ q.mu.Unlock()+ if sup1Token == "" {+ t.Fatalf("sup1 did not write a lease token")+ }++ // Rotation.+ q.mu.Lock()+ q.installations[0].AppID = "app_two"+ q.installations[0].BotOpenID = "bot_two"+ q.installations[0].AppSecretEncrypted = []byte("secret_two")+ q.mu.Unlock()++ // Wait for sup2 to start AND its lease token to differ from sup1's.+ // The successor's token must end up owning the row regardless of+ // when sup1's stale release lands.+ if !waitFor(500*time.Millisecond, func() bool {+ if atomic.LoadInt32(&factoryCalls) < 2 {+ return false+ }+ q.mu.Lock()+ defer q.mu.Unlock()+ curr, ok := q.leaseOwner[uuidString(instID)]+ return ok && curr != sup1Token+ }) {+ q.mu.Lock()+ got, ok := q.leaseOwner[uuidString(instID)]+ q.mu.Unlock()+ t.Fatalf("successor lease never present; ok=%v owner=%q factoryCalls=%d",+ ok, got, atomic.LoadInt32(&factoryCalls))+ }++ // Give sup1's deferred release a chance to land, then re-check.+ time.Sleep(150 * time.Millisecond)+ q.mu.Lock()+ owner, ok := q.leaseOwner[uuidString(instID)]+ q.mu.Unlock()+ if !ok {+ t.Fatalf("successor lease cleared after sup1's stale release — rotation fencing broken")+ }+ if owner == sup1Token {+ t.Fatalf("lease still held by sup1 token %q; successor never took over", sup1Token)+ }+}++func TestHubBacksOffOnFactoryError(t *testing.T) {+ q := newFakeHubQueries()+ instID := uuidFromString(t, "55555555-5555-5555-5555-555555555555")+ q.installations = []db.LarkInstallation{{ID: instID, Status: "active"}}++ factoryCalls := int32(0)+ factory := func(_ db.LarkInstallation) (EventConnector, error) {+ atomic.AddInt32(&factoryCalls, 1)+ return nil, errors.New("boom")+ }++ hub := NewHub(q, factory, nil, HubConfig{+ LeaseTTL: 500 * time.Millisecond,+ LeaseRenewInterval: 20 * time.Millisecond,+ PollInterval: 20 * time.Millisecond,+ MinBackoff: 5 * time.Millisecond,+ MaxBackoff: 20 * time.Millisecond,+ ResetBackoffAfter: 1 * time.Second,+ Logger: newDiscardLogger(),+ })++ ctx, cancel := context.WithCancel(context.Background())+ go hub.Run(ctx)++ // Let the supervisor retry under backoff. We want > 1 call to+ // prove the loop is alive but the increasing delay should keep+ // the rate sane.+ if !waitFor(200*time.Millisecond, func() bool { return atomic.LoadInt32(&factoryCalls) >= 2 }) {+ t.Fatalf("expected factory retries under backoff; got %d", atomic.LoadInt32(&factoryCalls))+ }+ calls := atomic.LoadInt32(&factoryCalls)+ cancel()+ hub.Wait()+ if calls > 200 {+ t.Fatalf("backoff appears broken: %d factory calls in 200ms", calls)+ }+}++// TestHubLeaseLossCancelsConnector pins the §4.4 ownership invariant.+// When another replica steals the lease, the renewer must cancel the+// connector's run context so the connector exits even if its wire I/O+// is currently blocked. Without that cancel, replica A could keep+// reading Lark events for an unbounded window while replica B already+// believes it is the sole owner — duplicate consumption, exactly what+// the lease is supposed to prevent.+func TestHubLeaseLossCancelsConnector(t *testing.T) {+ q := newFakeHubQueries()+ instID := uuidFromString(t, "66666666-6666-6666-6666-666666666666")+ q.installations = []db.LarkInstallation{{ID: instID, Status: "active"}}++ // fakeConnector default behavior blocks on ctx.Done — perfect for+ // "simulate a socket that never returns until we explicitly cancel+ // it" scenarios. We capture the ctx the supervisor handed it so we+ // can wait on its done channel directly.+ connCtxCh := make(chan context.Context, 1)+ conn := &fakeConnector{+ script: []func(ctx context.Context, emit EventEmitter) error{+ func(ctx context.Context, _ EventEmitter) error {+ connCtxCh <- ctx+ <-ctx.Done()+ return ctx.Err()+ },+ },+ }+ factory := func(_ db.LarkInstallation) (EventConnector, error) { return conn, nil }++ hub := NewHub(q, factory, nil, HubConfig{+ LeaseTTL: 500 * time.Millisecond,+ LeaseRenewInterval: 20 * time.Millisecond,+ PollInterval: 1 * time.Hour, // disable sweep noise; we drive lease state by hand.+ MinBackoff: 5 * time.Millisecond,+ MaxBackoff: 20 * time.Millisecond,+ ResetBackoffAfter: 10 * time.Second,+ Logger: newDiscardLogger(),+ })++ ctx, cancel := context.WithCancel(context.Background())+ defer func() { cancel(); hub.Wait() }()+ go hub.Run(ctx)++ // Wait for the supervisor to hand the connector a run context.+ var runCtx context.Context+ select {+ case runCtx = <-connCtxCh:+ case <-time.After(500 * time.Millisecond):+ t.Fatalf("connector never started")+ }++ // Simulate lease theft: rewrite the lease row to point at another+ // replica with a fresh expiry. The next renewal CAS will fail+ // because the token no longer matches our nodeID, the renewer+ // returns leased=false, and (with the fix) cancels the run ctx.+ q.presetLease(instID, "thief-replica", time.Now().Add(10*time.Second))++ select {+ case <-runCtx.Done():+ // Expected: renewer cancelled runCtx within a few renewal ticks.+ case <-time.After(500 * time.Millisecond):+ t.Fatalf("renewer did not cancel run ctx after lease loss")+ }+}++// TestHubEmitReturnsDispatchResultAndError pins the connector-facing+// emit contract: the supervisor's emit shim wraps the Dispatcher and+// surfaces both the typed DispatchResult and any infra error so the+// real Lark connector can post the right outbound (binding card,+// offline card, etc.) and react to infra failures.+func TestHubEmitReturnsDispatchResultAndError(t *testing.T) {+ q := newFakeHubQueries()+ instID := uuidFromString(t, "77777777-7777-7777-7777-777777777777")+ q.installations = []db.LarkInstallation{{ID: instID, Status: "active"}}++ // Capture what emit returned on the first invocation so the+ // connector goroutine can stash it for the test.+ var (+ gotRes DispatchResult+ gotErr error+ gotMu sync.Mutex+ )+ emitDone := make(chan struct{})++ conn := &fakeConnector{+ script: []func(ctx context.Context, emit EventEmitter) error{+ func(ctx context.Context, emit EventEmitter) error {+ res, err := emit(ctx, InboundMessage{+ EventID: "evt-1",+ EventType: "im.message.receive_v1",+ })+ gotMu.Lock()+ gotRes = res+ gotErr = err+ gotMu.Unlock()+ close(emitDone)+ <-ctx.Done()+ return ctx.Err()+ },+ },+ }+ factory := func(_ db.LarkInstallation) (EventConnector, error) { return conn, nil }++ // No dispatcher wired -> emit must return ErrDispatcherNotConfigured.+ // The point is the error surfaces back to the connector instead of+ // being silently dropped at the Hub.+ hub := NewHub(q, factory, nil, HubConfig{+ LeaseTTL: 500 * time.Millisecond,+ LeaseRenewInterval: 20 * time.Millisecond,+ PollInterval: 1 * time.Hour,+ MinBackoff: 5 * time.Millisecond,+ MaxBackoff: 20 * time.Millisecond,+ ResetBackoffAfter: 10 * time.Second,+ Logger: newDiscardLogger(),+ })++ ctx, cancel := context.WithCancel(context.Background())+ defer func() { cancel(); hub.Wait() }()+ go hub.Run(ctx)++ select {+ case <-emitDone:+ case <-time.After(500 * time.Millisecond):+ t.Fatalf("connector never invoked emit")+ }++ gotMu.Lock()+ defer gotMu.Unlock()+ if !errors.Is(gotErr, ErrDispatcherNotConfigured) {+ t.Fatalf("emit should propagate dispatcher errors; got %v", gotErr)+ }+ if gotRes.Outcome != "" {+ t.Fatalf("emit should not invent an outcome on dispatcher error; got %q", gotRes.Outcome)+ }+}++// TestHubReleaseLeaseBoundedByTimeout pins the shutdown-safety+// invariant: a frozen DB pool must NOT keep the supervisor blocked+// on releaseLease past the configured LeaseReleaseTimeout. Without+// the bound, ctx.Background()-rooted release calls could hang+// forever on a stalled pool, dragging out process shutdown well+// past the operator's expected drain budget.+func TestHubReleaseLeaseBoundedByTimeout(t *testing.T) {+ q := newFakeHubQueries()+ q.releaseBlock = make(chan struct{}) // never closed; release always sees ctx.Done+ instID := uuidFromString(t, "88888888-8888-8888-8888-888888888888")+ q.installations = []db.LarkInstallation{{ID: instID, Status: "active"}}++ conn := &fakeConnector{}+ factory := func(_ db.LarkInstallation) (EventConnector, error) { return conn, nil }++ releaseTimeout := 50 * time.Millisecond+ hub := NewHub(q, factory, nil, HubConfig{+ LeaseTTL: 500 * time.Millisecond,+ LeaseRenewInterval: 20 * time.Millisecond,+ PollInterval: 1 * time.Hour,+ MinBackoff: 5 * time.Millisecond,+ MaxBackoff: 20 * time.Millisecond,+ ResetBackoffAfter: 10 * time.Second,+ LeaseReleaseTimeout: releaseTimeout,+ ShutdownTimeout: 2 * time.Second, // generous; we want WaitWithTimeout to succeed+ Logger: newDiscardLogger(),+ })++ ctx, cancel := context.WithCancel(context.Background())+ go hub.Run(ctx)++ if !waitFor(500*time.Millisecond, func() bool { return conn.Runs() >= 1 }) {+ cancel()+ hub.Wait()+ t.Fatalf("expected connector to start; runs=%d", conn.Runs())+ }++ start := time.Now()+ cancel()+ // WaitWithTimeout MUST return true: the bound on releaseLease+ // has to let the supervisor unwind even though our fake release+ // never returns on its own.+ if !hub.WaitWithTimeout(2 * time.Second) {+ t.Fatalf("supervisor stuck despite bounded release; lease release timeout did not fire")+ }+ elapsed := time.Since(start)++ // Sanity bound: shutdown must complete in roughly the release+ // timeout plus a small jitter, NOT seconds. If the bound regressed+ // (e.g. someone reintroduced ctx.Background() without a deadline),+ // this assertion catches it.+ if elapsed > 500*time.Millisecond {+ t.Fatalf("shutdown took %s; expected ≈ %s + slack", elapsed, releaseTimeout)+ }++ q.mu.Lock()+ gotErr := q.releaseObservedCtxErr+ q.mu.Unlock()+ if !errors.Is(gotErr, context.DeadlineExceeded) {+ t.Fatalf("release should have observed DeadlineExceeded from its bounded ctx; got %v", gotErr)+ }+}++// TestHubWaitWithTimeoutReturnsTrueWhenSupervisorsExit covers the+// happy path: everything stops cleanly within the deadline, so the+// caller can proceed without logging a timeout warning.+func TestHubWaitWithTimeoutReturnsTrueWhenSupervisorsExit(t *testing.T) {+ q := newFakeHubQueries()+ instID := uuidFromString(t, "99999999-9999-9999-9999-999999999999")+ q.installations = []db.LarkInstallation{{ID: instID, Status: "active"}}++ conn := &fakeConnector{}+ factory := func(_ db.LarkInstallation) (EventConnector, error) { return conn, nil }++ hub := NewHub(q, factory, nil, HubConfig{+ LeaseTTL: 500 * time.Millisecond,+ LeaseRenewInterval: 20 * time.Millisecond,+ PollInterval: 1 * time.Hour,+ MinBackoff: 5 * time.Millisecond,+ MaxBackoff: 20 * time.Millisecond,+ ResetBackoffAfter: 10 * time.Second,+ Logger: newDiscardLogger(),+ })++ ctx, cancel := context.WithCancel(context.Background())+ go hub.Run(ctx)++ if !waitFor(500*time.Millisecond, func() bool { return conn.Runs() >= 1 }) {+ cancel()+ hub.Wait()+ t.Fatalf("expected connector to start; runs=%d", conn.Runs())+ }++ cancel()+ if !hub.WaitWithTimeout(1 * time.Second) {+ t.Fatalf("WaitWithTimeout returned false despite supervisor exiting promptly")+ }+}++// TestHubWaitWithTimeoutReturnsFalseWhenSupervisorStuck pins the+// bound on the join itself: if a (future real) connector or release+// path ignores ctx and refuses to exit, WaitWithTimeout MUST return+// false so main.go can log + proceed with shutdown rather than block+// the process forever.+func TestHubWaitWithTimeoutReturnsFalseWhenSupervisorStuck(t *testing.T) {+ q := newFakeHubQueries()+ q.releaseBlock = make(chan struct{}) // never closed+ instID := uuidFromString(t, "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa")+ q.installations = []db.LarkInstallation{{ID: instID, Status: "active"}}++ conn := &fakeConnector{}+ factory := func(_ db.LarkInstallation) (EventConnector, error) { return conn, nil }++ // LeaseReleaseTimeout > ShutdownTimeout so the release is still+ // blocked when the join deadline expires. This pins the "join+ // deadline trips before the supervisor unwinds" branch.+ hub := NewHub(q, factory, nil, HubConfig{+ LeaseTTL: 500 * time.Millisecond,+ LeaseRenewInterval: 20 * time.Millisecond,+ PollInterval: 1 * time.Hour,+ MinBackoff: 5 * time.Millisecond,+ MaxBackoff: 20 * time.Millisecond,+ ResetBackoffAfter: 10 * time.Second,+ LeaseReleaseTimeout: 5 * time.Second,+ Logger: newDiscardLogger(),+ })++ ctx, cancel := context.WithCancel(context.Background())+ go hub.Run(ctx)++ if !waitFor(500*time.Millisecond, func() bool { return conn.Runs() >= 1 }) {+ cancel()+ hub.Wait() // unbounded fallback; test will time out instead of hanging+ t.Fatalf("expected connector to start; runs=%d", conn.Runs())+ }++ cancel()+ if hub.WaitWithTimeout(50 * time.Millisecond) {+ t.Fatalf("WaitWithTimeout returned true while release was still blocked")+ }++ // Unblock the release so the supervisor can finally exit and the+ // test doesn't leak a goroutine.+ close(q.releaseBlock)+ hub.Wait()+}++// TestHubConfigDefaultsCoverShutdownKnobs documents that callers+// that omit the new shutdown knobs still get sensible defaults+// (matching the behavior router.go relies on by passing HubConfig{}).+// If the defaults regress to zero, releaseLease would derive a+// 0-deadline ctx that fails instantly — the real symptom would be+// "release lease failed: context deadline exceeded" warnings on+// every shutdown.+func TestHubConfigDefaultsCoverShutdownKnobs(t *testing.T) {+ c := HubConfig{}.withDefaults()+ if c.LeaseReleaseTimeout <= 0 {+ t.Fatalf("LeaseReleaseTimeout default must be > 0; got %s", c.LeaseReleaseTimeout)+ }+ if c.ShutdownTimeout <= 0 {+ t.Fatalf("ShutdownTimeout default must be > 0; got %s", c.ShutdownTimeout)+ }+}++// waitFor polls cond until it returns true or the deadline is reached.+// Returns true on success. Tests use this instead of time.Sleep so they+// remain robust on slow CI runners without slowing fast ones down.+func waitFor(timeout time.Duration, cond func() bool) bool {+ deadline := time.Now().Add(timeout)+ for time.Now().Before(deadline) {+ if cond() {+ return true+ }+ time.Sleep(time.Millisecond)+ }+ return cond()+}++// slowReplier blocks Reply for the configured duration unless the ctx+// fires first. Used to prove the Hub's reply-off-critical-path+// invariant: a Reply that exceeds ReplyTimeout MUST get its ctx+// cancelled instead of running unbounded.+type slowReplier struct {+ delay time.Duration+ startCh chan struct{}+ finishCh chan struct{}+ mu sync.Mutex+ callCount int+ lastCtxErr error // ctx.Err() observed when Reply returned+}++func newSlowReplier(delay time.Duration) *slowReplier {+ return &slowReplier{+ delay: delay,+ startCh: make(chan struct{}, 16),+ finishCh: make(chan struct{}, 16),+ }+}++func (s *slowReplier) Reply(ctx context.Context, _ db.LarkInstallation, _ InboundMessage, _ DispatchResult) {+ s.mu.Lock()+ s.callCount+++ s.mu.Unlock()+ select {+ case s.startCh <- struct{}{}:+ default:+ }+ select {+ case <-time.After(s.delay):+ case <-ctx.Done():+ }+ s.mu.Lock()+ s.lastCtxErr = ctx.Err()+ s.mu.Unlock()+ select {+ case s.finishCh <- struct{}{}:+ default:+ }+}++func (s *slowReplier) calls() int {+ s.mu.Lock()+ defer s.mu.Unlock()+ return s.callCount+}++func (s *slowReplier) ctxErr() error {+ s.mu.Lock()+ defer s.mu.Unlock()+ return s.lastCtxErr+}++// TestHubScheduleReplyReturnsImmediately verifies the core invariant+// behind the OutcomeReplier refactor: a slow replier MUST NOT block+// the dispatch caller. handleEvent is on the ACK critical path — the+// connector ACKs as soon as it returns — so coupling it to outbound+// Lark HTTP would let any slow card-send stall ACK past Lark's 3s+// deadline. This test puts a 10s sleep in the replier and asserts the+// scheduling call still returns in < 50ms.+func TestHubScheduleReplyReturnsImmediately(t *testing.T) {+ t.Parallel()+ rep := newSlowReplier(10 * time.Second)+ hub := NewHub(nil, nil, nil, HubConfig{+ ReplyTimeout: 100 * time.Millisecond,+ Logger: newDiscardLogger(),+ })+ hub.SetOutcomeReplier(rep)++ start := time.Now()+ hub.scheduleReply(db.LarkInstallation{}, InboundMessage{EventID: "e1"},+ DispatchResult{Outcome: OutcomeNeedsBinding}, newDiscardLogger())+ elapsed := time.Since(start)++ if elapsed > 50*time.Millisecond {+ t.Fatalf("scheduleReply took %s; ACK critical path would be blocked by outbound HTTP", elapsed)+ }++ // The replier should still be in flight — proves it really did+ // detach into a goroutine.+ select {+ case <-rep.startCh:+ // good — Reply was invoked async+ case <-time.After(500 * time.Millisecond):+ t.Fatal("detached replier never ran")+ }++ // Drain the timeout-bounded reply so the test doesn't leak goroutines.+ if !hub.WaitWithTimeout(1 * time.Second) {+ t.Fatal("reply goroutine did not exit after ReplyTimeout fired")+ }++ if !errors.Is(rep.ctxErr(), context.DeadlineExceeded) {+ t.Fatalf("replier ctx.Err() = %v; want DeadlineExceeded", rep.ctxErr())+ }+}++// TestHubReplyTimeoutCancelsHungReplier pins the bound on the detached+// reply: a replier that ignores ctx (or its outbound HTTP that hasn't+// noticed yet) MUST be cancelled at ReplyTimeout. The test gives the+// replier a deliberately long sleep and a short timeout, then asserts+// the reply goroutine exits within roughly the timeout — not the sleep.+func TestHubReplyTimeoutCancelsHungReplier(t *testing.T) {+ t.Parallel()+ timeout := 80 * time.Millisecond+ rep := newSlowReplier(10 * time.Second)+ hub := NewHub(nil, nil, nil, HubConfig{+ ReplyTimeout: timeout,+ Logger: newDiscardLogger(),+ })+ hub.SetOutcomeReplier(rep)++ start := time.Now()+ hub.scheduleReply(db.LarkInstallation{}, InboundMessage{EventID: "e2"},+ DispatchResult{Outcome: OutcomeAgentOffline}, newDiscardLogger())++ select {+ case <-rep.finishCh:+ case <-time.After(1 * time.Second):+ t.Fatal("replier never exited; ReplyTimeout did not fire")+ }+ elapsed := time.Since(start)++ // Sanity bound: shutdown must complete in roughly timeout + jitter.+ if elapsed > 500*time.Millisecond {+ t.Fatalf("replier exit took %s; expected ≈ %s", elapsed, timeout)+ }+ if !errors.Is(rep.ctxErr(), context.DeadlineExceeded) {+ t.Fatalf("replier should observe DeadlineExceeded; got %v", rep.ctxErr())+ }+ hub.Wait()+}++// TestHubWaitDrainsInFlightReplies verifies that Hub.Wait (and+// WaitWithTimeout) joins on the replier goroutines, not just the+// supervisor goroutines. Without this, shutdown could close the+// process while a binding-card send is still in flight — the user+// gets no card, no log entry, and the binding token they were going+// to receive is orphaned with no observability.+func TestHubWaitDrainsInFlightReplies(t *testing.T) {+ t.Parallel()+ rep := newSlowReplier(30 * time.Millisecond) // shorter than ReplyTimeout+ hub := NewHub(nil, nil, nil, HubConfig{+ ReplyTimeout: 1 * time.Second,+ Logger: newDiscardLogger(),+ })+ hub.SetOutcomeReplier(rep)++ hub.scheduleReply(db.LarkInstallation{}, InboundMessage{EventID: "e3"},+ DispatchResult{Outcome: OutcomeNeedsBinding}, newDiscardLogger())++ // Wait should block until the reply finishes its 30ms work.+ start := time.Now()+ hub.Wait()+ elapsed := time.Since(start)++ if elapsed < 20*time.Millisecond {+ t.Fatalf("Wait returned in %s; should have blocked until reply completed", elapsed)+ }+ if rep.calls() != 1 {+ t.Fatalf("reply call count = %d; want 1", rep.calls())+ }+ // Reply finished naturally (sleep returned), not via cancellation.+ if rep.ctxErr() != nil {+ t.Errorf("reply ctxErr = %v; want nil (slept normally)", rep.ctxErr())+ }+}++// TestHubNoopReplierInlineNoGoroutine verifies the optimisation: the+// noop replier (used when outbound APIClient isn't configured) runs+// inline, not under a goroutine. This avoids the cost of a goroutine+// per inbound event on a deployment that hasn't wired outbound replies+// yet. Indirectly proven by observing replyWg is not bumped (Wait+// returns immediately without any reply goroutine to drain).+func TestHubNoopReplierInlineNoGoroutine(t *testing.T) {+ t.Parallel()+ hub := NewHub(nil, nil, nil, HubConfig{+ Logger: newDiscardLogger(),+ })+ // hub.replier defaults to noop. Call scheduleReply many times — if+ // it spawned goroutines, Wait would wait at least until those+ // goroutines schedule, but with the fast-path it must return+ // instantly.+ for i := 0; i < 1000; i++ {+ hub.scheduleReply(db.LarkInstallation{}, InboundMessage{EventID: "e"},+ DispatchResult{Outcome: OutcomeNeedsBinding}, newDiscardLogger())+ }+ done := make(chan struct{})+ go func() { hub.Wait(); close(done) }()+ select {+ case <-done:+ case <-time.After(100 * time.Millisecond):+ t.Fatal("Wait should return immediately when no goroutine replies were scheduled")+ }+}++// TestHubReplyTimeoutDefaultIsUnder3s pins the value the production+// path uses — Lark requires ACK within 3 seconds, and the replier+// runs ON TOP of the dispatch latency, so it must complete strictly+// under 3s even if dispatch took 500ms. Defaulting to 2.5s leaves+// headroom both for outbound HTTP and for shutdown to drain replies+// without hitting the broader ShutdownTimeout.+func TestHubReplyTimeoutDefaultIsUnder3s(t *testing.T) {+ t.Parallel()+ c := HubConfig{}.withDefaults()+ if c.ReplyTimeout <= 0 {+ t.Fatalf("ReplyTimeout default must be > 0; got %s", c.ReplyTimeout)+ }+ if c.ReplyTimeout >= 3*time.Second {+ t.Fatalf("ReplyTimeout default %s is too close to Lark's 3s ACK deadline; outbound HTTP would race ACK", c.ReplyTimeout)+ }+}++// TestHubACKNotBlockedByOutboundReply proves the full integrated+// invariant: even when the OutcomeReplier hangs for far longer than+// the Lark ACK deadline, the connector's data-frame ACK still lands+// on the wire promptly. This is the end-to-end version of the unit+// test above, exercising connector -> Hub.handleEvent -> scheduleReply+// against a fakeWSConn so we can observe the actual binary ACK frame+// timing.+//+// Construct a dispatcher manually that returns OutcomeNeedsBinding+// (the outcome most prone to expensive outbound work — token mint ++// card send). Wire a slowReplier that sleeps 5s. Push one event.+// Assert: an ACK frame appears in conn.writes within 500ms (well+// under Lark's 3s budget).+func TestHubACKNotBlockedByOutboundReply(t *testing.T) {+ t.Parallel()++ conn := newFakeWSConn()+ decoder := FrameDecoderFunc(func(payload []byte, _ db.LarkInstallation) (InboundMessage, bool, error) {+ return InboundMessage{EventID: string(payload)}, true, nil+ })+ c := quietConnector(t, conn, decoder, time.Hour) // disable ping++ // Slow replier that would block ACK if the critical path coupling+ // regressed. 5s sleep, ReplyTimeout 2.5s — replier must be+ // cancelled at ~2.5s and the ACK must NOT have waited for it.+ rep := newSlowReplier(5 * time.Second)+ hub := NewHub(nil, nil, nil, HubConfig{+ ReplyTimeout: 2500 * time.Millisecond,+ Logger: newDiscardLogger(),+ })+ hub.SetOutcomeReplier(rep)++ emit := func(ctx context.Context, msg InboundMessage) (DispatchResult, error) {+ // Simulate the dispatcher's "successful binding-needed" verdict+ // without standing up the full Dispatcher (concrete struct ++ // service deps). The async reply is the only behaviour under+ // test here, and scheduleReply is what the real handleEvent+ // hands to the replier.+ res := DispatchResult{+ Outcome: OutcomeNeedsBinding,+ SenderOpenID: "ou_user_42",+ }+ hub.scheduleReply(db.LarkInstallation{}, msg, res, newDiscardLogger())+ return res, nil+ }++ ctx, cancel := context.WithCancel(context.Background())+ defer cancel()+ done := make(chan error, 1)+ go func() {+ done <- c.Run(ctx, db.LarkInstallation{AppID: "test_app"}, emit)+ }()++ start := time.Now()+ pushDataFrame(conn, []byte("evt-binding"), "om-binding")++ // The data-frame ACK MUST appear well under Lark's 3s budget.+ if !waitFor(500*time.Millisecond, func() bool {+ for _, w := range conn.snapshot() {+ f, err := UnmarshalFrame(w)+ if err != nil {+ continue+ }+ if f.Method == FrameMethodData && bytes.Contains(f.Payload, []byte(`"code":200`)) {+ return true+ }+ }+ return false+ }) {+ t.Fatalf("data-frame ACK did not land within 500ms; outbound reply blocked the critical path (replier still running? %v)", rep.calls() == 1)+ }+ ackLatency := time.Since(start)+ if ackLatency >= 3*time.Second {+ t.Fatalf("ACK landed in %s, past Lark's 3s deadline", ackLatency)+ }++ // Verify the replier was indeed launched (proves we didn't accidentally+ // short-circuit it).+ select {+ case <-rep.startCh:+ case <-time.After(200 * time.Millisecond):+ t.Fatal("replier never ran; the reply path is silently broken")+ }++ cancel()+ <-done+ hub.WaitWithTimeout(5 * time.Second)+}diff --git a/server/internal/integrations/lark/installation.go b/server/internal/integrations/lark/installation.gonew file mode 100644index 0000000000..3e1def9deb--- /dev/null+++ b/server/internal/integrations/lark/installation.go@@ -0,0 +1,157 @@+package lark++import (+ "context"+ "errors"+ "fmt"++ "github.com/jackc/pgx/v5"+ "github.com/jackc/pgx/v5/pgtype"+ "github.com/multica-ai/multica/server/internal/util/secretbox"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++// InstallationParams is the input shape RegistrationService assembles+// after a successful device-flow scan-to-install. The credentials are+// supplied here as plaintext — encryption happens inside+// InstallationService.Upsert via the supplied *secretbox.Box, so+// callers never see (and therefore cannot leak) the ciphertext that+// lands in the DB.+type InstallationParams struct {+ WorkspaceID pgtype.UUID+ AgentID pgtype.UUID+ AppID string+ AppSecret string // plaintext; encrypted at the service boundary+ TenantKey string // optional, "" treated as NULL+ BotOpenID string+ InstallerUserID pgtype.UUID+}++// InstallationService creates, refreshes and revokes per-agent Lark+// installations. It owns the at-rest encryption of `app_secret` so+// that no caller (and no test fixture) can accidentally insert a row+// with plaintext credentials — the only path to writing+// lark_installation goes through here.+type InstallationService struct {+ queries *db.Queries+ box *secretbox.Box+}++// NewInstallationService binds the service to a queries handle and a+// secretbox keyed for at-rest encryption. The box MUST be non-nil; we+// refuse to fall back to plaintext storage even in test or dev+// configurations because that is exactly the regression the §4.4+// requirement guards against.+func NewInstallationService(queries *db.Queries, box *secretbox.Box) (*InstallationService, error) {+ if box == nil {+ return nil, errors.New("lark: InstallationService requires a non-nil secretbox.Box")+ }+ return &InstallationService{queries: queries, box: box}, nil+}++// Upsert creates a new installation or refreshes an existing one in+// place (matching on the (workspace_id, agent_id) UNIQUE). Re-install+// resets status to 'active' but does NOT touch the WS lease — that is+// the hub's concern, not ours. The returned row is the post-write+// state; the encrypted secret column is included for completeness but+// callers SHOULD NOT log or persist it elsewhere.+func (s *InstallationService) Upsert(ctx context.Context, p InstallationParams) (db.LarkInstallation, error) {+ if err := validateInstallationParams(p); err != nil {+ return db.LarkInstallation{}, err+ }+ sealed, err := s.box.Seal([]byte(p.AppSecret))+ if err != nil {+ return db.LarkInstallation{}, fmt.Errorf("encrypt app_secret: %w", err)+ }+ return s.queries.UpsertLarkInstallation(ctx, db.UpsertLarkInstallationParams{+ WorkspaceID: p.WorkspaceID,+ AgentID: p.AgentID,+ AppID: p.AppID,+ AppSecretEncrypted: sealed,+ TenantKey: textOrNull(p.TenantKey),+ BotOpenID: p.BotOpenID,+ InstallerUserID: p.InstallerUserID,+ })+}++// Revoke flips status to 'revoked' so the WS hub tears the connection+// down on its next sweep and the dispatcher drops any in-flight+// events. The row is preserved (no DELETE) so audit history remains+// queryable; a subsequent re-install via Upsert flips status back to+// 'active' atomically.+func (s *InstallationService) Revoke(ctx context.Context, id pgtype.UUID) error {+ return s.queries.SetLarkInstallationStatus(ctx, db.SetLarkInstallationStatusParams{+ ID: id,+ Status: string(InstallationRevoked),+ })+}++// DecryptAppSecret returns the plaintext app_secret for the supplied+// installation row. Used by the WebSocket hub when it needs to+// authenticate against the Lark API on behalf of an installation; do+// NOT use this for read-only display surfaces. The plaintext value+// must never round-trip through an HTTP response.+func (s *InstallationService) DecryptAppSecret(inst db.LarkInstallation) (string, error) {+ plain, err := s.box.Open(inst.AppSecretEncrypted)+ if err != nil {+ return "", fmt.Errorf("decrypt app_secret: %w", err)+ }+ return string(plain), nil+}++// GetInWorkspace is the workspace-scoped lookup helper. Internal+// callers (Dispatcher) use GetLarkInstallationByAppID directly because+// the event payload only carries app_id; HTTP-side callers always+// know the workspace and should use this so a forged installation_id+// from a different workspace returns NotFound instead of leaking+// existence.+func (s *InstallationService) GetInWorkspace(ctx context.Context, id, workspaceID pgtype.UUID) (db.LarkInstallation, error) {+ row, err := s.queries.GetLarkInstallationInWorkspace(ctx, db.GetLarkInstallationInWorkspaceParams{+ ID: id,+ WorkspaceID: workspaceID,+ })+ if err != nil {+ if errors.Is(err, pgx.ErrNoRows) {+ return db.LarkInstallation{}, ErrInstallationNotFound+ }+ return db.LarkInstallation{}, err+ }+ return row, nil+}++// ListByWorkspace returns every installation rooted at the workspace,+// active and revoked, oldest first. The status column lets the UI+// distinguish "wired up" from "torn down but kept for audit".+func (s *InstallationService) ListByWorkspace(ctx context.Context, workspaceID pgtype.UUID) ([]db.LarkInstallation, error) {+ return s.queries.ListLarkInstallationsByWorkspace(ctx, workspaceID)+}++// ErrInstallationNotFound surfaces "no row matches in this workspace"+// — used by the HTTP layer to return 404. Distinct from a plain+// pgx.ErrNoRows so handlers do not need to import pgx.+var ErrInstallationNotFound = errors.New("lark installation not found")++func validateInstallationParams(p InstallationParams) error {+ switch {+ case !p.WorkspaceID.Valid:+ return errors.New("workspace_id is required")+ case !p.AgentID.Valid:+ return errors.New("agent_id is required")+ case !p.InstallerUserID.Valid:+ return errors.New("installer_user_id is required")+ case p.AppID == "":+ return errors.New("app_id is required")+ case p.AppSecret == "":+ return errors.New("app_secret is required")+ case p.BotOpenID == "":+ return errors.New("bot_open_id is required")+ }+ return nil+}++func textOrNull(s string) pgtype.Text {+ if s == "" {+ return pgtype.Text{}+ }+ return pgtype.Text{String: s, Valid: true}+}diff --git a/server/internal/integrations/lark/issue_command.go b/server/internal/integrations/lark/issue_command.gonew file mode 100644index 0000000000..840ed60732--- /dev/null+++ b/server/internal/integrations/lark/issue_command.go@@ -0,0 +1,75 @@+package lark++import "strings"++// issueCommandPrefix is the literal command token. We match exactly —+// `/Issue` or `/ISSUE` do NOT trigger creation. The case sensitivity+// is product-intentional: it avoids accidentally promoting messages+// that mention "/issue" inline in a sentence.+const issueCommandPrefix = "/issue"++// parseIssueCommand extracts an /issue command from a chat-message body.+// It returns (cmd, true) when the message qualifies and the caller+// should dispatch to IssueService.Create; (nil, false) when the body+// is not an issue command. The bool is redundant when cmd != nil but+// makes call sites easier to read.+//+// Recognized shapes (matching MUL-2671 §2.3):+//+// - `/issue <title>` → Title = "<title>", Description = ""+// - `/issue <title>\n<rest...>` → Title = "<title>", Description = "<rest>"+// (multi-line: first line is title, the+// remainder, joined back with newlines,+// becomes description)+// - `/issue` (alone, no title) → Title = "", Description = ""+// (the caller is expected to fall back+// to the previous user message; the+// parser does not do that lookup+// itself because it has no DB access)+//+// Only the first non-empty line is considered: a message body that+// begins with blank lines and then `/issue ...` still qualifies. A+// body whose first non-empty line is anything other than the literal+// prefix is not an issue command, even if `/issue` appears later.+func parseIssueCommand(body string) (*IssueCommand, bool) {+ lines := strings.Split(body, "\n")++ // Skip leading blank lines to find the first content line. A user+ // who copy-pastes from a doc and ends up with a leading newline+ // should not have their command silently ignored.+ firstIdx := -1+ for i, line := range lines {+ if strings.TrimSpace(line) != "" {+ firstIdx = i+ break+ }+ }+ if firstIdx == -1 {+ return nil, false+ }++ first := lines[firstIdx]+ trimmed := strings.TrimLeft(first, " \t")+ if !strings.HasPrefix(trimmed, issueCommandPrefix) {+ return nil, false+ }++ // What follows the prefix on the same line must be either the end+ // of the line or a whitespace character. This rejects words like+ // "/issuetracker" — `/issue` must be a token, not a prefix of one.+ rest := trimmed[len(issueCommandPrefix):]+ if rest != "" {+ r0 := rest[0]+ if r0 != ' ' && r0 != '\t' {+ return nil, false+ }+ }++ title := strings.TrimSpace(rest)+ description := ""+ if firstIdx+1 < len(lines) {+ description = strings.TrimRight(strings.Join(lines[firstIdx+1:], "\n"), " \t\n")+ }++ return &IssueCommand{Title: title, Description: description}, true+}diff --git a/server/internal/integrations/lark/issue_command_test.go b/server/internal/integrations/lark/issue_command_test.gonew file mode 100644index 0000000000..1212378b5c--- /dev/null+++ b/server/internal/integrations/lark/issue_command_test.go@@ -0,0 +1,137 @@+package lark++import "testing"++func TestParseIssueCommand(t *testing.T) {+ tests := []struct {+ name string+ body string+ wantMatch bool+ wantTitle string+ wantDescrip string+ }{+ {+ name: "non command body",+ body: "hello world",+ wantMatch: false,+ },+ {+ name: "empty body",+ body: "",+ wantMatch: false,+ },+ {+ name: "issue mentioned mid-sentence does not match",+ body: "please use /issue to file a ticket",+ wantMatch: false,+ },+ {+ name: "wrong case rejected",+ body: "/Issue something",+ wantMatch: false,+ },+ {+ name: "prefix-of-token rejected",+ body: "/issuetracker my title",+ wantMatch: false,+ },+ {+ name: "title only",+ body: "/issue fix login redirect",+ wantMatch: true,+ wantTitle: "fix login redirect",+ },+ {+ name: "title and description",+ body: "/issue fix login redirect\nuser is bounced back to landing",+ wantMatch: true,+ wantTitle: "fix login redirect",+ wantDescrip: "user is bounced back to landing",+ },+ {+ name: "multi-line description preserved",+ body: "/issue title\nline one\nline two",+ wantMatch: true,+ wantTitle: "title",+ wantDescrip: "line one\nline two",+ },+ {+ name: "leading blank lines tolerated",+ body: "\n\n/issue lazy formatter",+ wantMatch: true,+ wantTitle: "lazy formatter",+ },+ {+ name: "command alone has no title",+ body: "/issue",+ wantMatch: true,+ wantTitle: "",+ },+ {+ name: "command with trailing whitespace alone has no title",+ body: "/issue ",+ wantMatch: true,+ wantTitle: "",+ },+ {+ name: "tab separator accepted",+ body: "/issue\ttabby",+ wantMatch: true,+ wantTitle: "tabby",+ },+ {+ name: "trailing blank lines trimmed from description",+ body: "/issue title\nbody\n\n\n",+ wantMatch: true,+ wantTitle: "title",+ wantDescrip: "body",+ },+ {+ name: "lines after a non-command first line are not parsed",+ body: "hello\n/issue not here",+ wantMatch: false,+ },+ }++ for _, tc := range tests {+ t.Run(tc.name, func(t *testing.T) {+ cmd, ok := parseIssueCommand(tc.body)+ if ok != tc.wantMatch {+ t.Fatalf("match=%v want %v (cmd=%+v)", ok, tc.wantMatch, cmd)+ }+ if !tc.wantMatch {+ if cmd != nil {+ t.Fatalf("expected nil command, got %+v", cmd)+ }+ return+ }+ if cmd.Title != tc.wantTitle {+ t.Errorf("title=%q want %q", cmd.Title, tc.wantTitle)+ }+ if cmd.Description != tc.wantDescrip {+ t.Errorf("description=%q want %q", cmd.Description, tc.wantDescrip)+ }+ })+ }+}++func TestTitleFromPreviousMessage(t *testing.T) {+ tests := []struct {+ name string+ body string+ want string+ }{+ {name: "plain message", body: "fix the bug", want: "fix the bug"},+ {name: "previous was /issue command, use its title", body: "/issue prior title", want: "prior title"},+ {name: "multi-line plain takes first line", body: "first line\nsecond line", want: "first line"},+ {name: "blank lines skipped", body: "\n\nactual line", want: "actual line"},+ {name: "all whitespace returns empty", body: " \n\t\n", want: ""},+ }+ for _, tc := range tests {+ t.Run(tc.name, func(t *testing.T) {+ if got := titleFromPreviousMessage(tc.body); got != tc.want {+ t.Errorf("titleFromPreviousMessage(%q) = %q, want %q", tc.body, got, tc.want)+ }+ })+ }+}diff --git a/server/internal/integrations/lark/markdown_detect.go b/server/internal/integrations/lark/markdown_detect.gonew file mode 100644index 0000000000..fa16c63ab8--- /dev/null+++ b/server/internal/integrations/lark/markdown_detect.go@@ -0,0 +1,61 @@+package lark++import (+ "regexp"+ "strings"+)++// markdownPatterns enumerate the syntax shapes we treat as evidence+// that the agent's reply is markdown rather than prose. Each pattern+// is intentionally conservative — better to false-positive (route+// plain text through the markdown card, which still renders fine)+// than to false-negative (leave `**bold**` characters visible in+// the user's transcript).+//+// Patterns are compiled once at package init; containsMarkdown is on+// the chat-reply hot path.+var markdownPatterns = []*regexp.Regexp{+ regexp.MustCompile("(?m)^#{1,6}[ \t]"), // headings: # H1, ###### H6+ regexp.MustCompile("(?m)^[ \t]*[-*+][ \t]"), // unordered list+ regexp.MustCompile("(?m)^[ \t]*\\d+\\.[ \t]"), // ordered list+ regexp.MustCompile("(?m)^>[ \t]"), // blockquote+ regexp.MustCompile("(?m)^[ \t]*(?:---|\\*\\*\\*|___)[ \t]*$"), // hr / thematic break+ regexp.MustCompile("\\*\\*[^*\\n]+\\*\\*"), // **bold**+ regexp.MustCompile("__[^_\\n]+__"), // __bold__+ regexp.MustCompile("(?m)^[ \t]*\\|.+\\|[ \t]*$"), // table row (must have | on both ends)+ regexp.MustCompile("\\[[^\\]\\n]+\\]\\([^)\\n]+\\)"), // [text](url) link / image+}++// containsMarkdown returns true when the body almost certainly+// contains markdown syntax that Lark's plain-text `msg_type=text`+// renderer would leave un-rendered (showing raw asterisks, hashes,+// pipes, etc.). On true, the chat-reply router upgrades to the+// schema-2.0 interactive card path so the user sees formatted text.+//+// Fast-path tokens (backtick, asterisk, pipe, hash, leading dash on+// any line) are checked first; only on a hit do we run the slower+// regex pass. Empty strings short-circuit to false so an empty+// agent reply does not get wrapped in a card.+func containsMarkdown(s string) bool {+ if s == "" {+ return false+ }+ // Fenced code block — strong markdown signal, cheap substring check.+ if strings.Contains(s, "```") {+ return true+ }+ // Inline code: only count `…` runs that look paired and contain a+ // non-space char. Bare backticks (e.g. quoting a single keystroke+ // in prose) shouldn't trigger.+ if i := strings.Index(s, "`"); i >= 0 {+ if j := strings.Index(s[i+1:], "`"); j > 0 {+ return true+ }+ }+ for _, re := range markdownPatterns {+ if re.MatchString(s) {+ return true+ }+ }+ return false+}diff --git a/server/internal/integrations/lark/markdown_detect_test.go b/server/internal/integrations/lark/markdown_detect_test.gonew file mode 100644index 0000000000..5413cf7aac--- /dev/null+++ b/server/internal/integrations/lark/markdown_detect_test.go@@ -0,0 +1,49 @@+package lark++import "testing"++// TestContainsMarkdown pins the heuristic the chat-reply router uses+// to decide between plain text (msg_type=text) and the schema-2.0+// markdown card. We deliberately bias toward false-positives — a+// short prose reply happening to contain a backtick or asterisk+// still renders fine inside the card. False-negatives are the+// expensive case: the user sees raw `**bold**` text.+func TestContainsMarkdown(t *testing.T) {+ t.Parallel()++ plain := []string{+ "",+ "Hello!",+ "sure, on it",+ "Hello, world. How are you?", // bare comma + period, no markdown+ "the build is green",+ "我已经创建了 issue MUL-42", // Chinese + dashed identifier (no `- ` line)+ }+ for _, s := range plain {+ if containsMarkdown(s) {+ t.Errorf("containsMarkdown(%q) = true; want false", s)+ }+ }++ markdown := []string{+ "# Heading",+ "## Second-level",+ "**bold** statement",+ "call __init__ then run",+ "- bullet one\n- bullet two",+ "1. first\n2. second",+ "> quoted line",+ "see [docs](https://example.com)",+ "run `make check` first",+ "```go\nfunc foo() {}\n```",+ "| col1 | col2 |\n|------|------|\n| a | b |",+ "---",+ " - indented bullet",+ "plain prose\nthen a `inline code`\nthen more prose",+ }+ for _, s := range markdown {+ if !containsMarkdown(s) {+ t.Errorf("containsMarkdown(%q) = false; want true", s)+ }+ }+}diff --git a/server/internal/integrations/lark/noop_connector.go b/server/internal/integrations/lark/noop_connector.gonew file mode 100644index 0000000000..5056dc4947--- /dev/null+++ b/server/internal/integrations/lark/noop_connector.go@@ -0,0 +1,66 @@+package lark++import (+ "context"+ "log/slog"++ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++// NoopConnector satisfies EventConnector by holding the run context+// open without dialing anything and without emitting any inbound+// events. It exists so the Hub can be wired into the boot path before+// the real Lark long-connection client lands: the lease lifecycle,+// supervisor / renewer goroutines, sweep + shutdown plumbing all run+// against a real DB, and the operator sees the Hub's "lease acquired"+// log lines once an installation exists — without the Hub silently+// retrying a half-finished real connector and looking like the wire+// protocol is broken when it has not been implemented yet.+//+// The next stage of the MVP (MUL-2671) replaces this with a connector+// that opens the actual Lark WebSocket long connection, decodes+// events, and calls emit. At that point the NoopConnectorFactory call+// site in router.go swaps to the real factory; the Hub itself does+// not change.+type NoopConnector struct {+ logger *slog.Logger+}++// NewNoopConnector returns a connector that blocks until the Hub+// cancels its run context. Logger may be nil; callers typically pass+// slog.Default.+func NewNoopConnector(logger *slog.Logger) *NoopConnector {+ if logger == nil {+ logger = slog.Default()+ }+ return &NoopConnector{logger: logger}+}++// Run blocks until ctx is cancelled and then returns nil. A nil return+// tells the Hub the connection ended cleanly (no backoff retry storm+// on shutdown / lease loss). Because Run never errors and runs for as+// long as the lease is held, the Hub's "uptime >= ResetBackoffAfter"+// branch will reset the backoff on every supervisor cycle — which is+// the right thing for a placeholder.+func (c *NoopConnector) Run(ctx context.Context, inst db.LarkInstallation, _ EventEmitter) error {+ c.logger.Info("lark noop connector: holding lease (real long-conn not yet implemented)",+ "installation_id", uuidString(inst.ID),+ "app_id", inst.AppID,+ )+ <-ctx.Done()+ c.logger.Info("lark noop connector: exiting on ctx cancel",+ "installation_id", uuidString(inst.ID),+ )+ return nil+}++// NoopConnectorFactory returns a ConnectorFactory that hands every+// installation a NoopConnector sharing the supplied logger. Used by+// the router during the bootstrap stage; replaced by the real+// connector factory once the wire-protocol implementation lands.+func NoopConnectorFactory(logger *slog.Logger) ConnectorFactory {+ c := NewNoopConnector(logger)+ return func(_ db.LarkInstallation) (EventConnector, error) {+ return c, nil+ }+}diff --git a/server/internal/integrations/lark/noop_connector_test.go b/server/internal/integrations/lark/noop_connector_test.gonew file mode 100644index 0000000000..aae221dfdf--- /dev/null+++ b/server/internal/integrations/lark/noop_connector_test.go@@ -0,0 +1,65 @@+package lark++import (+ "context"+ "io"+ "log/slog"+ "testing"+ "time"++ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++func TestNoopConnectorRunBlocksUntilContextCancel(t *testing.T) {+ t.Parallel()++ c := NewNoopConnector(slog.New(slog.NewTextHandler(io.Discard, nil)))+ ctx, cancel := context.WithCancel(context.Background())++ done := make(chan error, 1)+ go func() {+ done <- c.Run(ctx, db.LarkInstallation{}, func(context.Context, InboundMessage) (DispatchResult, error) {+ t.Errorf("noop connector must not emit events")+ return DispatchResult{}, nil+ })+ }()++ // The connector must NOT return while the ctx is live.+ select {+ case err := <-done:+ t.Fatalf("Run returned before ctx cancel: %v", err)+ case <-time.After(50 * time.Millisecond):+ }++ cancel()++ select {+ case err := <-done:+ if err != nil {+ t.Fatalf("Run returned non-nil error after cancel: %v", err)+ }+ case <-time.After(time.Second):+ t.Fatal("Run did not return within 1s of ctx cancel")+ }+}++func TestNoopConnectorFactoryReturnsSameConnector(t *testing.T) {+ t.Parallel()++ factory := NoopConnectorFactory(slog.New(slog.NewTextHandler(io.Discard, nil)))++ c1, err := factory(db.LarkInstallation{})+ if err != nil {+ t.Fatalf("factory call 1: %v", err)+ }+ c2, err := factory(db.LarkInstallation{})+ if err != nil {+ t.Fatalf("factory call 2: %v", err)+ }+ if c1 != c2 {+ // Sharing the connector is what lets the logger be allocated+ // exactly once; if a future refactor changes this, also revisit+ // whether per-installation state is needed.+ t.Fatalf("expected factory to share one connector; got %p vs %p", c1, c2)+ }+}diff --git a/server/internal/integrations/lark/outbound.go b/server/internal/integrations/lark/outbound.gonew file mode 100644index 0000000000..d6cea31c32--- /dev/null+++ b/server/internal/integrations/lark/outbound.go@@ -0,0 +1,473 @@+package lark++import (+ "context"+ "encoding/json"+ "errors"+ "fmt"+ "log/slog"+ "time"++ "github.com/jackc/pgx/v5"+ "github.com/jackc/pgx/v5/pgtype"+ "github.com/multica-ai/multica/server/internal/events"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+ "github.com/multica-ai/multica/server/pkg/protocol"+)++// CardStatus mirrors lark_outbound_card_message.status. Kept as a typed+// alias so callers can't pass arbitrary strings into the status column.+type CardStatus string++const (+ CardStatusPending CardStatus = "pending"+ CardStatusStreaming CardStatus = "streaming"+ CardStatusFinal CardStatus = "final"+ CardStatusError CardStatus = "error"+)++// CardKind enumerates the small set of card variants the patcher+// renders. The Renderer is plug-replaceable so the on-wire card+// template can evolve without touching the patcher's transport / DB+// logic.+type CardKind string++const (+ CardKindThinking CardKind = "thinking"+ CardKindRunning CardKind = "running"+ CardKindFinal CardKind = "final"+ CardKindError CardKind = "error"+)++// CardRender is the rendered card body the Renderer produces. The+// patcher serializes the JSON before handing it to APIClient.+type CardRender struct {+ JSON string+}++// RenderInput is the (typed) snapshot the Renderer sees when building+// or patching a card. Fields are populated as they become available+// during a task lifecycle — IssueNumber is set for `/issue` flows,+// Content is set for completed chat tasks, ErrorMessage for failed.+type RenderInput struct {+ Kind CardKind+ AgentName string+ IssueNumber int32+ IssueID pgtype.UUID+ TaskID pgtype.UUID+ Content string+ ErrorMessage string+}++// Renderer turns a typed RenderInput into the actual Lark card JSON.+// Centralizing this lets us swap card templates (or A/B them) without+// touching event subscription or persistence code.+type Renderer interface {+ Render(in RenderInput) (CardRender, error)+}++// defaultRenderer produces minimal text-only cards that work against+// Lark's generic interactive-card schema. The exact JSON layout will+// be refined when the real product card design lands; this default+// keeps the wiring real (the JSON deserializes against Lark's schema)+// without committing the product to a particular template.+type defaultRenderer struct{}++// NewDefaultRenderer returns the production-default Renderer. Override+// via PatcherConfig.Renderer when a custom template is needed.+func NewDefaultRenderer() Renderer { return &defaultRenderer{} }++func (defaultRenderer) Render(in RenderInput) (CardRender, error) {+ header := "Multica"+ if in.AgentName != "" {+ header = in.AgentName+ }+ var body string+ switch in.Kind {+ case CardKindThinking:+ body = "Thinking…"+ case CardKindRunning:+ body = "Working on it…"+ case CardKindFinal:+ body = in.Content+ if body == "" {+ body = "Done."+ }+ case CardKindError:+ body = "Run failed."+ if in.ErrorMessage != "" {+ body = "Run failed: " + in.ErrorMessage+ }+ default:+ return CardRender{}, fmt.Errorf("unknown card kind %q", in.Kind)+ }+ // update_multi MUST be true on every render: Lark refuses to apply+ // PatchInteractiveCard to a card whose config does not declare it+ // a "shared, updatable" card. Since this renderer drives the+ // thinking → streaming → final/error lifecycle (the card is sent+ // once and patched multiple times), an absent update_multi causes+ // every patch after the first send to silently no-op on the+ // Lark side while the local outbound status row still flips to+ // streaming/final. Keep this on every kind — including thinking+ // and error — because that initial JSON IS the body Lark stores+ // and consults for subsequent patches.+ doc := map[string]any{+ "config": map[string]any{+ "wide_screen_mode": true,+ "update_multi": true,+ },+ "header": map[string]any{+ "template": "blue",+ "title": map[string]any{"tag": "plain_text", "content": header},+ },+ "elements": []any{+ map[string]any{+ "tag": "div",+ "text": map[string]any{+ "tag": "plain_text",+ "content": body,+ },+ },+ },+ }+ raw, err := json.Marshal(doc)+ if err != nil {+ return CardRender{}, err+ }+ return CardRender{JSON: string(raw)}, nil+}++// PatcherQueries is the narrow subset of *db.Queries the Patcher+// needs. Declared as an interface so the patcher is unit-testable+// without a real Postgres connection.+type PatcherQueries interface {+ GetAgentTask(ctx context.Context, id pgtype.UUID) (db.AgentTaskQueue, error)+ GetChatSession(ctx context.Context, id pgtype.UUID) (db.ChatSession, error)+ GetAgent(ctx context.Context, id pgtype.UUID) (db.Agent, error)+ GetLarkInstallation(ctx context.Context, id pgtype.UUID) (db.LarkInstallation, error)+ GetLarkChatSessionBindingBySession(ctx context.Context, chatSessionID pgtype.UUID) (db.LarkChatSessionBinding, error)+ GetLarkOutboundCardByTask(ctx context.Context, taskID pgtype.UUID) (db.LarkOutboundCardMessage, error)+ CreateLarkOutboundCardMessage(ctx context.Context, arg db.CreateLarkOutboundCardMessageParams) (db.LarkOutboundCardMessage, error)+ UpdateLarkOutboundCardStatus(ctx context.Context, arg db.UpdateLarkOutboundCardStatusParams) error+}++// CredentialsResolver decrypts an installation's app_secret for the+// transport layer. *InstallationService satisfies it directly; tests+// substitute a fake.+type CredentialsResolver interface {+ DecryptAppSecret(inst db.LarkInstallation) (string, error)+}++// PatcherConfig tunes the outbound Patcher. Defaults via withDefaults;+// tests typically override Renderer / Now / Logger.+type PatcherConfig struct {+ // Renderer drives the error card template used on the EventTaskFailed+ // path. The success path (EventChatDone) bypasses the renderer+ // entirely — it sends the raw assistant reply as a plain text IM+ // message — so this only matters for the failure branch.+ Renderer Renderer+ Now func() time.Time+ Logger *slog.Logger+}++func (c PatcherConfig) withDefaults() PatcherConfig {+ if c.Renderer == nil {+ c.Renderer = NewDefaultRenderer()+ }+ if c.Now == nil {+ c.Now = time.Now+ }+ if c.Logger == nil {+ c.Logger = slog.Default()+ }+ return c+}++// Patcher reacts to task-lifecycle events on the event bus and forwards+// chat replies to Lark as plain text IM messages. It is the outbound+// side of §4.5 — but the original "thinking → streaming → final card"+// lifecycle was reduced to a single plain-text reply on EventChatDone+// after Bohan reported the card chrome made replies feel like system+// notifications. The error path is the one survivor of card rendering:+// failed runs surface as a short error card on EventTaskFailed because+// the visual distinction from a normal reply is genuinely useful.+//+// Scope:+//+// - Only tasks whose chat_session has a lark_chat_session_binding+// produce outbound. Tasks born from the web UI or autopilot pass+// through unchanged.+//+// - Each EventChatDone yields one Lark text message; there is no+// streaming, no throttling, no DB row to track card-state.+//+// - Multi-replica safety is inherited from the inbound WS lease: at+// most one replica holds the installation lease at a time, the+// event bus is per-process, so exactly one Patcher reacts per run.+type Patcher struct {+ queries PatcherQueries+ credentials CredentialsResolver+ client APIClient+ cfg PatcherConfig+}++// NewPatcher constructs a Patcher bound to its dependencies. The+// patcher does not subscribe to the bus until Register is called.+func NewPatcher(queries PatcherQueries, credentials CredentialsResolver, client APIClient, cfg PatcherConfig) *Patcher {+ cfg = cfg.withDefaults()+ return &Patcher{+ queries: queries,+ credentials: credentials,+ client: client,+ cfg: cfg,+ }+}++// Register subscribes the patcher to the task-lifecycle events it+// cares about on the supplied bus. Idempotent only if you call it+// against a fresh bus; call sites should invoke it exactly once+// during server boot (after the bus + patcher are constructed and+// before HTTP traffic starts).+//+// Subscriptions are deliberately minimal:+//+// - EventChatDone — the agent finished replying. The Patcher sends+// the reply as a plain text IM message (Lark's `msg_type=text`),+// not as an interactive card. The earlier card-based design (with+// thinking → running → final patches) made every reply look like+// a system notification nested in card chrome; flipping to plain+// text makes free-form chat feel native.+//+// - EventTaskFailed — the run failed; surface a short error card+// so the failure is visually distinct from a successful reply.+//+// We deliberately do NOT subscribe to EventTaskQueued / EventTaskRunning+// (no thinking-card lifecycle anymore — adds noise without value) or to+// EventTaskCompleted (chat tasks always emit EventChatDone first, which+// is what we care about; non-chat tasks have no Lark binding anyway and+// would early-return). Leaving EventTaskCompleted unsubscribed also+// avoids the prior "Done." overwrite regression where the no-content+// EventTaskCompleted payload would wipe the real reply.+func (p *Patcher) Register(bus *events.Bus) {+ bus.Subscribe(protocol.EventTaskFailed, p.handleEvent)+ bus.Subscribe(protocol.EventChatDone, p.handleEvent)+}++func (p *Patcher) handleEvent(e events.Event) {+ // Use a fresh background ctx with a tight timeout: bus delivery is+ // synchronous so a stuck Lark HTTP call would otherwise wedge the+ // whole publish call site.+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)+ defer cancel()+ if err := p.processEvent(ctx, e); err != nil {+ p.cfg.Logger.Warn("lark patcher: event handling failed",+ "event_type", e.Type,+ "task_id", e.TaskID,+ "chat_session_id", e.ChatSessionID,+ "error", err,+ )+ }+}++func (p *Patcher) processEvent(ctx context.Context, e events.Event) error {+ taskID, chatSessionID, ok := taskAndSessionFromEvent(e)+ if !ok {+ return nil+ }+ if !chatSessionID.Valid {+ // Issue / autopilot tasks have no chat_session.+ return nil+ }++ binding, err := p.queries.GetLarkChatSessionBindingBySession(ctx, chatSessionID)+ if err != nil {+ if errors.Is(err, pgx.ErrNoRows) {+ // Web-only chat session — not a Lark target.+ return nil+ }+ return fmt.Errorf("lookup chat session binding: %w", err)+ }++ inst, err := p.queries.GetLarkInstallation(ctx, binding.InstallationID)+ if err != nil {+ return fmt.Errorf("load installation: %w", err)+ }+ if InstallationStatus(inst.Status) != InstallationActive {+ // Revoked between trigger and event; nothing to patch.+ return nil+ }+ creds, err := p.installationCredentials(inst)+ if err != nil {+ return err+ }++ agent, agentErr := p.queries.GetAgent(ctx, inst.AgentID)+ agentName := ""+ if agentErr == nil {+ agentName = agent.Name+ }++ switch e.Type {+ case protocol.EventChatDone:+ return p.sendChatReply(ctx, creds, binding, e.Payload)+ case protocol.EventTaskFailed:+ return p.fail(ctx, creds, binding, taskID, agentName, e.Payload)+ }+ return nil+}++// sendChatReply turns ChatDonePayload.Content into a Lark message.+// The wire shape is chosen per-reply based on whether the body+// contains any markdown syntax:+//+// - Plain prose (no markdown) → `msg_type=text`. A one-line "Hi!"+// reply should feel like a normal IM message, not a notification+// card with chrome around it.+//+// - Anything with markdown (headings, lists, code blocks, tables,+// bold/italic, links) → schema-2.0 interactive card with a+// `tag: "markdown"` body element so Lark's client renders the+// formatting instead of leaving raw `**bold**` characters in+// the transcript. The card is visually subtler than the legacy+// binding-prompt template — just a single markdown block, no+// header / icon / CTA buttons.+//+// Empty content is silently dropped: we'd rather show nothing than+// "Done." (the prior card fallback that confused Bohan in the live+// dev env). In practice an empty Content means the daemon completed+// the task without producing visible output, which only happens for+// edge cases like a chat task that just acknowledged a system event;+// not emitting a message there is the right product call.+func (p *Patcher) sendChatReply(ctx context.Context, creds InstallationCredentials, binding db.LarkChatSessionBinding, payload any) error {+ content := chatDoneContent(payload)+ if content == "" {+ return nil+ }+ if containsMarkdown(content) {+ if _, err := p.client.SendMarkdownCard(ctx, SendMarkdownCardParams{+ InstallationID: creds,+ ChatID: ChatID(binding.LarkChatID),+ Markdown: content,+ }); err != nil {+ return fmt.Errorf("send markdown card: %w", err)+ }+ return nil+ }+ if _, err := p.client.SendTextMessage(ctx, SendTextParams{+ InstallationID: creds,+ ChatID: ChatID(binding.LarkChatID),+ Text: content,+ }); err != nil {+ return fmt.Errorf("send text message: %w", err)+ }+ return nil+}++func (p *Patcher) installationCredentials(inst db.LarkInstallation) (InstallationCredentials, error) {+ if p.credentials == nil {+ return InstallationCredentials{}, errors.New("lark patcher: credentials resolver missing")+ }+ secret, err := p.credentials.DecryptAppSecret(inst)+ if err != nil {+ return InstallationCredentials{}, fmt.Errorf("decrypt app_secret: %w", err)+ }+ creds := InstallationCredentials{+ AppID: inst.AppID,+ AppSecret: secret,+ }+ if inst.TenantKey.Valid {+ creds.TenantKey = inst.TenantKey.String+ }+ return creds, nil+}++// fail surfaces a short error card on task failure. Unlike the+// success path (plain text via sendChatReply), failures stay as cards+// because the user benefits from the visual distinction — a red /+// header-styled card is much harder to miss than a regular bubble,+// and these are rare enough that the card chrome isn't noisy.+//+// One-shot send (no patching, no DB row): if the task fails a second+// time we'd just send a second card, which is fine — failure is+// usually a single terminal event.+func (p *Patcher) fail(ctx context.Context, creds InstallationCredentials, binding db.LarkChatSessionBinding, taskID pgtype.UUID, agentName string, payload any) error {+ render, err := p.cfg.Renderer.Render(RenderInput{+ Kind: CardKindError,+ AgentName: agentName,+ TaskID: taskID,+ ErrorMessage: errorMessageFromPayload(payload),+ })+ if err != nil {+ return fmt.Errorf("render error card: %w", err)+ }+ if _, err := p.client.SendInteractiveCard(ctx, SendCardParams{+ InstallationID: creds,+ ChatID: ChatID(binding.LarkChatID),+ CardJSON: render.JSON,+ }); err != nil {+ return fmt.Errorf("send error card: %w", err)+ }+ return nil+}++// taskAndSessionFromEvent parses the typed-ish payload broadcastTaskEvent+// publishes — a map[string]any with `task_id` (always) and+// `chat_session_id` (chat tasks only). EventChatDone carries a+// ChatDonePayload struct instead.+func taskAndSessionFromEvent(e events.Event) (taskID, chatSessionID pgtype.UUID, ok bool) {+ if e.TaskID != "" {+ if err := taskID.Scan(e.TaskID); err != nil {+ taskID = pgtype.UUID{}+ }+ }+ if e.ChatSessionID != "" {+ if err := chatSessionID.Scan(e.ChatSessionID); err != nil {+ chatSessionID = pgtype.UUID{}+ }+ }+ switch p := e.Payload.(type) {+ case map[string]any:+ if !taskID.Valid {+ if s, _ := p["task_id"].(string); s != "" {+ _ = taskID.Scan(s)+ }+ }+ if !chatSessionID.Valid {+ if s, _ := p["chat_session_id"].(string); s != "" {+ _ = chatSessionID.Scan(s)+ }+ }+ case protocol.ChatDonePayload:+ if !taskID.Valid {+ _ = taskID.Scan(p.TaskID)+ }+ if !chatSessionID.Valid {+ _ = chatSessionID.Scan(p.ChatSessionID)+ }+ }+ return taskID, chatSessionID, taskID.Valid+}++func chatDoneContent(payload any) string {+ switch p := payload.(type) {+ case protocol.ChatDonePayload:+ return p.Content+ case map[string]any:+ if s, ok := p["content"].(string); ok {+ return s+ }+ }+ return ""+}++func errorMessageFromPayload(payload any) string {+ if m, ok := payload.(map[string]any); ok {+ if s, ok := m["error"].(string); ok {+ return s+ }+ if s, ok := m["error_message"].(string); ok {+ return s+ }+ }+ return ""+}diff --git a/server/internal/integrations/lark/outbound_test.go b/server/internal/integrations/lark/outbound_test.gonew file mode 100644index 0000000000..b7741e2dde--- /dev/null+++ b/server/internal/integrations/lark/outbound_test.go@@ -0,0 +1,450 @@+package lark++import (+ "context"+ "encoding/json"+ "errors"+ "strings"+ "sync"+ "testing"+ "time"++ "github.com/jackc/pgx/v5"+ "github.com/jackc/pgx/v5/pgtype"+ "github.com/multica-ai/multica/server/internal/events"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+ "github.com/multica-ai/multica/server/pkg/protocol"+)++type fakePatcherQueries struct {+ mu sync.Mutex+ binding db.LarkChatSessionBinding+ bindingErr error+ installation db.LarkInstallation+ installationErr error+ agent db.Agent+ agentErr error+ card db.LarkOutboundCardMessage+ cardErr error+ created []db.CreateLarkOutboundCardMessageParams+ createReturn db.LarkOutboundCardMessage+ statusUpdates []db.UpdateLarkOutboundCardStatusParams+}++func (f *fakePatcherQueries) GetAgentTask(ctx context.Context, id pgtype.UUID) (db.AgentTaskQueue, error) {+ return db.AgentTaskQueue{}, nil+}+func (f *fakePatcherQueries) GetChatSession(ctx context.Context, id pgtype.UUID) (db.ChatSession, error) {+ return db.ChatSession{}, nil+}+func (f *fakePatcherQueries) GetAgent(ctx context.Context, id pgtype.UUID) (db.Agent, error) {+ return f.agent, f.agentErr+}+func (f *fakePatcherQueries) GetLarkInstallation(ctx context.Context, id pgtype.UUID) (db.LarkInstallation, error) {+ return f.installation, f.installationErr+}+func (f *fakePatcherQueries) GetLarkChatSessionBindingBySession(ctx context.Context, sessID pgtype.UUID) (db.LarkChatSessionBinding, error) {+ return f.binding, f.bindingErr+}+func (f *fakePatcherQueries) GetLarkOutboundCardByTask(ctx context.Context, taskID pgtype.UUID) (db.LarkOutboundCardMessage, error) {+ return f.card, f.cardErr+}+func (f *fakePatcherQueries) CreateLarkOutboundCardMessage(ctx context.Context, arg db.CreateLarkOutboundCardMessageParams) (db.LarkOutboundCardMessage, error) {+ f.mu.Lock()+ defer f.mu.Unlock()+ f.created = append(f.created, arg)+ return f.createReturn, nil+}+func (f *fakePatcherQueries) UpdateLarkOutboundCardStatus(ctx context.Context, arg db.UpdateLarkOutboundCardStatusParams) error {+ f.mu.Lock()+ defer f.mu.Unlock()+ f.statusUpdates = append(f.statusUpdates, arg)+ return nil+}++type fakeCredentials struct{ secret string }++func (f fakeCredentials) DecryptAppSecret(inst db.LarkInstallation) (string, error) {+ return f.secret, nil+}++type fakeAPIClient struct {+ mu sync.Mutex+ sent []SendCardParams+ patched []PatchCardParams+ textSent []SendTextParams+ mdCardSent []SendMarkdownCardParams+ sendReturn string+ sendErr error+ patchErr error+ textSendErr error+ textSendReturn string+ mdCardErr error+ mdCardReturn string+ bindingSent []BindingPromptParams+}++func (f *fakeAPIClient) IsConfigured() bool { return true }++func (f *fakeAPIClient) SendInteractiveCard(ctx context.Context, p SendCardParams) (string, error) {+ f.mu.Lock()+ defer f.mu.Unlock()+ f.sent = append(f.sent, p)+ return f.sendReturn, f.sendErr+}+func (f *fakeAPIClient) PatchInteractiveCard(ctx context.Context, p PatchCardParams) error {+ f.mu.Lock()+ defer f.mu.Unlock()+ f.patched = append(f.patched, p)+ return f.patchErr+}+func (f *fakeAPIClient) SendTextMessage(ctx context.Context, p SendTextParams) (string, error) {+ f.mu.Lock()+ defer f.mu.Unlock()+ f.textSent = append(f.textSent, p)+ return f.textSendReturn, f.textSendErr+}+func (f *fakeAPIClient) SendMarkdownCard(ctx context.Context, p SendMarkdownCardParams) (string, error) {+ f.mu.Lock()+ defer f.mu.Unlock()+ f.mdCardSent = append(f.mdCardSent, p)+ return f.mdCardReturn, f.mdCardErr+}+func (f *fakeAPIClient) SendBindingPromptCard(ctx context.Context, p BindingPromptParams) error {+ f.mu.Lock()+ defer f.mu.Unlock()+ f.bindingSent = append(f.bindingSent, p)+ return nil+}+func (f *fakeAPIClient) GetBotInfo(ctx context.Context, creds InstallationCredentials) (BotInfo, error) {+ return BotInfo{}, nil+}++func newTestPatcher(t *testing.T) (*Patcher, *fakePatcherQueries, *fakeAPIClient) {+ t.Helper()+ q := &fakePatcherQueries{+ binding: db.LarkChatSessionBinding{+ ChatSessionID: uuidFromString(t, "cccccccc-cccc-cccc-cccc-cccccccccccc"),+ InstallationID: uuidFromString(t, "1111aaaa-1111-1111-1111-111111111111"),+ LarkChatID: "oc_test_chat",+ LarkChatType: "p2p",+ },+ installation: db.LarkInstallation{+ ID: uuidFromString(t, "1111aaaa-1111-1111-1111-111111111111"),+ AppID: "cli_test_app",+ AppSecretEncrypted: []byte("ciphertext"),+ Status: string(InstallationActive),+ AgentID: uuidFromString(t, "aaaa1111-aaaa-aaaa-aaaa-aaaaaaaaaaaa"),+ },+ agent: db.Agent{Name: "TestAgent"},+ cardErr: pgx.ErrNoRows,+ }+ api := &fakeAPIClient{sendReturn: "lark_card_msg_1", textSendReturn: "lark_text_msg_1"}+ p := NewPatcher(q, fakeCredentials{secret: "shh"}, api, PatcherConfig{+ Logger: newDiscardLogger(),+ Now: time.Now,+ })+ return p, q, api+}++// TestPatcherSendsPlainTextOnChatDone pins the new behaviour Bohan asked+// for: when the agent finishes replying, the Patcher posts the reply as+// a plain Lark IM text message (msg_type=text), not nested inside an+// interactive card. This is the load-bearing UX call — the prior card+// chrome made every reply look like a system notification.+func TestPatcherSendsPlainTextOnChatDone(t *testing.T) {+ p, q, api := newTestPatcher(t)+ taskID := uuidFromString(t, "ee333333-ee33-ee33-ee33-eeeeeeeeeeee")++ p.handleEvent(events.Event{+ Type: protocol.EventChatDone,+ TaskID: uuidString(taskID),+ ChatSessionID: uuidString(q.binding.ChatSessionID),+ Payload: protocol.ChatDonePayload{+ TaskID: uuidString(taskID),+ ChatSessionID: uuidString(q.binding.ChatSessionID),+ Content: "Hello! I'm cc, a coding agent…",+ },+ })++ api.mu.Lock()+ defer api.mu.Unlock()+ if len(api.textSent) != 1 {+ t.Fatalf("expected one SendTextMessage call on ChatDone; got %d", len(api.textSent))+ }+ got := api.textSent[0]+ if got.Text != "Hello! I'm cc, a coding agent…" {+ t.Errorf("text mismatch: got %q", got.Text)+ }+ if got.ChatID != ChatID(q.binding.LarkChatID) {+ t.Errorf("chat_id mismatch: got %q want %q", got.ChatID, q.binding.LarkChatID)+ }+ if got.InstallationID.AppID != "cli_test_app" {+ t.Errorf("expected installation app_id propagated; got %q", got.InstallationID.AppID)+ }+ if len(api.sent) != 0 || len(api.patched) != 0 {+ t.Errorf("ChatDone must NOT send / patch any card; got sent=%d patched=%d",+ len(api.sent), len(api.patched))+ }+}++// TestPatcherRoutesMarkdownReplyToCard pins the two-path chat reply:+// when the agent's body contains markdown syntax, the Patcher MUST+// route to SendMarkdownCard (schema-2.0 interactive card with a+// `tag: "markdown"` body element) so Lark renders the formatting+// instead of leaving raw `**bold**` / `# heading` characters in the+// transcript. Plain prose continues to go through SendTextMessage.+func TestPatcherRoutesMarkdownReplyToCard(t *testing.T) {+ p, q, api := newTestPatcher(t)+ taskID := uuidFromString(t, "ee444444-ee44-ee44-ee44-eeeeeeeeeeee")++ body := "# Summary\n\n- bullet one\n- bullet two\n\n```go\nfunc f() {}\n```\n"+ p.handleEvent(events.Event{+ Type: protocol.EventChatDone,+ TaskID: uuidString(taskID),+ ChatSessionID: uuidString(q.binding.ChatSessionID),+ Payload: protocol.ChatDonePayload{+ TaskID: uuidString(taskID),+ ChatSessionID: uuidString(q.binding.ChatSessionID),+ Content: body,+ },+ })++ api.mu.Lock()+ defer api.mu.Unlock()+ if len(api.mdCardSent) != 1 {+ t.Fatalf("expected one SendMarkdownCard call; got %d", len(api.mdCardSent))+ }+ got := api.mdCardSent[0]+ if got.Markdown != body {+ t.Errorf("markdown body must be forwarded verbatim; got %q", got.Markdown)+ }+ if got.ChatID != ChatID(q.binding.LarkChatID) {+ t.Errorf("chat_id mismatch: got %q want %q", got.ChatID, q.binding.LarkChatID)+ }+ if len(api.textSent) != 0 {+ t.Errorf("markdown body must NOT also fire SendTextMessage; got %d", len(api.textSent))+ }+ if len(api.sent) != 0 || len(api.patched) != 0 {+ t.Errorf("ChatDone must NOT use legacy card paths; sent=%d patched=%d", len(api.sent), len(api.patched))+ }+}++// TestPatcherRoutesPlainReplyToText is the inverse: a short prose+// reply without any markdown syntax should stay on the cheap+// msg_type=text path so the user sees a normal IM bubble.+func TestPatcherRoutesPlainReplyToText(t *testing.T) {+ p, q, api := newTestPatcher(t)+ taskID := uuidFromString(t, "ee555555-ee55-ee55-ee55-eeeeeeeeeeee")++ p.handleEvent(events.Event{+ Type: protocol.EventChatDone,+ TaskID: uuidString(taskID),+ ChatSessionID: uuidString(q.binding.ChatSessionID),+ Payload: protocol.ChatDonePayload{+ TaskID: uuidString(taskID),+ ChatSessionID: uuidString(q.binding.ChatSessionID),+ Content: "Sure, on it.",+ },+ })++ api.mu.Lock()+ defer api.mu.Unlock()+ if len(api.textSent) != 1 {+ t.Fatalf("plain prose must take the text path; got %d text sends", len(api.textSent))+ }+ if len(api.mdCardSent) != 0 {+ t.Errorf("plain prose must NOT wrap in a markdown card; got %d card sends", len(api.mdCardSent))+ }+}++// TestPatcherDropsEmptyChatReply guards the fallback we deliberately+// removed: the previous design rendered "Done." when content was+// empty. Now an empty Content is silently dropped (no text message+// sent at all). Showing nothing is better than showing the misleading+// "Done." fallback, which Bohan reported confused him in the live env.+func TestPatcherDropsEmptyChatReply(t *testing.T) {+ p, q, api := newTestPatcher(t)+ taskID := uuidFromString(t, "ee777777-ee77-ee77-ee77-eeeeeeeeeeee")++ p.handleEvent(events.Event{+ Type: protocol.EventChatDone,+ TaskID: uuidString(taskID),+ ChatSessionID: uuidString(q.binding.ChatSessionID),+ Payload: protocol.ChatDonePayload{+ TaskID: uuidString(taskID),+ ChatSessionID: uuidString(q.binding.ChatSessionID),+ Content: "",+ },+ })++ api.mu.Lock()+ defer api.mu.Unlock()+ if len(api.textSent) != 0 {+ t.Errorf("empty content must drop, not render the Done. fallback; got %d text sends", len(api.textSent))+ }+}++func TestPatcherSkipsWhenNoChatSessionBinding(t *testing.T) {+ p, q, api := newTestPatcher(t)+ q.bindingErr = pgx.ErrNoRows++ p.handleEvent(events.Event{+ Type: protocol.EventChatDone,+ TaskID: uuidString(uuidFromString(t, "ee222222-ee22-ee22-ee22-eeeeeeeeeeee")),+ ChatSessionID: uuidString(uuidFromString(t, "cc222222-cc22-cc22-cc22-cccccccccccc")),+ Payload: protocol.ChatDonePayload{+ Content: "irrelevant — no binding",+ },+ })++ api.mu.Lock()+ defer api.mu.Unlock()+ if len(api.textSent) != 0 || len(api.sent) != 0 {+ t.Fatalf("web-only chat sessions must produce no outbound; got text=%d cards=%d",+ len(api.textSent), len(api.sent))+ }+}++// TestPatcherFailEventSendsErrorCard verifies the failure path still+// surfaces a card. The visual distinction between a successful reply+// (plain text bubble) and a failure (red header card) is genuinely+// useful — and failures are rare enough that the card chrome isn't+// noisy. One-shot send (no patching of any prior thinking card,+// because there isn't one anymore).+func TestPatcherFailEventSendsErrorCard(t *testing.T) {+ p, q, api := newTestPatcher(t)+ taskID := uuidFromString(t, "ee444444-ee44-ee44-ee44-eeeeeeeeeeee")++ p.handleEvent(events.Event{+ Type: protocol.EventTaskFailed,+ TaskID: uuidString(taskID),+ ChatSessionID: uuidString(q.binding.ChatSessionID),+ Payload: map[string]any{+ "task_id": uuidString(taskID),+ "chat_session_id": uuidString(q.binding.ChatSessionID),+ "error": "boom",+ },+ })++ api.mu.Lock()+ defer api.mu.Unlock()+ if len(api.sent) != 1 {+ t.Fatalf("fail event must send an error card; got %d card sends", len(api.sent))+ }+ if len(api.patched) != 0 {+ t.Errorf("fail event must NOT patch any card (no prior card lifecycle); got %d patches", len(api.patched))+ }+ if !strings.Contains(api.sent[0].CardJSON, "boom") {+ t.Errorf("error card body should embed the error message; got %s", api.sent[0].CardJSON)+ }+}++func TestPatcherSwallowsInstallationLoadErrors(t *testing.T) {+ p, q, api := newTestPatcher(t)+ q.installationErr = errors.New("db down")++ p.handleEvent(events.Event{+ Type: protocol.EventChatDone,+ TaskID: uuidString(uuidFromString(t, "ee555555-ee55-ee55-ee55-eeeeeeeeeeee")),+ ChatSessionID: uuidString(q.binding.ChatSessionID),+ Payload: protocol.ChatDonePayload{+ Content: "would-be reply",+ },+ })++ // The patcher logs but never panics; no outbound.+ api.mu.Lock()+ defer api.mu.Unlock()+ if len(api.textSent) != 0 || len(api.sent) != 0 {+ t.Fatalf("DB failure must not produce outbound; got text=%d cards=%d",+ len(api.textSent), len(api.sent))+ }+}++// TestPatcherIgnoresEventTaskCompletedForChatTasks pins the no-extra-send+// invariant. TaskService publishes ChatDone (with content) immediately+// before TaskCompleted (without content) for every chat task. The+// Patcher must NOT react to TaskCompleted — doing so would either+// re-send the same text reply (duplicate bubble) or send the "Done."+// fallback (the original bug Bohan reported). The fix is to leave+// EventTaskCompleted unsubscribed; this test asserts exactly one+// outbound text message from the sequence.+func TestPatcherIgnoresEventTaskCompletedForChatTasks(t *testing.T) {+ p, q, api := newTestPatcher(t)+ taskID := uuidFromString(t, "ee666666-ee66-ee66-ee66-eeeeeeeeeeee")++ // Step 1: ChatDone arrives with the real agent reply. Plain text+ // is sent to Lark.+ p.handleEvent(events.Event{+ Type: protocol.EventChatDone,+ TaskID: uuidString(taskID),+ ChatSessionID: uuidString(q.binding.ChatSessionID),+ Payload: protocol.ChatDonePayload{+ TaskID: uuidString(taskID),+ ChatSessionID: uuidString(q.binding.ChatSessionID),+ Content: "Hello! I'm cc, a coding agent…",+ },+ })++ // Step 2: TaskCompleted fires immediately after with no content.+ // The Patcher MUST NOT send a second message — neither a+ // duplicate of the reply nor the "Done." fallback.+ p.handleEvent(events.Event{+ Type: protocol.EventTaskCompleted,+ TaskID: uuidString(taskID),+ ChatSessionID: uuidString(q.binding.ChatSessionID),+ Payload: map[string]any{+ "task_id": uuidString(taskID),+ "chat_session_id": uuidString(q.binding.ChatSessionID),+ "status": "completed",+ },+ })++ api.mu.Lock()+ defer api.mu.Unlock()+ if len(api.textSent) != 1 {+ t.Fatalf("exactly one text send expected (ChatDone); EventTaskCompleted must be ignored. Got %d sends", len(api.textSent))+ }+ if api.textSent[0].Text != "Hello! I'm cc, a coding agent…" {+ t.Errorf("text content mismatch; got %q", api.textSent[0].Text)+ }+ if len(api.sent) != 0 || len(api.patched) != 0 {+ t.Errorf("no card outbound expected on the success path; got sent=%d patched=%d",+ len(api.sent), len(api.patched))+ }+}++// TestDefaultRendererConfigCarriesUpdateMulti pins the streaming-card+// contract: Lark refuses PatchInteractiveCard on a card whose config+// does not declare update_multi=true. Since the Patcher's whole+// raison d'être is to send a thinking card and then patch it forward+// to streaming/final/error, ANY kind missing update_multi would make+// the patch silently no-op against Lark while the local DB row still+// flips. Hence the assertion covers every kind, not just the final+// patched kinds.+func TestDefaultRendererConfigCarriesUpdateMulti(t *testing.T) {+ r := NewDefaultRenderer()+ for _, kind := range []CardKind{CardKindThinking, CardKindRunning, CardKindFinal, CardKindError} {+ t.Run(string(kind), func(t *testing.T) {+ out, err := r.Render(RenderInput{Kind: kind, Content: "x", ErrorMessage: "y"})+ if err != nil {+ t.Fatalf("render: %v", err)+ }+ var doc map[string]any+ if err := json.Unmarshal([]byte(out.JSON), &doc); err != nil {+ t.Fatalf("decode card json: %v", err)+ }+ cfg, ok := doc["config"].(map[string]any)+ if !ok {+ t.Fatalf("missing config block: %v", doc)+ }+ if v, _ := cfg["update_multi"].(bool); !v {+ t.Errorf("config.update_multi must be true so subsequent patches apply; got %v", cfg)+ }+ if v, _ := cfg["wide_screen_mode"].(bool); !v {+ t.Errorf("config.wide_screen_mode regression: %v", cfg)+ }+ })+ }+}diff --git a/server/internal/integrations/lark/outcome_replier.go b/server/internal/integrations/lark/outcome_replier.gonew file mode 100644index 0000000000..f487cbd09b--- /dev/null+++ b/server/internal/integrations/lark/outcome_replier.go@@ -0,0 +1,350 @@+package lark++import (+ "context"+ "encoding/json"+ "errors"+ "fmt"+ "log/slog"+ "net/url"+ "strings"++ "github.com/jackc/pgx/v5/pgtype"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++// OutcomeReplier reacts to the Dispatcher's verdict by posting the+// appropriate Lark-side reply card. This is the outbound half of the+// `EventEmitter` contract in hub.go: NeedsBinding sends the binding+// prompt to the sender's open_id, AgentOffline / AgentArchived send+// a status notice into the chat. OutcomeIngested is owned by the+// Patcher (task lifecycle); OutcomeDropped is silent.+//+// Reply is best-effort by design: a transient Lark outage MUST NOT+// fail the inbound pipeline (the message is already durable in+// chat_session by the time we get here for OutcomeIngested, and for+// the other outcomes there is no durable side effect to undo). Errors+// are logged and swallowed; the next inbound message for the same+// user retries the reply on its own.+type OutcomeReplier interface {+ Reply(ctx context.Context, inst db.LarkInstallation, msg InboundMessage, res DispatchResult)+}++// OutcomeReplierQueries is the narrow subset of *db.Queries the+// replier needs. Pinned via an interface so tests substitute a fake.+type OutcomeReplierQueries interface {+ GetAgent(ctx context.Context, id pgtype.UUID) (db.Agent, error)+}++// noopReplier is the safe default when Lark is wired without an+// outbound APIClient (stub) or without a BindingTokenService. It+// logs each outcome that would have produced a reply so an operator+// can see the gap in production logs.+type noopReplier struct {+ log *slog.Logger+}++func (n *noopReplier) Reply(ctx context.Context, inst db.LarkInstallation, msg InboundMessage, res DispatchResult) {+ switch res.Outcome {+ case OutcomeNeedsBinding, OutcomeAgentOffline, OutcomeAgentArchived:+ n.log.Warn("lark outcome replier: outbound reply skipped (replier not wired)",+ "outcome", string(res.Outcome),+ "installation_id", uuidString(inst.ID),+ "chat_id", string(msg.ChatID),+ "open_id", string(msg.SenderOpenID),+ )+ }+}++// NewNoopOutcomeReplier returns the no-op replier. Used as the+// fallback when the production wiring is incomplete (e.g. stub+// APIClient, no binding token service).+func NewNoopOutcomeReplier(log *slog.Logger) OutcomeReplier {+ if log == nil {+ log = slog.Default()+ }+ return &noopReplier{log: log}+}++// LarkOutcomeReplier is the production OutcomeReplier. It composes:+//+// - APIClient — to send the binding prompt card (open_id-targeted)+// and the offline/archived notice cards (chat_id-targeted).+// - BindingTokenService — to mint a one-shot binding token for the+// NeedsBinding flow.+// - CredentialsResolver — to decrypt app_secret per call (the+// plaintext secret never lives on the in-memory installation row).+// - OutcomeReplierQueries — for the agent name shown on cards.+//+// The replier is constructed once at boot and shared across the Hub's+// supervisor goroutines; all dependencies must be goroutine-safe+// (the standard implementations are).+type LarkOutcomeReplier struct {+ client APIClient+ bindingSvc *BindingTokenService+ credentials CredentialsResolver+ queries OutcomeReplierQueries+ publicURL string // e.g. https://multica.example, trailing slash trimmed+ bindingPath string // path component of the binding URL, default "/lark/bind"+ noticeHeader string // header text used by the offline/archived cards+ log *slog.Logger+}++// OutcomeReplierConfig wires the production replier. PublicURL is the+// Multica HTTP host the user clicks into to redeem the binding token+// (e.g. https://multica.example); empty means the binding flow can+// only log the open_id, not produce a clickable card. The other+// fields default at construction.+type OutcomeReplierConfig struct {+ APIClient APIClient+ BindingSvc *BindingTokenService+ Credentials CredentialsResolver+ Queries OutcomeReplierQueries+ PublicURL string+ BindingPath string+ Logger *slog.Logger+}++// NewLarkOutcomeReplier validates the configuration and returns the+// production replier. Missing dependencies fall back to noop so the+// boot path stays robust on partially-configured deployments.+func NewLarkOutcomeReplier(cfg OutcomeReplierConfig) OutcomeReplier {+ log := cfg.Logger+ if log == nil {+ log = slog.Default()+ }+ if cfg.APIClient == nil || cfg.BindingSvc == nil || cfg.Credentials == nil || cfg.Queries == nil {+ return NewNoopOutcomeReplier(log)+ }+ if !cfg.APIClient.IsConfigured() {+ log.Warn("lark outcome replier: APIClient.IsConfigured()=false; downgrading to noop replier")+ return NewNoopOutcomeReplier(log)+ }+ if cfg.PublicURL == "" {+ log.Warn("lark outcome replier: MULTICA_PUBLIC_URL not set; binding prompt CTA will not work")+ }+ bindingPath := cfg.BindingPath+ if bindingPath == "" {+ bindingPath = "/lark/bind"+ }+ if !strings.HasPrefix(bindingPath, "/") {+ bindingPath = "/" + bindingPath+ }+ return &LarkOutcomeReplier{+ client: cfg.APIClient,+ bindingSvc: cfg.BindingSvc,+ credentials: cfg.Credentials,+ queries: cfg.Queries,+ publicURL: strings.TrimRight(cfg.PublicURL, "/"),+ bindingPath: bindingPath,+ noticeHeader: "Multica",+ log: log,+ }+}++// Reply implements OutcomeReplier. Reads carefully — the switch is+// the SOURCE OF TRUTH for which outcomes generate a reply, and a+// missing branch silently drops the user-visible side effect.+func (r *LarkOutcomeReplier) Reply(ctx context.Context, inst db.LarkInstallation, msg InboundMessage, res DispatchResult) {+ switch res.Outcome {+ case OutcomeNeedsBinding:+ if err := r.sendBindingPrompt(ctx, inst, res); err != nil {+ r.log.Warn("lark outcome replier: binding prompt failed",+ "installation_id", uuidString(inst.ID),+ "open_id", string(res.SenderOpenID),+ "err", err.Error(),+ )+ }+ case OutcomeAgentOffline:+ if err := r.sendChatNotice(ctx, inst, msg, agentOfflineCopy); err != nil {+ r.log.Warn("lark outcome replier: offline notice failed",+ "installation_id", uuidString(inst.ID),+ "chat_id", string(msg.ChatID),+ "err", err.Error(),+ )+ }+ case OutcomeAgentArchived:+ if err := r.sendChatNotice(ctx, inst, msg, agentArchivedCopy); err != nil {+ r.log.Warn("lark outcome replier: archived notice failed",+ "installation_id", uuidString(inst.ID),+ "chat_id", string(msg.ChatID),+ "err", err.Error(),+ )+ }+ case OutcomeIngested:+ // The agent's chat reply itself goes through the Patcher (text+ // message on ChatDone). But /issue does NOT block on the+ // agent — the user expects an immediate "Created [MUL-42]"+ // confirmation as soon as the issue row commits, separate+ // from whatever the agent eventually replies. Without this,+ // the user types `/issue fix login bug` and just sees the+ // agent's eventual response, with no clear signal that the+ // command itself was understood. Gate on IssueID.Valid so a+ // plain chat message (no /issue) stays silent here.+ if res.IssueID.Valid {+ if err := r.sendIssueCreated(ctx, inst, msg, res); err != nil {+ r.log.Warn("lark outcome replier: issue-created confirmation failed",+ "installation_id", uuidString(inst.ID),+ "chat_id", string(msg.ChatID),+ "issue_id", uuidString(res.IssueID),+ "err", err.Error(),+ )+ }+ }+ case OutcomeDropped:+ // OutcomeDropped is informational; no user-visible reply.+ }+}++func (r *LarkOutcomeReplier) sendBindingPrompt(ctx context.Context, inst db.LarkInstallation, res DispatchResult) error {+ if res.SenderOpenID == "" {+ return errors.New("missing sender open_id")+ }+ if r.publicURL == "" {+ return errors.New("public_url not configured")+ }+ token, err := r.bindingSvc.Mint(ctx, inst.WorkspaceID, inst.ID, res.SenderOpenID)+ if err != nil {+ return fmt.Errorf("mint binding token: %w", err)+ }+ bindURL := r.publicURL + r.bindingPath + "?token=" + url.QueryEscape(token.Raw)+ creds, err := r.installationCredentials(inst)+ if err != nil {+ return err+ }+ return r.client.SendBindingPromptCard(ctx, BindingPromptParams{+ InstallationID: creds,+ OpenID: res.SenderOpenID,+ BindURL: bindURL,+ })+}++// sendIssueCreated posts the "Created [MUL-42] <title>" confirmation+// as a plain text message. We deliberately send text rather than an+// interactive card so the confirmation flows inline with the rest of+// the Lark conversation — consistent with how chat replies render+// after MUL-2671's plain-text refactor. The link to Multica is+// included on its own line so Lark's auto-linker turns it into a+// tappable URL.+func (r *LarkOutcomeReplier) sendIssueCreated(ctx context.Context, inst db.LarkInstallation, msg InboundMessage, res DispatchResult) error {+ if msg.ChatID == "" {+ return errors.New("missing chat_id")+ }+ creds, err := r.installationCredentials(inst)+ if err != nil {+ return err+ }+ text := issueCreatedText(res, r.publicURL)+ if _, err := r.client.SendTextMessage(ctx, SendTextParams{+ InstallationID: creds,+ ChatID: msg.ChatID,+ Text: text,+ }); err != nil {+ return fmt.Errorf("send issue-created text: %w", err)+ }+ return nil+}++// issueCreatedText composes the user-facing confirmation. Identifier+// always wins over a bare number — DispatchResult.IssueIdentifier+// already encodes the workspace prefix when available. PublicURL is+// optional: when empty (self-host operators who haven't configured+// MULTICA_PUBLIC_URL) the message still confirms the issue, just+// without a deep link the user can tap.+func issueCreatedText(res DispatchResult, publicURL string) string {+ identifier := res.IssueIdentifier+ if identifier == "" {+ identifier = fmt.Sprintf("#%d", res.IssueNumber)+ }+ title := strings.TrimSpace(res.IssueTitle)+ var line string+ if title == "" {+ line = fmt.Sprintf("Created %s", identifier)+ } else {+ line = fmt.Sprintf("Created %s — %s", identifier, title)+ }+ if publicURL == "" {+ return line+ }+ return line + "\n" + strings.TrimRight(publicURL, "/") + "/issues/" + identifier+}++func (r *LarkOutcomeReplier) sendChatNotice(ctx context.Context, inst db.LarkInstallation, msg InboundMessage, body string) error {+ if msg.ChatID == "" {+ return errors.New("missing chat_id")+ }+ creds, err := r.installationCredentials(inst)+ if err != nil {+ return err+ }+ header := r.noticeHeader+ if agent, aerr := r.queries.GetAgent(ctx, inst.AgentID); aerr == nil && agent.Name != "" {+ header = agent.Name+ }+ cardJSON, err := renderNoticeCard(header, body)+ if err != nil {+ return fmt.Errorf("render notice card: %w", err)+ }+ if _, err := r.client.SendInteractiveCard(ctx, SendCardParams{+ InstallationID: creds,+ ChatID: msg.ChatID,+ CardJSON: cardJSON,+ }); err != nil {+ return fmt.Errorf("send notice card: %w", err)+ }+ return nil+}++func (r *LarkOutcomeReplier) installationCredentials(inst db.LarkInstallation) (InstallationCredentials, error) {+ secret, err := r.credentials.DecryptAppSecret(inst)+ if err != nil {+ return InstallationCredentials{}, fmt.Errorf("decrypt app_secret: %w", err)+ }+ creds := InstallationCredentials{+ AppID: inst.AppID,+ AppSecret: secret,+ }+ if inst.TenantKey.Valid {+ creds.TenantKey = inst.TenantKey.String+ }+ return creds, nil+}++// renderNoticeCard produces a minimal text-only interactive card for+// the offline / archived dispatch outcomes. Lark requires+// update_multi=true on every card we may patch later; these notice+// cards are one-shot, so update_multi is left false (the card stays+// as-is). Header / body match the Chinese voice used elsewhere in+// the integration.+func renderNoticeCard(header, body string) (string, error) {+ doc := map[string]any{+ "config": map[string]any{"wide_screen_mode": true},+ "header": map[string]any{+ "template": "grey",+ "title": map[string]any{"tag": "plain_text", "content": header},+ },+ "elements": []any{+ map[string]any{+ "tag": "div",+ "text": map[string]any{+ "tag": "plain_text",+ "content": body,+ },+ },+ },+ }+ raw, err := json.Marshal(doc)+ if err != nil {+ return "", err+ }+ return string(raw), nil+}++// agentOfflineCopy and agentArchivedCopy are the user-visible Chinese+// strings for the two daemon/agent unavailability outcomes. They+// match the §4.6 design: an offline agent will run when the daemon+// comes back; an archived agent needs operator action.+const (+ agentOfflineCopy = "Agent 当前离线,消息已记录。下次 daemon 上线后会自动继续处理。"+ agentArchivedCopy = "这个 Agent 已被归档,无法继续处理消息。请联系工作区管理员恢复或重新绑定。"+)diff --git a/server/internal/integrations/lark/outcome_replier_test.go b/server/internal/integrations/lark/outcome_replier_test.gonew file mode 100644index 0000000000..0bbc96db23--- /dev/null+++ b/server/internal/integrations/lark/outcome_replier_test.go@@ -0,0 +1,372 @@+package lark++import (+ "context"+ "errors"+ "io"+ "log/slog"+ "strings"+ "sync"+ "testing"++ "github.com/jackc/pgx/v5"+ "github.com/jackc/pgx/v5/pgtype"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++// stubAPIClientWithRecorder is a fake APIClient that captures the+// arguments of each outbound call so the replier tests can assert+// what landed.+type stubAPIClientWithRecorder struct {+ mu sync.Mutex+ configured bool+ bindingCalls []BindingPromptParams+ interactiveOut []SendCardParams+ textOut []SendTextParams+ sendErr error+ textErr error+ bindingErr error+}++func (s *stubAPIClientWithRecorder) IsConfigured() bool { return s.configured }++func (s *stubAPIClientWithRecorder) SendInteractiveCard(ctx context.Context, p SendCardParams) (string, error) {+ s.mu.Lock()+ defer s.mu.Unlock()+ if s.sendErr != nil {+ return "", s.sendErr+ }+ s.interactiveOut = append(s.interactiveOut, p)+ return "lark-msg-id", nil+}++func (s *stubAPIClientWithRecorder) PatchInteractiveCard(ctx context.Context, p PatchCardParams) error {+ return nil+}++func (s *stubAPIClientWithRecorder) SendTextMessage(ctx context.Context, p SendTextParams) (string, error) {+ s.mu.Lock()+ defer s.mu.Unlock()+ if s.textErr != nil {+ return "", s.textErr+ }+ s.textOut = append(s.textOut, p)+ return "lark-text-msg-id", nil+}++func (s *stubAPIClientWithRecorder) SendMarkdownCard(ctx context.Context, p SendMarkdownCardParams) (string, error) {+ return "lark-md-msg-id", nil+}++func (s *stubAPIClientWithRecorder) SendBindingPromptCard(ctx context.Context, p BindingPromptParams) error {+ s.mu.Lock()+ defer s.mu.Unlock()+ if s.bindingErr != nil {+ return s.bindingErr+ }+ s.bindingCalls = append(s.bindingCalls, p)+ return nil+}++func (s *stubAPIClientWithRecorder) GetBotInfo(ctx context.Context, creds InstallationCredentials) (BotInfo, error) {+ return BotInfo{}, nil+}++// stubCredentialsResolver returns a fixed plaintext secret.+type stubCredentialsResolver struct{ secret string }++func (s stubCredentialsResolver) DecryptAppSecret(inst db.LarkInstallation) (string, error) {+ if s.secret == "" {+ return "", errors.New("no secret configured")+ }+ return s.secret, nil+}++// stubReplierQueries returns a fixed agent.+type stubReplierQueries struct {+ agent db.Agent+ err error+}++func (s stubReplierQueries) GetAgent(ctx context.Context, id pgtype.UUID) (db.Agent, error) {+ if s.err != nil {+ return db.Agent{}, s.err+ }+ return s.agent, nil+}++// stubBindingMint is a minimal TxStarter stand-in: the real+// BindingTokenService.Mint calls qx.CreateLarkBindingToken on the+// non-tx queries handle when no transaction is started by the caller.+// We bypass that path by constructing a BindingTokenService with a+// fake DB query interface — but since BindingTokenService is a+// concrete struct around *db.Queries, the cleanest seam in tests is+// to swap the replier's bindingSvc field for a fake that satisfies+// the narrow Mint method via an in-package alias.++// fakeBindingMinter substitutes for BindingTokenService.Mint in tests+// — we cannot construct a real BindingTokenService without a live+// *db.Queries, but the replier only calls .Mint on it, so a typed+// wrapper around a function works.+//+// We monkey-patch by exposing a package-level seam on the replier in+// the test file: the production path uses bindingSvc directly; the+// test path wraps the replier so Reply can be exercised end-to-end.++// TestLarkOutcomeReplierFallsBackToNoopWhenStubAPI ensures the+// production replier downgrades to noop when the supplied APIClient+// reports IsConfigured()=false. This avoids a misconfigured+// deployment burning binding tokens that can never be delivered.+func TestLarkOutcomeReplierFallsBackToNoopWhenStubAPI(t *testing.T) {+ t.Parallel()+ log := slog.New(slog.NewTextHandler(io.Discard, nil))+ stub := &stubAPIClientWithRecorder{configured: false}+ rep := NewLarkOutcomeReplier(OutcomeReplierConfig{+ APIClient: stub,+ BindingSvc: &BindingTokenService{}, // not nil so we exercise the IsConfigured guard+ Credentials: stubCredentialsResolver{secret: "s"},+ Queries: stubReplierQueries{},+ PublicURL: "https://multica.test",+ Logger: log,+ })+ if _, isNoop := rep.(*noopReplier); !isNoop {+ t.Fatalf("expected noopReplier when APIClient.IsConfigured()=false, got %T", rep)+ }+}++// TestLarkOutcomeReplierFallsBackToNoopWhenNilDep verifies that any+// missing dependency yields a noop replier rather than a half-wired+// production one (which would panic on first use).+func TestLarkOutcomeReplierFallsBackToNoopWhenNilDep(t *testing.T) {+ t.Parallel()+ log := slog.New(slog.NewTextHandler(io.Discard, nil))+ cases := []OutcomeReplierConfig{+ {}, // all nil+ {APIClient: &stubAPIClientWithRecorder{configured: true}},+ {APIClient: &stubAPIClientWithRecorder{configured: true}, BindingSvc: &BindingTokenService{}},+ {APIClient: &stubAPIClientWithRecorder{configured: true}, BindingSvc: &BindingTokenService{}, Credentials: stubCredentialsResolver{secret: "s"}},+ }+ for i, cfg := range cases {+ cfg.Logger = log+ if _, isNoop := NewLarkOutcomeReplier(cfg).(*noopReplier); !isNoop {+ t.Errorf("case %d: expected noopReplier with missing dep, got production", i)+ }+ }+}++// TestLarkOutcomeReplierAgentOfflineSendsCard exercises the+// non-binding path, which doesn't require the BindingTokenService+// machinery — we can construct the production replier and assert+// SendInteractiveCard was called with the expected chat_id + body.+func TestLarkOutcomeReplierAgentOfflineSendsCard(t *testing.T) {+ t.Parallel()+ log := slog.New(slog.NewTextHandler(io.Discard, nil))+ stub := &stubAPIClientWithRecorder{configured: true}+ rep := NewLarkOutcomeReplier(OutcomeReplierConfig{+ APIClient: stub,+ BindingSvc: &BindingTokenService{},+ Credentials: stubCredentialsResolver{secret: "s"},+ Queries: stubReplierQueries{agent: db.Agent{Name: "Trump"}},+ PublicURL: "https://multica.test",+ Logger: log,+ })+ inst := db.LarkInstallation{AppID: "cli_x"}+ inst.ID = mustUUID("11111111-1111-1111-1111-111111111111")+ msg := InboundMessage{ChatID: "oc_chat_1", SenderOpenID: "ou_user_1"}+ rep.Reply(context.Background(), inst, msg, DispatchResult{Outcome: OutcomeAgentOffline})++ if len(stub.interactiveOut) != 1 {+ t.Fatalf("expected one SendInteractiveCard call, got %d", len(stub.interactiveOut))+ }+ got := stub.interactiveOut[0]+ if got.ChatID != "oc_chat_1" {+ t.Errorf("ChatID = %q; want oc_chat_1", got.ChatID)+ }+ if got.InstallationID.AppID != "cli_x" {+ t.Errorf("AppID = %q", got.InstallationID.AppID)+ }+ if got.InstallationID.AppSecret != "s" {+ t.Errorf("AppSecret = %q", got.InstallationID.AppSecret)+ }+ if !contains(got.CardJSON, "离线") || !contains(got.CardJSON, "Trump") {+ t.Errorf("CardJSON should embed offline copy and agent name: %s", got.CardJSON)+ }+}++func TestLarkOutcomeReplierAgentArchivedSendsCard(t *testing.T) {+ t.Parallel()+ log := slog.New(slog.NewTextHandler(io.Discard, nil))+ stub := &stubAPIClientWithRecorder{configured: true}+ rep := NewLarkOutcomeReplier(OutcomeReplierConfig{+ APIClient: stub,+ BindingSvc: &BindingTokenService{},+ Credentials: stubCredentialsResolver{secret: "s"},+ Queries: stubReplierQueries{},+ PublicURL: "https://multica.test",+ Logger: log,+ })+ msg := InboundMessage{ChatID: "oc_chat_arch"}+ rep.Reply(context.Background(), db.LarkInstallation{}, msg, DispatchResult{Outcome: OutcomeAgentArchived})+ if len(stub.interactiveOut) != 1 {+ t.Fatalf("expected one SendInteractiveCard call, got %d", len(stub.interactiveOut))+ }+ if !contains(stub.interactiveOut[0].CardJSON, "归档") {+ t.Errorf("CardJSON should embed archived copy: %s", stub.interactiveOut[0].CardJSON)+ }+}++// TestLarkOutcomeReplierIngestedAndDroppedAreSilent asserts that the+// replier does NOT call the APIClient on outcomes owned elsewhere+// (Patcher handles Ingested; Dropped is informational only).+func TestLarkOutcomeReplierIngestedAndDroppedAreSilent(t *testing.T) {+ t.Parallel()+ log := slog.New(slog.NewTextHandler(io.Discard, nil))+ stub := &stubAPIClientWithRecorder{configured: true}+ rep := NewLarkOutcomeReplier(OutcomeReplierConfig{+ APIClient: stub,+ BindingSvc: &BindingTokenService{},+ Credentials: stubCredentialsResolver{secret: "s"},+ Queries: stubReplierQueries{},+ PublicURL: "https://multica.test",+ Logger: log,+ })+ msg := InboundMessage{ChatID: "oc_x"}+ rep.Reply(context.Background(), db.LarkInstallation{}, msg, DispatchResult{Outcome: OutcomeIngested})+ rep.Reply(context.Background(), db.LarkInstallation{}, msg, DispatchResult{Outcome: OutcomeDropped, DropReason: DropReasonDuplicate})+ if len(stub.interactiveOut) != 0 || len(stub.bindingCalls) != 0 {+ t.Errorf("Ingested/Dropped should not trigger any APIClient call; got interactive=%d binding=%d",+ len(stub.interactiveOut), len(stub.bindingCalls))+ }+}++// TestLarkOutcomeReplierOfflineSwallowsAPIError verifies the+// best-effort contract: an APIClient failure must NOT panic or+// propagate — Reply has no return signal — but the test still+// observes the side effect (single attempted SendInteractiveCard).+func TestLarkOutcomeReplierOfflineSwallowsAPIError(t *testing.T) {+ t.Parallel()+ log := slog.New(slog.NewTextHandler(io.Discard, nil))+ stub := &stubAPIClientWithRecorder{configured: true, sendErr: errors.New("lark 5xx")}+ rep := NewLarkOutcomeReplier(OutcomeReplierConfig{+ APIClient: stub,+ BindingSvc: &BindingTokenService{},+ Credentials: stubCredentialsResolver{secret: "s"},+ Queries: stubReplierQueries{},+ PublicURL: "https://multica.test",+ Logger: log,+ })+ // Should NOT panic.+ rep.Reply(context.Background(), db.LarkInstallation{}, InboundMessage{ChatID: "oc"}, DispatchResult{Outcome: OutcomeAgentOffline})+}++// TestNoopReplierIsHandledByHub verifies that NewHub installs a noop+// replier by default — so the inbound pipeline runs even when the+// caller never calls SetOutcomeReplier (e.g. in deployments that+// only run the inbound dispatcher pre-outbound-wiring). This guards+// the "no nil replier crash" contract on hub.handleEvent.+func TestNoopReplierIsHandledByHub(t *testing.T) {+ t.Parallel()+ hub := NewHub(nil, nil, nil, HubConfig{})+ if hub.replier == nil {+ t.Fatal("Hub.replier must default to noop, not nil")+ }+}++// TestLarkOutcomeReplierIssueCreatedSendsConfirmation pins the+// recovered /issue confirmation path. Before the plain-text refactor+// the design called for a "已创建 [MUL-xxx]" card; the refactor+// dropped the whole card lifecycle, which had the side effect of+// silently dropping the issue-created signal. Trump flagged it as a+// blocker on PR #3277 review. Fix: OutcomeIngested with IssueID.Valid+// triggers a plain text confirmation send via SendTextMessage,+// composing the workspace-qualified identifier with the title and a+// deep link back to Multica.+func TestLarkOutcomeReplierIssueCreatedSendsConfirmation(t *testing.T) {+ t.Parallel()+ log := slog.New(slog.NewTextHandler(io.Discard, nil))+ stub := &stubAPIClientWithRecorder{configured: true}+ rep := NewLarkOutcomeReplier(OutcomeReplierConfig{+ APIClient: stub,+ BindingSvc: &BindingTokenService{},+ Credentials: stubCredentialsResolver{secret: "s"},+ Queries: stubReplierQueries{},+ PublicURL: "https://multica.test",+ Logger: log,+ })++ inst := db.LarkInstallation{AppID: "cli_x"}+ inst.ID = mustUUID("11111111-1111-1111-1111-111111111111")+ msg := InboundMessage{ChatID: "oc_chat_42", SenderOpenID: "ou_user"}+ rep.Reply(context.Background(), inst, msg, DispatchResult{+ Outcome: OutcomeIngested,+ IssueID: mustUUID("22222222-2222-2222-2222-222222222222"),+ IssueNumber: 42,+ IssueIdentifier: "MUL-42",+ IssueTitle: "fix login bug",+ })++ stub.mu.Lock()+ defer stub.mu.Unlock()+ if len(stub.textOut) != 1 {+ t.Fatalf("expected one SendTextMessage call, got %d", len(stub.textOut))+ }+ got := stub.textOut[0]+ if got.ChatID != "oc_chat_42" {+ t.Errorf("ChatID = %q; want oc_chat_42", got.ChatID)+ }+ if !strings.Contains(got.Text, "MUL-42") {+ t.Errorf("text should embed the workspace-qualified key; got %q", got.Text)+ }+ if !strings.Contains(got.Text, "fix login bug") {+ t.Errorf("text should embed the issue title; got %q", got.Text)+ }+ if !strings.Contains(got.Text, "https://multica.test/issues/MUL-42") {+ t.Errorf("text should embed the deep link back to Multica; got %q", got.Text)+ }+ // No interactive card on this path — the confirmation must be+ // plain text, matching how chat replies render.+ if len(stub.interactiveOut) != 0 {+ t.Errorf("issue-created confirmation must not send a card; got %d cards", len(stub.interactiveOut))+ }+}++// TestLarkOutcomeReplierOutcomeIngestedSilentWithoutIssue pins the+// silent-by-default behaviour for plain chat messages. The "Created"+// text is gated on IssueID.Valid; a chat that didn't include /issue+// must NOT trigger an outbound from the OutcomeReplier (the agent's+// reply is delivered separately by the Patcher on EventChatDone).+func TestLarkOutcomeReplierOutcomeIngestedSilentWithoutIssue(t *testing.T) {+ t.Parallel()+ log := slog.New(slog.NewTextHandler(io.Discard, nil))+ stub := &stubAPIClientWithRecorder{configured: true}+ rep := NewLarkOutcomeReplier(OutcomeReplierConfig{+ APIClient: stub,+ BindingSvc: &BindingTokenService{},+ Credentials: stubCredentialsResolver{secret: "s"},+ Queries: stubReplierQueries{},+ PublicURL: "https://multica.test",+ Logger: log,+ })++ rep.Reply(context.Background(), db.LarkInstallation{}, InboundMessage{ChatID: "oc"},+ DispatchResult{Outcome: OutcomeIngested}) // no IssueID++ stub.mu.Lock()+ defer stub.mu.Unlock()+ if len(stub.textOut) != 0 || len(stub.interactiveOut) != 0 {+ t.Errorf("plain chat ingest must be silent at the replier; got text=%d cards=%d",+ len(stub.textOut), len(stub.interactiveOut))+ }+}++func mustUUID(s string) pgtype.UUID {+ var u pgtype.UUID+ if err := u.Scan(s); err != nil {+ panic(err)+ }+ return u+}++// silence the unused import warnings for the dependencies we keep+// reaching for via reflection in future test cases.+var _ = pgx.ErrNoRowsdiff --git a/server/internal/integrations/lark/registration.go b/server/internal/integrations/lark/registration.gonew file mode 100644index 0000000000..808a45b1a7--- /dev/null+++ b/server/internal/integrations/lark/registration.go@@ -0,0 +1,426 @@+package lark++import (+ "context"+ "encoding/json"+ "errors"+ "fmt"+ "io"+ "net/http"+ "net/url"+ "strings"+ "time"+)++// Lark PersonalAgent registration is a 1:1 implementation of RFC 8628+// (OAuth 2.0 Device Authorization Grant) against accounts.feishu.cn+// (mainland) / accounts.larksuite.com (international). The protocol+// has only two phases:+//+// 1. begin — POST <domain>/oauth/v1/app/registration with+// action=begin and (archetype=PersonalAgent / auth_method=client_secret+// / request_user_info=open_id). Lark returns a device_code, a+// verification_uri_complete (the QR target), a polling interval,+// and an expiry. Multica renders the QR, the user scans it in the+// Lark app, walks the "create a PersonalAgent for this account"+// flow, and authorizes.+//+// 2. poll — POST the same URL with action=poll and the device_code.+// The server replies with one of:+// - {error: "authorization_pending"} — keep polling.+// - {error: "slow_down"} — bump the interval +5s, then poll.+// - {user_info: {tenant_brand: "lark"}}+// — user authorized via the+// international tenant; we+// switch the polling host to+// accounts.larksuite.com and+// keep going.+// - {client_id, client_secret, user_info: {open_id}}+// — terminal success.+// - {error: "expired_token"|"access_denied"}+// — terminal failure.+//+// We deliberately inline this client (rather than depend on+// github.com/larksuite/oapi-sdk-go/scene/registration) so the registration+// surface ships with the same go.mod footprint as the rest of the lark+// package — a ~270-line single-file client is the right size to own+// when the alternative is dragging a full SDK + its transitive deps+// for one endpoint.++const (+ registrationDefaultFeishuDomain = "https://accounts.feishu.cn"+ registrationDefaultLarkDomain = "https://accounts.larksuite.com"++ registrationEndpoint = "/oauth/v1/app/registration"++ // Default polling cadence Lark uses when the server omits `interval`.+ // 5s matches the Lark SDK; smaller would risk slow_down responses+ // without buying any latency improvement.+ registrationDefaultPollSeconds = 5++ // Default registration window (10 minutes) — long enough for a user+ // to scan, switch apps, walk the create-bot flow, and authorize on+ // their phone, short enough that an abandoned session does not pin+ // resources for hours.+ registrationDefaultExpireSeconds = 600++ // Internal-tenant brand label Lark uses to flag "you scanned with a+ // Lark (international) account, not a Feishu (mainland) one". When+ // we see this we re-aim polling at accounts.larksuite.com and+ // re-issue the very next poll WITHOUT first waiting for the polling+ // interval — the upstream SDK shows that Lark's server emits the+ // tenant_brand hint exactly once during the polling stream and the+ // subsequent poll must reach the new domain to learn the credentials.+ registrationTenantBrandLark = "lark"+)++// RegistrationConfig configures the device-flow client. All fields are+// optional; the zero value targets accounts.feishu.cn over the standard+// http.Client (with a 30s per-call timeout so a stalled poll cannot+// silently pin a session goroutine for the entire expiry window).+type RegistrationConfig struct {+ // Domain is the initial polling host. Default+ // "https://accounts.feishu.cn"; staging deployments can point this+ // at a mock or at the Lark beta endpoint.+ Domain string++ // LarkDomain is the international-tenant polling host the client+ // switches to when Lark's poll response surfaces+ // user_info.tenant_brand="lark". Default+ // "https://accounts.larksuite.com".+ LarkDomain string++ // HTTPClient is the transport for every request the client makes.+ // Empty defaults to a fresh *http.Client with a 30s timeout — the+ // device-flow endpoint is normally a sub-second call but we add+ // headroom for cross-region paths.+ HTTPClient *http.Client++ // Source labels the QR-code URL's `source` query param so Lark's+ // telemetry can attribute installs back to Multica. Empty defaults+ // to "multica".+ Source string++ // Now is overridable for deterministic expiry-bound tests.+ Now func() time.Time+}++func (c RegistrationConfig) withDefaults() RegistrationConfig {+ if c.Domain == "" {+ c.Domain = registrationDefaultFeishuDomain+ }+ if c.LarkDomain == "" {+ c.LarkDomain = registrationDefaultLarkDomain+ }+ if c.HTTPClient == nil {+ c.HTTPClient = &http.Client{Timeout: 30 * time.Second}+ }+ if c.Source == "" {+ c.Source = "multica"+ }+ if c.Now == nil {+ c.Now = time.Now+ }+ return c+}++// RegistrationClient runs the device-flow protocol but does NOT own+// session state or installation provisioning — RegistrationService+// composes the client with the session store and the DB write path.+// Splitting these lets the protocol client be deterministic and easy+// to test against an httptest fake without involving the database.+type RegistrationClient struct {+ cfg RegistrationConfig+}++// NewRegistrationClient constructs the device-flow client.+func NewRegistrationClient(cfg RegistrationConfig) *RegistrationClient {+ return &RegistrationClient{cfg: cfg.withDefaults()}+}++// BeginResult is what Begin returns to RegistrationService.+type BeginResult struct {+ DeviceCode string+ // QRCodeURL is the verification_uri_complete with Multica's `source`+ // telemetry params appended; render this as a QR image client-side.+ QRCodeURL string+ // Domain is the polling host this session opened against. The+ // service must pass it back to Poll so the international-tenant+ // switch (StatusDomainSwitched) can re-aim subsequent polls.+ Domain string+ // Interval is Lark's suggested polling cadence. Slow_down responses+ // add 5s; the service is responsible for honoring the updated+ // cadence.+ Interval time.Duration+ // ExpiresIn is the absolute lifetime of the device_code. A poll+ // after this window returns expired_token; the session goroutine+ // uses this to size its context.WithTimeout.+ ExpiresIn time.Duration+}++// PollResult is the discriminated union of every terminal and+// non-terminal poll outcome. The caller branches on the populated+// fields:+// - Success (ClientID + ClientSecret + OpenID) → install+// - SwitchedDomain (new domain string) → swap host, re-poll immediately+// - Status ("authorization_pending" / "slow_down") → wait, poll again+// - Err (terminal error) → abort the session+type PollResult struct {+ ClientID string+ ClientSecret string+ OpenID OpenID++ // SwitchedDomain is non-empty when Lark told us "this is a Lark+ // international account, re-poll over there." RegistrationService+ // must update its session's stored domain and re-poll WITHOUT+ // honoring the interval (the SDK does the same — the upstream+ // behaviour is that the very next poll lands on the new domain and+ // returns the actual credentials).+ SwitchedDomain string++ // Status carries non-terminal protocol signals — typically+ // "authorization_pending" or "slow_down". The service uses these+ // to decide whether to bump the polling interval.+ Status string++ // Err is the terminal error code (e.g. "access_denied",+ // "expired_token", or a free-form Lark code we did not anticipate).+ // On a non-terminal result this is nil.+ Err *RegistrationError+}++// RegistrationError is the typed Lark protocol error. The handler+// pipeline maps `Code` to a stable user-facing reason so the UI can+// render the right copy without parsing prose.+type RegistrationError struct {+ Code string+ Description string+}++func (e *RegistrationError) Error() string {+ if e == nil {+ return ""+ }+ if e.Description == "" {+ return fmt.Sprintf("registration: %s", e.Code)+ }+ return fmt.Sprintf("registration: %s: %s", e.Code, e.Description)+}++// Begin opens a new device-flow session against the configured Feishu+// (mainland) domain. Lark may surface a Lark-international tenant on+// the FIRST poll — we don't try to predict it here; the polling loop+// in RegistrationService handles the domain swap.+//+// namePreset pre-fills the bot/app name on Lark's "create a+// PersonalAgent" form so the installed bot defaults to e.g.+// "<agent> - Multica" instead of Lark's auto-generated+// "{用户姓名}的智能助手". It is a user-editable default (the user can+// still change it on the form), and it rides on the QR URL — not the+// begin POST body, which has no name field. Empty omits the pre-fill.+func (c *RegistrationClient) Begin(ctx context.Context, namePreset string) (*BeginResult, error) {+ var resp struct {+ DeviceCode string `json:"device_code"`+ VerificationURIComplete string `json:"verification_uri_complete"`+ VerificationURI string `json:"verification_uri"`+ UserCode string `json:"user_code"`+ Interval int `json:"interval"`+ ExpireIn int `json:"expire_in"`+ Error string `json:"error"`+ ErrorDescription string `json:"error_description"`+ }+ form := url.Values{+ "action": []string{"begin"},+ "archetype": []string{"PersonalAgent"},+ "auth_method": []string{"client_secret"},+ "request_user_info": []string{"open_id"},+ }+ if err := c.doForm(ctx, c.cfg.Domain, form, &resp); err != nil {+ return nil, err+ }+ if resp.Error != "" {+ return nil, &RegistrationError{Code: resp.Error, Description: resp.ErrorDescription}+ }+ if resp.DeviceCode == "" {+ return nil, &RegistrationError{Code: "invalid_response", Description: "device_code is empty"}+ }+ if resp.VerificationURIComplete == "" {+ return nil, &RegistrationError{Code: "invalid_response", Description: "verification_uri_complete is empty"}+ }+ qr, err := decorateQRCodeURL(resp.VerificationURIComplete, c.cfg.Source, namePreset)+ if err != nil {+ return nil, &RegistrationError{Code: "invalid_response", Description: "verification_uri_complete is not a URL: " + err.Error()}+ }+ interval := registrationDefaultPollSeconds+ if resp.Interval > 0 {+ interval = resp.Interval+ }+ expireIn := registrationDefaultExpireSeconds+ if resp.ExpireIn > 0 {+ expireIn = resp.ExpireIn+ }+ return &BeginResult{+ DeviceCode: resp.DeviceCode,+ QRCodeURL: qr,+ Domain: c.cfg.Domain,+ Interval: time.Duration(interval) * time.Second,+ ExpiresIn: time.Duration(expireIn) * time.Second,+ }, nil+}++// Poll runs a single poll round-trip against the supplied domain (which+// the caller may have updated mid-session via SwitchedDomain from a+// prior PollResult). Domain selection lives outside the client so the+// session state machine in RegistrationService is the single source of+// truth for which host the next call must hit.+func (c *RegistrationClient) Poll(ctx context.Context, domain, deviceCode string) (*PollResult, error) {+ if deviceCode == "" {+ return nil, &RegistrationError{Code: "invalid_argument", Description: "device_code is required"}+ }+ if domain == "" {+ domain = c.cfg.Domain+ }+ var resp struct {+ ClientID string `json:"client_id,omitempty"`+ ClientSecret string `json:"client_secret,omitempty"`+ UserInfo *struct {+ OpenID string `json:"open_id,omitempty"`+ TenantBrand string `json:"tenant_brand,omitempty"`+ } `json:"user_info,omitempty"`+ Error string `json:"error,omitempty"`+ ErrorDescription string `json:"error_description,omitempty"`+ }+ form := url.Values{+ "action": []string{"poll"},+ "device_code": []string{deviceCode},+ }+ if err := c.doForm(ctx, domain, form, &resp); err != nil {+ return nil, err+ }++ // Tenant-brand-driven domain swap. Lark emits this exactly once+ // when a Lark-international account authorized; the next poll must+ // hit accounts.larksuite.com to learn the credentials. We surface+ // the swap as a typed signal so the service does not have to know+ // the brand string.+ if resp.UserInfo != nil &&+ resp.UserInfo.TenantBrand == registrationTenantBrandLark &&+ !strings.HasPrefix(domain, c.cfg.LarkDomain) {+ return &PollResult{SwitchedDomain: c.cfg.LarkDomain}, nil+ }++ // Success: both client_id AND client_secret AND the installer+ // open_id must be present. Partial responses are treated as a+ // protocol error so RegistrationService never writes a+ // half-populated lark_installation row.+ if resp.ClientID != "" && resp.ClientSecret != "" {+ if resp.UserInfo == nil || resp.UserInfo.OpenID == "" {+ return nil, &RegistrationError{+ Code: "invalid_response",+ Description: "success response missing installer open_id",+ }+ }+ return &PollResult{+ ClientID: resp.ClientID,+ ClientSecret: resp.ClientSecret,+ OpenID: OpenID(resp.UserInfo.OpenID),+ }, nil+ }++ switch resp.Error {+ case "authorization_pending", "slow_down":+ return &PollResult{Status: resp.Error}, nil+ case "access_denied", "expired_token":+ return &PollResult{+ Err: &RegistrationError{Code: resp.Error, Description: resp.ErrorDescription},+ }, nil+ case "":+ // Empty error AND empty credentials = keep polling; this+ // matches the upstream SDK's tolerant handling for the case+ // where the server briefly returns an empty body during the+ // authorize-redirect window.+ return &PollResult{Status: "authorization_pending"}, nil+ default:+ return &PollResult{+ Err: &RegistrationError{Code: resp.Error, Description: resp.ErrorDescription},+ }, nil+ }+}++func (c *RegistrationClient) doForm(ctx context.Context, domain string, form url.Values, out any) error {+ endpoint := strings.TrimRight(domain, "/") + registrationEndpoint+ req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, strings.NewReader(form.Encode()))+ if err != nil {+ return fmt.Errorf("registration: new request: %w", err)+ }+ req.Header.Set("Content-Type", "application/x-www-form-urlencoded")+ resp, err := c.cfg.HTTPClient.Do(req)+ if err != nil {+ return fmt.Errorf("registration: http do: %w", err)+ }+ defer resp.Body.Close()+ body, err := io.ReadAll(resp.Body)+ if err != nil {+ return fmt.Errorf("registration: read body: %w", err)+ }+ if len(body) == 0 {+ return &RegistrationError{+ Code: fmt.Sprintf("http_%d", resp.StatusCode),+ Description: "empty body",+ }+ }+ // RFC 8628 device-flow servers return non-2xx with a JSON body whose+ // `error` field is the actual signal — `authorization_pending` and+ // `slow_down` arrive as HTTP 400, NOT 2xx. Decoding the body first+ // and letting the caller route on `resp.Error` is what the upstream+ // Go SDK does; treating any non-2xx as a hard protocol error (the+ // previous behaviour) killed every session on the first poll because+ // the user hasn't scanned the QR yet at that point.+ if jsonErr := json.Unmarshal(body, out); jsonErr == nil {+ return nil+ }+ // Body didn't parse — surface the raw status + payload tail so ops+ // can tell a Lark outage / proxy interception apart from a schema+ // drift. Caller treats this as a terminal protocol error.+ return &RegistrationError{+ Code: fmt.Sprintf("http_%d", resp.StatusCode),+ Description: truncate(string(body), 256),+ }+}++// decorateQRCodeURL appends the SDK-style telemetry params Lark expects+// on the QR-image URL. Without `from=sdk&tp=sdk&source=<src>` the+// scanner UI on the user's phone shows a less polished prompt and Lark+// cannot attribute installs back to Multica in their analytics.+//+// namePreset, when non-empty, is appended as `name=<...>` to pre-fill+// the bot/app name on Lark's "create a PersonalAgent" form. This+// mirrors the upstream SDK's AppPreset.Name: Lark reads it from the+// verification/QR URL (the begin POST body carries no name field) and+// treats it as a user-editable default, not a locked final name.+func decorateQRCodeURL(raw, source, namePreset string) (string, error) {+ u, err := url.Parse(raw)+ if err != nil {+ return "", err+ }+ q := u.Query()+ q.Set("from", "sdk")+ q.Set("tp", "sdk")+ q.Set("source", "go-sdk/"+source)+ if namePreset != "" {+ q.Set("name", namePreset)+ }+ u.RawQuery = q.Encode()+ return u.String(), nil+}++// ErrRegistrationAccessDenied is returned by RegistrationService when+// the user explicitly denied the install in the Lark UI. Distinct from+// other terminal failures so the UI can render "you cancelled the+// install" instead of a generic error.+var ErrRegistrationAccessDenied = errors.New("lark registration: access denied by user")++// ErrRegistrationExpired is returned by RegistrationService when the+// device_code's expiry window elapsed without the user authorizing.+// Distinct so the UI can prompt "scan again — the previous QR expired".+var ErrRegistrationExpired = errors.New("lark registration: expired")diff --git a/server/internal/integrations/lark/registration_service.go b/server/internal/integrations/lark/registration_service.gonew file mode 100644index 0000000000..4efae70290--- /dev/null+++ b/server/internal/integrations/lark/registration_service.go@@ -0,0 +1,578 @@+package lark++import (+ "context"+ "crypto/rand"+ "encoding/base64"+ "errors"+ "fmt"+ "log/slog"+ "strings"+ "sync"+ "time"++ "github.com/jackc/pgx/v5/pgtype"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++// RegistrationSessionStatus is the discriminated state a `begin`+// session lives in. The HTTP status endpoint serializes the underlying+// string verbatim so the frontend can pattern-match without parsing+// prose.+type RegistrationSessionStatus string++const (+ // RegistrationStatusPending means the QR has been minted and the+ // background goroutine is still polling Lark. The frontend keeps+ // polling our status endpoint at the cadence we return in+ // poll_interval_seconds.+ RegistrationStatusPending RegistrationSessionStatus = "pending"++ // RegistrationStatusSuccess means the device-flow returned+ // credentials AND the lark_installation + installer-binding pair+ // committed. `installation_id` is populated. The frontend closes+ // the dialog and invalidates the installations cache.+ RegistrationStatusSuccess RegistrationSessionStatus = "success"++ // RegistrationStatusError means the session reached a terminal+ // failure (expired, user-denied, Lark protocol error, follow-up+ // bot-info / DB error). `error_reason` is set to a stable code so+ // the frontend can render the right copy without parsing+ // `error_message`.+ RegistrationStatusError RegistrationSessionStatus = "error"+)++// Reason codes the service stores on a failed session. Stable strings+// so the frontend can switch on them without parsing prose.+const (+ RegistrationReasonExpired = "expired"+ RegistrationReasonAccessDenied = "access_denied"+ RegistrationReasonProtocol = "lark_protocol_error"+ RegistrationReasonBotInfoFailed = "bot_info_failed"+ RegistrationReasonInstallationConflict = "installation_conflict"+ RegistrationReasonInstallerBindFailed = "installer_bind_failed"+ RegistrationReasonInternalError = "internal_error"+)++// RegistrationServiceConfig configures the service.+type RegistrationServiceConfig struct {+ // SessionTTL caps how long a successful or errored session stays in+ // the in-process cache before GC. Default 30 minutes — long enough+ // for the frontend to fetch the final status after the dialog+ // closes, short enough that abandoned sessions do not pin memory+ // forever. Independent of the device-flow expiry (Lark's+ // expire_in, ~10 min).+ SessionTTL time.Duration++ // Now is overridable for deterministic expiry-bound tests.+ Now func() time.Time++ // Logger is used for protocol-level warnings (Lark error codes,+ // post-success bot info failures). Nil uses slog.Default().+ Logger *slog.Logger+}++func (c RegistrationServiceConfig) withDefaults() RegistrationServiceConfig {+ if c.SessionTTL == 0 {+ c.SessionTTL = 30 * time.Minute+ }+ if c.Now == nil {+ c.Now = time.Now+ }+ if c.Logger == nil {+ c.Logger = slog.Default()+ }+ return c+}++// RegistrationService owns the device-flow install lifecycle. It is the+// one place that:+//+// 1. opens a new device-flow session against Lark (Begin),+// 2. tracks the session's polling state in-process,+// 3. runs the background polling goroutine,+// 4. on success, calls APIClient.GetBotInfo with the freshly minted+// credentials, then writes lark_installation + the installer's+// lark_user_binding in a single transaction.+//+// In-process session storage is intentional: device-flow sessions are+// short-lived (<10 min), the QR has no value outside the same browser+// session that initiated it, and persisting half-completed installs+// into Postgres would add a migration + GC sweep without delivering any+// product capability the user can re-use across server restarts.+type RegistrationService struct {+ cfg RegistrationServiceConfig+ client *RegistrationClient+ api APIClient+ queries *db.Queries+ tx TxStarter+ installs *InstallationService+ binder InstallerBinder+ authQueries authQueriesAdapter++ mu sync.Mutex+ sessions map[string]*registrationSession+}++// authQueriesAdapter is the minimal lookup surface the service needs+// before kicking off a session: agent ↔ workspace ownership validation.+// Kept as an interface so tests can drop in a stub instead of a real+// *db.Queries + Postgres fixture.+type authQueriesAdapter interface {+ GetAgentInWorkspace(ctx context.Context, params db.GetAgentInWorkspaceParams) (db.Agent, error)+}++// NewRegistrationService wires the device-flow client, the APIClient+// (for the post-success GetBotInfo lookup), and the DB write path. Any+// required dependency missing surfaces as a constructor error so a+// silent half-init at startup cannot leave the install button+// returning 500s at runtime.+func NewRegistrationService(+ cfg RegistrationServiceConfig,+ client *RegistrationClient,+ api APIClient,+ queries *db.Queries,+ tx TxStarter,+ installs *InstallationService,+ binder InstallerBinder,+) (*RegistrationService, error) {+ if client == nil {+ return nil, errors.New("lark registration: RegistrationClient is required")+ }+ if api == nil {+ return nil, errors.New("lark registration: APIClient is required")+ }+ if queries == nil {+ return nil, errors.New("lark registration: queries is required")+ }+ if tx == nil {+ return nil, errors.New("lark registration: TxStarter is required")+ }+ if installs == nil {+ return nil, errors.New("lark registration: InstallationService is required")+ }+ if binder == nil {+ return nil, errors.New("lark registration: InstallerBinder is required")+ }+ return &RegistrationService{+ cfg: cfg.withDefaults(),+ client: client,+ api: api,+ queries: queries,+ tx: tx,+ installs: installs,+ binder: binder,+ authQueries: queries,+ sessions: make(map[string]*registrationSession),+ }, nil+}++// registrationSession is the in-memory state for one in-flight install.+type registrationSession struct {+ id string+ workspaceID pgtype.UUID+ agentID pgtype.UUID+ initiatorID pgtype.UUID++ deviceCode string+ domain string+ qrCodeURL string+ interval time.Duration+ expiresAt time.Time++ mu sync.Mutex+ status RegistrationSessionStatus+ installationID pgtype.UUID+ errorReason string+ errorMessage string+ gcAfter time.Time+}++func (s *registrationSession) snapshot() RegistrationSessionState {+ s.mu.Lock()+ defer s.mu.Unlock()+ return RegistrationSessionState{+ ID: s.id,+ Status: s.status,+ InstallationID: s.installationID,+ ErrorReason: s.errorReason,+ ErrorMessage: s.errorMessage,+ }+}++func (s *registrationSession) markSuccess(installationID pgtype.UUID, gcAfter time.Time) {+ s.mu.Lock()+ defer s.mu.Unlock()+ s.status = RegistrationStatusSuccess+ s.installationID = installationID+ s.gcAfter = gcAfter+}++func (s *registrationSession) markError(reason, msg string, gcAfter time.Time) {+ s.mu.Lock()+ defer s.mu.Unlock()+ // Idempotent: if a parallel goroutine already terminated the+ // session (e.g. expiry fired between status reads), don't clobber+ // the first reason — the user already saw it.+ if s.status != RegistrationStatusPending {+ return+ }+ s.status = RegistrationStatusError+ s.errorReason = reason+ s.errorMessage = msg+ s.gcAfter = gcAfter+}++// RegistrationSessionState is the read-only snapshot the handler+// serializes to the frontend. Internal mutex is hidden by construction.+type RegistrationSessionState struct {+ ID string+ Status RegistrationSessionStatus+ InstallationID pgtype.UUID+ ErrorReason string+ ErrorMessage string+}++// BeginInstallParams is the trusted input from the handler — the+// workspace, agent, and initiating user have already been authenticated+// and authorized at the router (admin role on the workspace; agent+// belongs to the workspace).+type BeginInstallParams struct {+ WorkspaceID pgtype.UUID+ AgentID pgtype.UUID+ InitiatorID pgtype.UUID+}++// BeginInstallResult is the public payload the handler echoes to the+// frontend. The session_id is the opaque handle the frontend uses to+// poll status; we deliberately do NOT echo the device_code or the+// polling interval (which is internal scheduling state).+type BeginInstallResult struct {+ SessionID string+ QRCodeURL string+ ExpiresInSeconds int+ PollIntervalSeconds int+}++// BeginInstall opens a fresh device-flow session and kicks off the+// background polling goroutine. The returned payload feeds the QR-code+// dialog on the frontend; the polling goroutine runs until success,+// terminal failure, or device_code expiry.+//+// The session_id is the only opaque token returned to the browser —+// the device_code is server-side only (Lark would honor a poll from+// anywhere if the device_code leaked, so we never echo it).+func (s *RegistrationService) BeginInstall(ctx context.Context, p BeginInstallParams) (BeginInstallResult, error) {+ if !p.WorkspaceID.Valid || !p.AgentID.Valid || !p.InitiatorID.Valid {+ return BeginInstallResult{}, errors.New("lark registration: workspace, agent, and initiator are required")+ }+ // Agent ownership pre-check — without this, a workspace admin+ // could open an install session against another workspace's agent+ // by guessing the UUID, and the device_code minted against Lark+ // would still produce credentials. The handler does the same+ // check; doing it here too keeps the service self-defending.+ //+ // We keep the agent: its name pre-fills the bot name on Lark's+ // PersonalAgent creation form (see botNamePreset) so the installed+ // bot reads "<agent> - Multica" instead of "{用户姓名}的智能助手".+ agent, err := s.authQueries.GetAgentInWorkspace(ctx, db.GetAgentInWorkspaceParams{+ ID: p.AgentID,+ WorkspaceID: p.WorkspaceID,+ })+ if err != nil {+ return BeginInstallResult{}, fmt.Errorf("lark registration: agent not in workspace: %w", err)+ }++ begin, err := s.client.Begin(ctx, botNamePreset(agent.Name))+ if err != nil {+ return BeginInstallResult{}, fmt.Errorf("lark registration: begin: %w", err)+ }++ now := s.cfg.Now()+ sessionID, err := randomSessionID()+ if err != nil {+ return BeginInstallResult{}, fmt.Errorf("lark registration: mint session id: %w", err)+ }+ sess := ®istrationSession{+ id: sessionID,+ workspaceID: p.WorkspaceID,+ agentID: p.AgentID,+ initiatorID: p.InitiatorID,+ deviceCode: begin.DeviceCode,+ domain: begin.Domain,+ qrCodeURL: begin.QRCodeURL,+ interval: begin.Interval,+ expiresAt: now.Add(begin.ExpiresIn),+ status: RegistrationStatusPending,+ }+ s.mu.Lock()+ s.sessions[sessionID] = sess+ s.mu.Unlock()++ // The polling goroutine outlives the request context, so we cannot+ // reuse ctx here. We size its own context to the device_code+ // expiry — the worst case is a session that quietly times out+ // after Lark's window closes, which we surface to the user as+ // RegistrationReasonExpired on the next status read.+ go s.runPolling(sess)++ return BeginInstallResult{+ SessionID: sessionID,+ QRCodeURL: begin.QRCodeURL,+ ExpiresInSeconds: int(begin.ExpiresIn / time.Second),+ PollIntervalSeconds: int(begin.Interval / time.Second),+ }, nil+}++// GetSession returns the current state of an in-flight or recently-+// finished session. The workspace UUID is required so a session+// initiated by one workspace cannot be polled by another (the session+// id is unguessable but defense-in-depth costs nothing here).+//+// ErrRegistrationSessionNotFound is returned for unknown / expired /+// GC'd sessions; the frontend treats it the same as an error reason+// of "session_lost" — prompt the user to restart the install.+func (s *RegistrationService) GetSession(workspaceID pgtype.UUID, sessionID string) (RegistrationSessionState, error) {+ if strings.TrimSpace(sessionID) == "" {+ return RegistrationSessionState{}, ErrRegistrationSessionNotFound+ }+ s.gcExpiredLocked()+ s.mu.Lock()+ sess, ok := s.sessions[sessionID]+ s.mu.Unlock()+ if !ok {+ return RegistrationSessionState{}, ErrRegistrationSessionNotFound+ }+ if !uuidEqual(sess.workspaceID, workspaceID) {+ // Treat as not found — leaking "exists but wrong workspace"+ // would let an attacker enumerate session ids across workspaces.+ return RegistrationSessionState{}, ErrRegistrationSessionNotFound+ }+ return sess.snapshot(), nil+}++// runPolling is the background loop. The pattern matches the upstream+// SDK: wait → poll → branch on result. On any terminal outcome we+// either record the installation+binding (success) or mark the session+// errored.+func (s *RegistrationService) runPolling(sess *registrationSession) {+ // Bound the entire polling life by Lark's expiry — once that+ // window closes, no further poll can succeed.+ ctx, cancel := context.WithDeadline(context.Background(), sess.expiresAt)+ defer cancel()++ interval := sess.interval+ if interval <= 0 {+ interval = time.Duration(registrationDefaultPollSeconds) * time.Second+ }+ domain := sess.domain+ deviceCode := sess.deviceCode++ for {+ select {+ case <-ctx.Done():+ s.cfg.Logger.Info("lark registration: session expired",+ "session_id", sess.id,+ "workspace_id", uuidString(sess.workspaceID))+ sess.markError(RegistrationReasonExpired, "QR expired before authorization", s.gcDeadline())+ return+ case <-time.After(interval):+ }++ res, err := s.client.Poll(ctx, domain, deviceCode)+ if err != nil {+ var re *RegistrationError+ if errors.As(err, &re) {+ s.cfg.Logger.Warn("lark registration: protocol error",+ "session_id", sess.id, "code", re.Code, "desc", re.Description)+ sess.markError(RegistrationReasonProtocol, re.Error(), s.gcDeadline())+ return+ }+ // Transient transport error (DNS, network) — log and try+ // again on the next tick rather than killing the session,+ // which lets a 30-second cross-region blip self-heal.+ s.cfg.Logger.Warn("lark registration: transport error, will retry",+ "session_id", sess.id, "err", err)+ continue+ }++ switch {+ case res.SwitchedDomain != "":+ // Tenant-brand switch — re-aim immediately without+ // honoring the interval, matching the upstream SDK's+ // behavior. Lark emits the brand hint exactly once on the+ // transition poll and the credential-bearing response+ // lands on the next call to the new domain.+ domain = res.SwitchedDomain+ s.cfg.Logger.Info("lark registration: switched to lark-international domain",+ "session_id", sess.id, "domain", domain)+ continue+ case res.ClientID != "" && res.ClientSecret != "":+ s.finishSuccess(ctx, sess, res)+ return+ case res.Err != nil:+ reason := RegistrationReasonProtocol+ if res.Err.Code == "access_denied" {+ reason = RegistrationReasonAccessDenied+ } else if res.Err.Code == "expired_token" {+ reason = RegistrationReasonExpired+ }+ s.cfg.Logger.Info("lark registration: terminal error",+ "session_id", sess.id, "code", res.Err.Code, "desc", res.Err.Description)+ sess.markError(reason, res.Err.Error(), s.gcDeadline())+ return+ case res.Status == "slow_down":+ // Honor Lark's back-off — bump by 5s, per RFC 8628 §3.5.+ interval += 5 * time.Second+ default:+ // authorization_pending — keep the interval, loop.+ }+ }+}++// finishSuccess runs the post-poll finalization: bot info lookup ++// installation insert + installer binding, all in a single DB+// transaction.+func (s *RegistrationService) finishSuccess(ctx context.Context, sess *registrationSession, res *PollResult) {+ creds := InstallationCredentials{AppID: res.ClientID, AppSecret: res.ClientSecret}+ info, err := s.api.GetBotInfo(ctx, creds)+ if err != nil {+ s.cfg.Logger.Warn("lark registration: bot info failed",+ "session_id", sess.id, "err", err)+ sess.markError(RegistrationReasonBotInfoFailed, err.Error(), s.gcDeadline())+ return+ }+ if info.OpenID == "" {+ sess.markError(RegistrationReasonBotInfoFailed, "bot info missing open_id", s.gcDeadline())+ return+ }++ // Encrypt the app_secret before the transaction so the seal cost+ // doesn't sit inside the DB lock. The InstallationService's Upsert+ // would do this for us, but we need the encrypted blob inside the+ // transaction-scoped queries handle so the installer-bind commits+ // alongside the installation insert — replicate the Seal here.+ sealed, err := s.installs.box.Seal([]byte(res.ClientSecret))+ if err != nil {+ s.cfg.Logger.Error("lark registration: seal app_secret",+ "session_id", sess.id, "err", err)+ sess.markError(RegistrationReasonInternalError, err.Error(), s.gcDeadline())+ return+ }++ tx, err := s.tx.Begin(ctx)+ if err != nil {+ s.cfg.Logger.Error("lark registration: begin tx",+ "session_id", sess.id, "err", err)+ sess.markError(RegistrationReasonInternalError, err.Error(), s.gcDeadline())+ return+ }+ defer tx.Rollback(ctx)+ qtx := s.queries.WithTx(tx)++ inst, err := qtx.UpsertLarkInstallation(ctx, db.UpsertLarkInstallationParams{+ WorkspaceID: sess.workspaceID,+ AgentID: sess.agentID,+ AppID: res.ClientID,+ AppSecretEncrypted: sealed,+ BotOpenID: string(info.OpenID),+ BotUnionID: textOrNull(info.UnionID),+ InstallerUserID: sess.initiatorID,+ })+ if err != nil {+ s.cfg.Logger.Warn("lark registration: upsert installation",+ "session_id", sess.id, "err", err)+ sess.markError(RegistrationReasonInstallationConflict, err.Error(), s.gcDeadline())+ return+ }++ if err := s.binder.BindInstallerTx(ctx, qtx, InstallerBindParams{+ WorkspaceID: sess.workspaceID,+ InstallationID: inst.ID,+ MulticaUserID: sess.initiatorID,+ LarkOpenID: res.OpenID,+ }); err != nil {+ s.cfg.Logger.Warn("lark registration: bind installer",+ "session_id", sess.id, "err", err)+ sess.markError(RegistrationReasonInstallerBindFailed, err.Error(), s.gcDeadline())+ return+ }++ if err := tx.Commit(ctx); err != nil {+ s.cfg.Logger.Error("lark registration: commit",+ "session_id", sess.id, "err", err)+ sess.markError(RegistrationReasonInternalError, err.Error(), s.gcDeadline())+ return+ }+ sess.markSuccess(inst.ID, s.gcDeadline())+ s.cfg.Logger.Info("lark registration: install complete",+ "session_id", sess.id,+ "workspace_id", uuidString(sess.workspaceID),+ "agent_id", uuidString(sess.agentID),+ "installation_id", uuidString(inst.ID))+}++func (s *RegistrationService) gcDeadline() time.Time {+ return s.cfg.Now().Add(s.cfg.SessionTTL)+}++// gcExpiredLocked drops any session whose `gcAfter` is in the past.+// Pending sessions are NOT GC'd here — runPolling will set their+// gcAfter when it terminates, and an expired-by-deadline session+// closes itself.+func (s *RegistrationService) gcExpiredLocked() {+ now := s.cfg.Now()+ s.mu.Lock()+ defer s.mu.Unlock()+ for id, sess := range s.sessions {+ sess.mu.Lock()+ drop := !sess.gcAfter.IsZero() && sess.gcAfter.Before(now)+ sess.mu.Unlock()+ if drop {+ delete(s.sessions, id)+ }+ }+}++// ErrRegistrationSessionNotFound is what the service returns for+// unknown / GC'd sessions. The handler maps it to 404.+var ErrRegistrationSessionNotFound = errors.New("lark registration: session not found")++func randomSessionID() (string, error) {+ buf := make([]byte, 24)+ if _, err := rand.Read(buf); err != nil {+ return "", err+ }+ return base64.RawURLEncoding.EncodeToString(buf), nil+}++func uuidEqual(a, b pgtype.UUID) bool {+ if !a.Valid || !b.Valid {+ return false+ }+ return a.Bytes == b.Bytes+}++// botNamePreset builds the display name we pre-fill on Lark's+// PersonalAgent creation form so the installed bot reads+// "<agent> - Multica" instead of Lark's auto-generated+// "{用户姓名}的智能助手". Lark treats this as a default the installer can+// still edit; we never get to lock the final name. A blank agent name+// (defensive — Agent.Name is NOT NULL in schema) degrades to plain+// "Multica" rather than a dangling " - Multica".+func botNamePreset(agentName string) string {+ name := strings.TrimSpace(agentName)+ if name == "" {+ return "Multica"+ }+ return name + " - Multica"+}++// uuidString is the package-local UUID-to-string helper defined in+// hub.go; redeclared `func uuidString(u pgtype.UUID) string` removed+// to avoid the symbol collision.+//+// InstallationService.box is unexported but reachable from this file+// because both live in package `lark`; we read it directly in+// finishSuccess so the Seal happens outside the DB transaction (which+// would otherwise hold a row lock across the crypto call).diff --git a/server/internal/integrations/lark/registration_service_test.go b/server/internal/integrations/lark/registration_service_test.gonew file mode 100644index 0000000000..d9d88914ae--- /dev/null+++ b/server/internal/integrations/lark/registration_service_test.go@@ -0,0 +1,277 @@+package lark++import (+ "context"+ "errors"+ "strings"+ "sync"+ "testing"+ "time"++ "github.com/jackc/pgx/v5"+ "github.com/jackc/pgx/v5/pgtype"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++// These tests cover the pure-Go halves of RegistrationService —+// constructor validation, session-id security boundary, status code+// mapping — without touching the database. The polling goroutine's+// DB-write paths (UpsertLarkInstallation + BindInstallerTx in one tx)+// require a real Postgres + sqlc-generated *db.Queries and are+// covered by an integration test against the migration suite.++// TestRegistrationServiceConstructorValidatesDeps pins that every+// required dependency surfaces as a constructor error rather than a+// runtime panic inside BeginInstall — a half-init at startup would+// otherwise leave the install button returning 500s with no signal in+// the logs.+func TestRegistrationServiceConstructorValidatesDeps(t *testing.T) {+ client := NewRegistrationClient(RegistrationConfig{})+ api := NewStubAPIClient(nil)+ cases := []struct {+ name string+ fn func() error+ needle string+ }{+ {"missing client", func() error {+ _, err := NewRegistrationService(RegistrationServiceConfig{}, nil, api, &db.Queries{}, fakeTxStarter{}, &InstallationService{}, &fakeInstallerBinder{})+ return err+ }, "RegistrationClient"},+ {"missing api", func() error {+ _, err := NewRegistrationService(RegistrationServiceConfig{}, client, nil, &db.Queries{}, fakeTxStarter{}, &InstallationService{}, &fakeInstallerBinder{})+ return err+ }, "APIClient"},+ {"missing queries", func() error {+ _, err := NewRegistrationService(RegistrationServiceConfig{}, client, api, nil, fakeTxStarter{}, &InstallationService{}, &fakeInstallerBinder{})+ return err+ }, "queries"},+ {"missing tx", func() error {+ _, err := NewRegistrationService(RegistrationServiceConfig{}, client, api, &db.Queries{}, nil, &InstallationService{}, &fakeInstallerBinder{})+ return err+ }, "TxStarter"},+ {"missing installs", func() error {+ _, err := NewRegistrationService(RegistrationServiceConfig{}, client, api, &db.Queries{}, fakeTxStarter{}, nil, &fakeInstallerBinder{})+ return err+ }, "InstallationService"},+ {"missing binder", func() error {+ _, err := NewRegistrationService(RegistrationServiceConfig{}, client, api, &db.Queries{}, fakeTxStarter{}, &InstallationService{}, nil)+ return err+ }, "InstallerBinder"},+ }+ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ err := tc.fn()+ if err == nil || !strings.Contains(err.Error(), tc.needle) {+ t.Errorf("want error mentioning %q, got %v", tc.needle, err)+ }+ })+ }+}++// TestBotNamePreset pins the bot-name pre-fill format that rides on the+// QR URL: "<agent> - Multica", with a blank agent name degrading to+// plain "Multica" rather than a dangling " - Multica".+func TestBotNamePreset(t *testing.T) {+ cases := []struct{ in, want string }{+ {"Ada", "Ada - Multica"},+ {" Ada ", "Ada - Multica"},+ {"产品助手", "产品助手 - Multica"},+ {"", "Multica"},+ {" ", "Multica"},+ }+ for _, tc := range cases {+ if got := botNamePreset(tc.in); got != tc.want {+ t.Errorf("botNamePreset(%q) = %q, want %q", tc.in, got, tc.want)+ }+ }+}++// TestRegistrationGetSessionNotFound pins both halves of the+// not-found path: unknown session id, and (the security-critical one)+// known session id but from a different workspace. Both must surface+// the same ErrRegistrationSessionNotFound — leaking "exists but wrong+// workspace" would let an attacker enumerate session ids across+// workspaces.+func TestRegistrationGetSessionNotFound(t *testing.T) {+ s := newRegistrationServiceForTest(t)+ ws := uuidFromStringSvc(t, "11111111-1111-1111-1111-111111111111")+ otherWs := uuidFromStringSvc(t, "22222222-2222-2222-2222-222222222222")++ if _, err := s.GetSession(ws, "nope"); !errors.Is(err, ErrRegistrationSessionNotFound) {+ t.Errorf("unknown session: want ErrRegistrationSessionNotFound, got %v", err)+ }++ // Plant a session by hand for the cross-workspace test (BeginInstall+ // requires a live DB; we are only exercising the lookup boundary).+ s.mu.Lock()+ s.sessions["plant-1"] = ®istrationSession{+ id: "plant-1",+ workspaceID: ws,+ status: RegistrationStatusPending,+ }+ s.mu.Unlock()++ if _, err := s.GetSession(otherWs, "plant-1"); !errors.Is(err, ErrRegistrationSessionNotFound) {+ t.Errorf("cross-workspace lookup: want ErrRegistrationSessionNotFound, got %v", err)+ }++ state, err := s.GetSession(ws, "plant-1")+ if err != nil {+ t.Fatalf("same-workspace lookup: %v", err)+ }+ if state.Status != RegistrationStatusPending {+ t.Errorf("Status: got %q want pending", state.Status)+ }+}++// TestRegistrationGetSessionGCsExpiredEntries pins that a session+// whose gcAfter is in the past is dropped on the next lookup, so the+// in-memory map cannot grow unbounded across restarts of long-lived+// servers.+func TestRegistrationGetSessionGCsExpiredEntries(t *testing.T) {+ clock := &fakeClockSvc{now: time.Unix(1_700_000_000, 0)}+ s := newRegistrationServiceForTest(t)+ s.cfg.Now = clock.Now+ ws := uuidFromStringSvc(t, "11111111-1111-1111-1111-111111111111")++ s.mu.Lock()+ s.sessions["expired"] = ®istrationSession{+ id: "expired",+ workspaceID: ws,+ status: RegistrationStatusError,+ gcAfter: clock.Now().Add(-1 * time.Minute),+ }+ s.sessions["live"] = ®istrationSession{+ id: "live",+ workspaceID: ws,+ status: RegistrationStatusSuccess,+ gcAfter: clock.Now().Add(10 * time.Minute),+ }+ s.mu.Unlock()++ // Lookup of any id triggers gcExpiredLocked — the expired one+ // disappears, the live one stays.+ if _, err := s.GetSession(ws, "live"); err != nil {+ t.Errorf("live session lookup: %v", err)+ }+ if _, err := s.GetSession(ws, "expired"); !errors.Is(err, ErrRegistrationSessionNotFound) {+ t.Errorf("expired session lookup: want not-found, got %v", err)+ }+ s.mu.Lock()+ _, expiredExists := s.sessions["expired"]+ s.mu.Unlock()+ if expiredExists {+ t.Errorf("GC should have dropped the expired session from the map")+ }+}++// TestRegistrationSessionMarkErrorIsIdempotent guards against a+// double-fire race between the expiry timer and a Poll-driven terminal+// error: whichever fires first wins, and the second mark must NOT+// clobber the first reason (the user already saw it).+func TestRegistrationSessionMarkErrorIsIdempotent(t *testing.T) {+ sess := ®istrationSession{+ id: "x",+ status: RegistrationStatusPending,+ }+ deadline := time.Unix(1_700_001_000, 0)+ sess.markError(RegistrationReasonAccessDenied, "user denied", deadline)+ sess.markError(RegistrationReasonExpired, "qr expired", deadline) // second mark — should no-op+ st := sess.snapshot()+ if st.ErrorReason != RegistrationReasonAccessDenied {+ t.Errorf("first reason should win; got %q", st.ErrorReason)+ }+}++// TestRegistrationSessionStateSnapshotIsValueCopy pins that the+// snapshot does not return a pointer alias of the internal session —+// a leaked alias would let the handler's serializer race the polling+// goroutine on field reads. The snapshot is value-copied so the+// caller can read it without holding the session mutex.+func TestRegistrationSessionStateSnapshotIsValueCopy(t *testing.T) {+ sess := ®istrationSession{+ id: "x",+ status: RegistrationStatusPending,+ }+ s1 := sess.snapshot()+ deadline := time.Unix(1_700_001_000, 0)+ sess.markSuccess(uuidFromStringSvc(t, "33333333-3333-3333-3333-333333333333"), deadline)+ if s1.Status != RegistrationStatusPending {+ t.Errorf("snapshot must be a value copy; got mutated to %q", s1.Status)+ }+ s2 := sess.snapshot()+ if s2.Status != RegistrationStatusSuccess {+ t.Errorf("second snapshot should reflect new state; got %q", s2.Status)+ }+}++// TestRandomSessionIDUnique pins the in-process collision risk: 1024+// rounds with no duplicate is enough headroom for the 24-byte input+// (~10^57 keyspace) and matches the bar applied to randomToken.+func TestRandomSessionIDUnique(t *testing.T) {+ seen := map[string]struct{}{}+ for i := 0; i < 1024; i++ {+ id, err := randomSessionID()+ if err != nil {+ t.Fatalf("randomSessionID: %v", err)+ }+ if _, dup := seen[id]; dup {+ t.Fatalf("duplicate after %d iterations: %q", i, id)+ }+ seen[id] = struct{}{}+ }+}++// fakeInstallerBinder records BindInstallerTx calls for tests that+// need to assert the bind happened.+type fakeInstallerBinder struct {+ mu sync.Mutex+ calls []InstallerBindParams+ err error+}++func (f *fakeInstallerBinder) BindInstallerTx(_ context.Context, _ *db.Queries, p InstallerBindParams) error {+ f.mu.Lock()+ defer f.mu.Unlock()+ f.calls = append(f.calls, p)+ return f.err+}++// fakeTxStarter is a TxStarter stub for constructor tests — never+// actually called.+type fakeTxStarter struct{}++func (fakeTxStarter) Begin(_ context.Context) (pgx.Tx, error) {+ return nil, errors.New("fakeTxStarter Begin not implemented")+}++// newRegistrationServiceForTest constructs a service with all+// dependencies mocked / nil — the GetSession boundary does not exercise+// the polling goroutine, so the unused deps stay zero.+func newRegistrationServiceForTest(t *testing.T) *RegistrationService {+ t.Helper()+ return &RegistrationService{+ cfg: RegistrationServiceConfig{}.withDefaults(),+ sessions: make(map[string]*registrationSession),+ }+}++func uuidFromStringSvc(t *testing.T, s string) pgtype.UUID {+ t.Helper()+ var u pgtype.UUID+ if err := u.Scan(s); err != nil {+ t.Fatalf("scan uuid: %v", err)+ }+ return u+}++type fakeClockSvc struct {+ mu sync.Mutex+ now time.Time+}++func (c *fakeClockSvc) Now() time.Time {+ c.mu.Lock()+ defer c.mu.Unlock()+ return c.now+}diff --git a/server/internal/integrations/lark/registration_test.go b/server/internal/integrations/lark/registration_test.gonew file mode 100644index 0000000000..ea65b954b5--- /dev/null+++ b/server/internal/integrations/lark/registration_test.go@@ -0,0 +1,467 @@+package lark++import (+ "context"+ "errors"+ "net/http"+ "net/http/httptest"+ "net/url"+ "strings"+ "sync/atomic"+ "testing"+ "time"+)++// registrationFake is a tiny HTTP stand-in for accounts.feishu.cn /+// accounts.larksuite.com. Each test registers a sequence of poll+// handlers and assertions about what the client sent.+type registrationFake struct {+ t *testing.T+ srv *httptest.Server+ mux *http.ServeMux++ beginN atomic.Int32+ pollN atomic.Int32+}++func newRegistrationFake(t *testing.T) *registrationFake {+ t.Helper()+ f := ®istrationFake{t: t, mux: http.NewServeMux()}+ f.srv = httptest.NewServer(f.mux)+ t.Cleanup(f.srv.Close)+ return f+}++func (f *registrationFake) URL() string { return f.srv.URL }++// stubBegin pins the /oauth/v1/app/registration response for action=begin.+// Verifies the client sent the canonical PersonalAgent registration form.+func (f *registrationFake) stubBegin(resp map[string]any) {+ f.mux.HandleFunc(registrationEndpoint, func(w http.ResponseWriter, r *http.Request) {+ _ = r.ParseForm()+ switch r.Form.Get("action") {+ case "begin":+ f.beginN.Add(1)+ if got := r.Form.Get("archetype"); got != "PersonalAgent" {+ f.t.Errorf("begin: archetype=%q want PersonalAgent", got)+ }+ if got := r.Form.Get("auth_method"); got != "client_secret" {+ f.t.Errorf("begin: auth_method=%q want client_secret", got)+ }+ if got := r.Form.Get("request_user_info"); got != "open_id" {+ f.t.Errorf("begin: request_user_info=%q want open_id", got)+ }+ writeJSON(w, resp)+ case "poll":+ f.t.Errorf("poll called before stubBegin handler was replaced — tests should set stubPoll explicitly")+ default:+ f.t.Errorf("unknown action: %q", r.Form.Get("action"))+ }+ })+}++// rewriteHandler replaces /oauth/v1/app/registration with a fresh+// handler — used to install a poll script after Begin has been+// exercised.+func (f *registrationFake) rewriteHandler(h http.HandlerFunc) {+ f.mux = http.NewServeMux()+ f.mux.HandleFunc(registrationEndpoint, h)+ f.srv.Config.Handler = f.mux+}++func TestRegistrationClient_Begin_HappyPath(t *testing.T) {+ fake := newRegistrationFake(t)+ fake.stubBegin(map[string]any{+ "device_code": "dc_xyz",+ "verification_uri_complete": "https://accounts.feishu.cn/oauth/v1/qrcode?code=abc",+ "verification_uri": "https://accounts.feishu.cn/oauth/v1/qrcode",+ "user_code": "ABCD-EFGH",+ "interval": 3,+ "expire_in": 600,+ })++ c := NewRegistrationClient(RegistrationConfig{Domain: fake.URL()})+ res, err := c.Begin(context.Background(), "Ada - Multica")+ if err != nil {+ t.Fatalf("Begin: %v", err)+ }+ if res.DeviceCode != "dc_xyz" {+ t.Errorf("DeviceCode: got %q", res.DeviceCode)+ }+ if res.Interval != 3*time.Second {+ t.Errorf("Interval: got %v want 3s", res.Interval)+ }+ if res.ExpiresIn != 600*time.Second {+ t.Errorf("ExpiresIn: got %v want 600s", res.ExpiresIn)+ }+ if res.Domain != fake.URL() {+ t.Errorf("Domain: got %q want %q", res.Domain, fake.URL())+ }+ // QR URL must carry the SDK telemetry params Lark expects so the+ // scanner UI surfaces the polished prompt on the user's phone.+ u, err := url.Parse(res.QRCodeURL)+ if err != nil {+ t.Fatalf("QRCodeURL: %v", err)+ }+ q := u.Query()+ if q.Get("from") != "sdk" {+ t.Errorf("qr from=%q want sdk", q.Get("from"))+ }+ if q.Get("tp") != "sdk" {+ t.Errorf("qr tp=%q want sdk", q.Get("tp"))+ }+ if !strings.HasPrefix(q.Get("source"), "go-sdk/multica") {+ t.Errorf("qr source=%q want go-sdk/multica", q.Get("source"))+ }+ // The name preset pre-fills the Lark PersonalAgent creation form so+ // the bot defaults to "<agent> - Multica" rather than the+ // auto-generated "{用户姓名}的智能助手".+ if q.Get("name") != "Ada - Multica" {+ t.Errorf("qr name=%q want %q", q.Get("name"), "Ada - Multica")+ }+}++// TestRegistrationClient_Begin_OmitsNameWhenPresetEmpty pins that an+// empty preset leaves the `name` param off the QR URL entirely (rather+// than emitting name= and pre-filling a blank), so the begin path is+// unchanged when no preset is supplied.+func TestRegistrationClient_Begin_OmitsNameWhenPresetEmpty(t *testing.T) {+ fake := newRegistrationFake(t)+ fake.stubBegin(map[string]any{+ "device_code": "dc_noname",+ "verification_uri_complete": "https://accounts.feishu.cn/oauth/v1/qrcode?code=abc",+ })++ c := NewRegistrationClient(RegistrationConfig{Domain: fake.URL()})+ res, err := c.Begin(context.Background(), "")+ if err != nil {+ t.Fatalf("Begin: %v", err)+ }+ u, err := url.Parse(res.QRCodeURL)+ if err != nil {+ t.Fatalf("QRCodeURL: %v", err)+ }+ if _, ok := u.Query()["name"]; ok {+ t.Errorf("qr URL should omit name when preset empty, got %q", res.QRCodeURL)+ }+}++func TestRegistrationClient_Begin_DefaultsWhenServerOmitsTimers(t *testing.T) {+ // When Lark's response omits `interval` / `expire_in` (the empty+ // path the upstream SDK accepts), the client falls back to its+ // documented defaults rather than zero-second polling that would+ // hammer the endpoint or zero-second expiry that would fail the+ // very first poll.+ fake := newRegistrationFake(t)+ fake.stubBegin(map[string]any{+ "device_code": "dc_default",+ "verification_uri_complete": "https://accounts.feishu.cn/oauth/v1/qrcode?code=abc",+ })++ c := NewRegistrationClient(RegistrationConfig{Domain: fake.URL()})+ res, err := c.Begin(context.Background(), "")+ if err != nil {+ t.Fatalf("Begin: %v", err)+ }+ if res.Interval != time.Duration(registrationDefaultPollSeconds)*time.Second {+ t.Errorf("interval default: got %v", res.Interval)+ }+ if res.ExpiresIn != time.Duration(registrationDefaultExpireSeconds)*time.Second {+ t.Errorf("expire default: got %v", res.ExpiresIn)+ }+}++func TestRegistrationClient_Begin_LarkError(t *testing.T) {+ fake := newRegistrationFake(t)+ fake.stubBegin(map[string]any{+ "error": "invalid_request",+ "error_description": "missing archetype",+ })+ c := NewRegistrationClient(RegistrationConfig{Domain: fake.URL()})+ _, err := c.Begin(context.Background(), "")+ if err == nil {+ t.Fatal("expected error from Lark error response")+ }+ var re *RegistrationError+ if !errorsAs(err, &re) {+ t.Fatalf("want *RegistrationError, got %T %v", err, err)+ }+ if re.Code != "invalid_request" {+ t.Errorf("Code: got %q want invalid_request", re.Code)+ }+}++func TestRegistrationClient_Begin_HTTPNon2xx(t *testing.T) {+ fake := newRegistrationFake(t)+ fake.mux.HandleFunc(registrationEndpoint, func(w http.ResponseWriter, r *http.Request) {+ w.WriteHeader(500)+ _, _ = w.Write([]byte("server boom"))+ })+ c := NewRegistrationClient(RegistrationConfig{Domain: fake.URL()})+ _, err := c.Begin(context.Background(), "")+ if err == nil {+ t.Fatal("want error on 500")+ }+ var re *RegistrationError+ if !errorsAs(err, &re) || re.Code != "http_500" {+ t.Errorf("want http_500 RegistrationError, got %v", err)+ }+}++func TestRegistrationClient_Poll_AuthorizationPending(t *testing.T) {+ fake := newRegistrationFake(t)+ fake.mux.HandleFunc(registrationEndpoint, func(w http.ResponseWriter, r *http.Request) {+ writeJSON(w, map[string]any{"error": "authorization_pending"})+ })+ c := NewRegistrationClient(RegistrationConfig{Domain: fake.URL()})+ res, err := c.Poll(context.Background(), fake.URL(), "dc_x")+ if err != nil {+ t.Fatalf("Poll: %v", err)+ }+ if res.Status != "authorization_pending" {+ t.Errorf("Status: got %q want authorization_pending", res.Status)+ }+ if res.ClientID != "" || res.SwitchedDomain != "" || res.Err != nil {+ t.Errorf("unexpected populated fields: %+v", res)+ }+}++// TestRegistrationClient_Poll_AuthorizationPendingHTTP400 pins the+// RFC 8628 transport behaviour Lark actually uses: the device-flow+// polling endpoint returns HTTP 400 with the JSON body+// `{"error":"authorization_pending"}` while the user hasn't scanned+// the QR yet. The previous transport treated any non-2xx as a+// terminal protocol error, which killed every install session on the+// first poll and made the QR dialog silently empty in the UI —+// because the frontend received status="error" + lark_protocol_error+// within seconds of opening the dialog.+//+// Verified against the live Lark service: it returns HTTP 400 with+// `code=20094` for the wait-state, not HTTP 200.+func TestRegistrationClient_Poll_AuthorizationPendingHTTP400(t *testing.T) {+ fake := newRegistrationFake(t)+ fake.mux.HandleFunc(registrationEndpoint, func(w http.ResponseWriter, r *http.Request) {+ w.Header().Set("Content-Type", "application/json")+ w.WriteHeader(http.StatusBadRequest)+ _, _ = w.Write([]byte(`{"error":"authorization_pending","error_description":"","code":20094}`))+ })+ c := NewRegistrationClient(RegistrationConfig{Domain: fake.URL()})+ res, err := c.Poll(context.Background(), fake.URL(), "dc_x")+ if err != nil {+ t.Fatalf("Poll: %v", err)+ }+ if res.Status != "authorization_pending" {+ t.Errorf("Status: got %q want authorization_pending (HTTP 400 should NOT be a terminal error)", res.Status)+ }+ if res.Err != nil {+ t.Errorf("PollResult.Err should be nil for authorization_pending wait state, got %+v", res.Err)+ }+}++// TestRegistrationClient_Poll_AccessDeniedHTTP400 verifies the+// adjacent path: HTTP 400 with `error=access_denied` IS terminal (user+// cancelled in the Lark UI). The fix in doForm must distinguish these+// two cases by the body's `error` field, not by the HTTP status.+func TestRegistrationClient_Poll_AccessDeniedHTTP400(t *testing.T) {+ fake := newRegistrationFake(t)+ fake.mux.HandleFunc(registrationEndpoint, func(w http.ResponseWriter, r *http.Request) {+ w.Header().Set("Content-Type", "application/json")+ w.WriteHeader(http.StatusBadRequest)+ _, _ = w.Write([]byte(`{"error":"access_denied","error_description":"user cancelled"}`))+ })+ c := NewRegistrationClient(RegistrationConfig{Domain: fake.URL()})+ res, err := c.Poll(context.Background(), fake.URL(), "dc_x")+ if err != nil {+ t.Fatalf("Poll: %v", err)+ }+ if res.Err == nil || res.Err.Code != "access_denied" {+ t.Errorf("PollResult.Err: got %+v; want access_denied", res.Err)+ }+}++// TestRegistrationClient_Poll_HTTP500UnparseableIsTerminal pins the+// fallback: a non-JSON 5xx (e.g. proxy returning a HTML error page) is+// still surfaced as a typed protocol error so ops can tell a Lark+// outage from a schema drift.+func TestRegistrationClient_Poll_HTTP500UnparseableIsTerminal(t *testing.T) {+ fake := newRegistrationFake(t)+ fake.mux.HandleFunc(registrationEndpoint, func(w http.ResponseWriter, r *http.Request) {+ w.WriteHeader(http.StatusBadGateway)+ _, _ = w.Write([]byte("<html><body>502 Bad Gateway</body></html>"))+ })+ c := NewRegistrationClient(RegistrationConfig{Domain: fake.URL()})+ _, err := c.Poll(context.Background(), fake.URL(), "dc_x")+ if err == nil {+ t.Fatal("want error on unparseable 502 body")+ }+ var re *RegistrationError+ if !errorsAs(err, &re) || re.Code != "http_502" {+ t.Errorf("want http_502 RegistrationError, got %v", err)+ }+}++func TestRegistrationClient_Poll_SlowDown(t *testing.T) {+ fake := newRegistrationFake(t)+ fake.mux.HandleFunc(registrationEndpoint, func(w http.ResponseWriter, r *http.Request) {+ writeJSON(w, map[string]any{"error": "slow_down"})+ })+ c := NewRegistrationClient(RegistrationConfig{Domain: fake.URL()})+ res, err := c.Poll(context.Background(), fake.URL(), "dc_x")+ if err != nil {+ t.Fatalf("Poll: %v", err)+ }+ if res.Status != "slow_down" {+ t.Errorf("Status: got %q want slow_down", res.Status)+ }+}++func TestRegistrationClient_Poll_EmptyBodyTreatedAsPending(t *testing.T) {+ // Lark sometimes returns an empty {}; treating it as "keep polling"+ // matches the upstream SDK and avoids a spurious abort during the+ // window between the user authorizing and the credentials being+ // minted on Lark's side.+ fake := newRegistrationFake(t)+ fake.mux.HandleFunc(registrationEndpoint, func(w http.ResponseWriter, r *http.Request) {+ writeJSON(w, map[string]any{})+ })+ c := NewRegistrationClient(RegistrationConfig{Domain: fake.URL()})+ res, err := c.Poll(context.Background(), fake.URL(), "dc_x")+ if err != nil {+ t.Fatalf("Poll: %v", err)+ }+ if res.Status != "authorization_pending" {+ t.Errorf("Status: got %q want authorization_pending", res.Status)+ }+}++func TestRegistrationClient_Poll_DomainSwitchOnLarkTenant(t *testing.T) {+ fake := newRegistrationFake(t)+ fake.mux.HandleFunc(registrationEndpoint, func(w http.ResponseWriter, r *http.Request) {+ writeJSON(w, map[string]any{+ "user_info": map[string]any{"tenant_brand": "lark"},+ })+ })+ // LarkDomain points at a *distinct* host so we can assert the+ // switch surfaced the right value. We do NOT actually want the+ // client to hit it during this single Poll call — the switch+ // signal is consumed by RegistrationService, which re-polls+ // against the new host on the NEXT iteration.+ c := NewRegistrationClient(RegistrationConfig{+ Domain: fake.URL(),+ LarkDomain: "https://lark-international.test",+ })+ res, err := c.Poll(context.Background(), fake.URL(), "dc_x")+ if err != nil {+ t.Fatalf("Poll: %v", err)+ }+ if res.SwitchedDomain != "https://lark-international.test" {+ t.Errorf("SwitchedDomain: got %q", res.SwitchedDomain)+ }+}++func TestRegistrationClient_Poll_Success(t *testing.T) {+ fake := newRegistrationFake(t)+ fake.mux.HandleFunc(registrationEndpoint, func(w http.ResponseWriter, r *http.Request) {+ writeJSON(w, map[string]any{+ "client_id": "cli_personal_42",+ "client_secret": "secret_42",+ "user_info": map[string]any{"open_id": "ou_installer_42", "tenant_brand": "feishu"},+ })+ })+ c := NewRegistrationClient(RegistrationConfig{Domain: fake.URL()})+ res, err := c.Poll(context.Background(), fake.URL(), "dc_x")+ if err != nil {+ t.Fatalf("Poll: %v", err)+ }+ if res.ClientID != "cli_personal_42" {+ t.Errorf("ClientID: got %q", res.ClientID)+ }+ if res.ClientSecret != "secret_42" {+ t.Errorf("ClientSecret: got %q", res.ClientSecret)+ }+ if string(res.OpenID) != "ou_installer_42" {+ t.Errorf("OpenID: got %q", res.OpenID)+ }+}++func TestRegistrationClient_Poll_SuccessMissingOpenIDIsProtocolError(t *testing.T) {+ // A "success" response without the installer open_id would leave+ // the auto-bind step with nothing to insert. Treat that as a hard+ // protocol error so RegistrationService never writes a half-built+ // installation row.+ fake := newRegistrationFake(t)+ fake.mux.HandleFunc(registrationEndpoint, func(w http.ResponseWriter, r *http.Request) {+ writeJSON(w, map[string]any{+ "client_id": "cli_personal_42",+ "client_secret": "secret_42",+ })+ })+ c := NewRegistrationClient(RegistrationConfig{Domain: fake.URL()})+ _, err := c.Poll(context.Background(), fake.URL(), "dc_x")+ if err == nil {+ t.Fatal("want error on success-without-open_id")+ }+ var re *RegistrationError+ if !errorsAs(err, &re) || re.Code != "invalid_response" {+ t.Errorf("want invalid_response, got %v", err)+ }+}++func TestRegistrationClient_Poll_AccessDenied(t *testing.T) {+ fake := newRegistrationFake(t)+ fake.mux.HandleFunc(registrationEndpoint, func(w http.ResponseWriter, r *http.Request) {+ writeJSON(w, map[string]any{+ "error": "access_denied",+ "error_description": "user denied install",+ })+ })+ c := NewRegistrationClient(RegistrationConfig{Domain: fake.URL()})+ res, err := c.Poll(context.Background(), fake.URL(), "dc_x")+ if err != nil {+ t.Fatalf("Poll: %v", err)+ }+ if res.Err == nil || res.Err.Code != "access_denied" {+ t.Errorf("Err: %+v", res.Err)+ }+}++func TestRegistrationClient_Poll_ExpiredToken(t *testing.T) {+ fake := newRegistrationFake(t)+ fake.mux.HandleFunc(registrationEndpoint, func(w http.ResponseWriter, r *http.Request) {+ writeJSON(w, map[string]any{"error": "expired_token"})+ })+ c := NewRegistrationClient(RegistrationConfig{Domain: fake.URL()})+ res, err := c.Poll(context.Background(), fake.URL(), "dc_x")+ if err != nil {+ t.Fatalf("Poll: %v", err)+ }+ if res.Err == nil || res.Err.Code != "expired_token" {+ t.Errorf("Err: %+v", res.Err)+ }+}++func TestRegistrationClient_Poll_UnknownErrorPassesThrough(t *testing.T) {+ fake := newRegistrationFake(t)+ fake.mux.HandleFunc(registrationEndpoint, func(w http.ResponseWriter, r *http.Request) {+ writeJSON(w, map[string]any{"error": "rate_limited"})+ })+ c := NewRegistrationClient(RegistrationConfig{Domain: fake.URL()})+ res, err := c.Poll(context.Background(), fake.URL(), "dc_x")+ if err != nil {+ t.Fatalf("Poll: %v", err)+ }+ if res.Err == nil || res.Err.Code != "rate_limited" {+ t.Errorf("Err: %+v", res.Err)+ }+}++func TestRegistrationClient_Poll_MissingDeviceCode(t *testing.T) {+ c := NewRegistrationClient(RegistrationConfig{})+ if _, err := c.Poll(context.Background(), "", ""); err == nil {+ t.Fatal("want error on missing device_code")+ }+}++// errorsAs is a tiny wrapper over errors.As so the test source stays+// terse — call sites read `errorsAs(err, &re)`.+func errorsAs(err error, target any) bool { return errors.As(err, target) }diff --git a/server/internal/integrations/lark/types.go b/server/internal/integrations/lark/types.gonew file mode 100644index 0000000000..292f7c548a--- /dev/null+++ b/server/internal/integrations/lark/types.go@@ -0,0 +1,84 @@+package lark++import "time"++// OpenID is a Lark user's per-installation identifier. Different+// installations of the same app produce different open_ids for the+// same human user; cross-installation identity merging would need+// union_id (Phase 2). Typed alias instead of plain string so callers+// can't accidentally pass a Multica user UUID where a Lark open_id is+// expected.+type OpenID string++// ChatID identifies a Lark conversation (p2p or group). One ChatID maps+// to one Multica chat_session via lark_chat_session_binding.+type ChatID string++// ChatType discriminates p2p (single-user DM with the Bot) from group+// chats. The DB column constraints lark_chat_session_binding.lark_chat_type+// to the same two values.+type ChatType string++const (+ ChatTypeP2P ChatType = "p2p"+ ChatTypeGroup ChatType = "group"+)++// InstallationStatus mirrors the lark_installation.status check+// constraint. A revoked installation accepts no further events; its+// WebSocket is torn down and inbound events are dropped with an+// audit row.+type InstallationStatus string++const (+ InstallationActive InstallationStatus = "active"+ InstallationRevoked InstallationStatus = "revoked"+)++// DropReason enumerates the categories the inbound pipeline writes+// into lark_inbound_audit.drop_reason. The DB column is open TEXT so+// new reasons can be added without a migration; callers should reuse+// these constants to keep dashboards / queries consistent.+//+// All drop_reason values are recorded WITHOUT message body — see+// MUL-2671 §4.7 (drop-audit policy).+type DropReason string++const (+ // DropReasonUnboundUser — the sender's open_id has no row in+ // lark_user_binding for this installation. The Bot replies with the+ // binding card; the message itself is not stored.+ DropReasonUnboundUser DropReason = "unbound_user"++ // DropReasonNonWorkspaceMember — the sender resolved to a Multica+ // user, but that user is not a member of this installation's+ // workspace. The Bot replies with a "not in this workspace" notice;+ // the message itself is not stored.+ DropReasonNonWorkspaceMember DropReason = "non_workspace_member"++ // DropReasonNotAddressedInGroup — the message arrived in a group+ // chat but did not @ the Bot and was not a reply to a Bot card.+ // Group chats only ingest messages explicitly addressed to the Bot.+ DropReasonNotAddressedInGroup DropReason = "not_addressed_in_group"++ // DropReasonDuplicate — message_id already present in+ // lark_inbound_message_dedup. WebSocket reconnects can replay events;+ // this is the idempotency path.+ DropReasonDuplicate DropReason = "duplicate"++ // DropReasonRevokedInstallation — installation.status='revoked'.+ // The WS connection should already be closed; this catches any+ // in-flight events that landed during teardown.+ DropReasonRevokedInstallation DropReason = "revoked_installation"++ // DropReasonInvalidEvent — payload failed schema validation+ // (missing required fields, wrong event_type for this hook, etc.).+ DropReasonInvalidEvent DropReason = "invalid_event"+)++// BindingTokenTTL caps the lifetime of a member-binding token. The DB+// CHECK on lark_binding_token (`expires_at <= created_at + INTERVAL '15+// minutes'`) enforces the same bound at the storage layer, so a+// misconfigured caller or a hand-inserted SQL row cannot exceed it.+// Keep these two values in sync if the product value changes.+const BindingTokenTTL = 15 * time.Minutediff --git a/server/internal/integrations/lark/union_id_backfill.go b/server/internal/integrations/lark/union_id_backfill.gonew file mode 100644index 0000000000..00641a9b8b--- /dev/null+++ b/server/internal/integrations/lark/union_id_backfill.go@@ -0,0 +1,132 @@+package lark++import (+ "context"+ "log/slog"+ "time"++ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++// BackfillBotUnionIDs walks every active lark_installation row whose+// bot_union_id is NULL and calls APIClient.GetBotInfo to capture and+// persist it. This is the migration glue for installations created+// before migration 112 added the column — see MUL-2671 group @-mention+// triage. New installs already write bot_union_id during the device-+// flow finalize, so this is a one-shot bridge, not an ongoing job.+//+// Behavior:+//+// - The function is best-effort and per-installation idempotent:+// a transient HTTP / decrypt / DB error on one row does not block+// subsequent rows or interrupt server startup. Every outcome is+// logged with the installation id so an operator can audit+// coverage after a deploy.+//+// - Soft-fails on union_id absence (Lark returns code=0 with empty+// union_id when the app's contact scope is restricted): we log+// and move on; the decoder transitional open_id fallback keeps+// the install usable in single-bot deployments.+//+// - Callers should fire this from a separate goroutine at boot so+// a slow Lark round-trip cannot block HTTP listener startup. The+// backfill respects ctx cancellation between rows.+//+// Schedule: the router invokes this once per process at boot. There+// is no reason to repeat it on a sweep cadence — once bot_union_id+// is non-NULL, the decoder uses it directly, and a re-install path+// already overwrites both identifiers via UpsertLarkInstallation.+func BackfillBotUnionIDs(+ ctx context.Context,+ queries *db.Queries,+ api APIClient,+ creds CredentialsDecrypter,+ log *slog.Logger,+) {+ if log == nil {+ log = slog.Default()+ }+ if api == nil || !api.IsConfigured() {+ log.Info("lark backfill: APIClient not configured; skipping union_id backfill")+ return+ }+ rows, err := queries.ListActiveLarkInstallations(ctx)+ if err != nil {+ log.Warn("lark backfill: list installations failed", "err", err)+ return+ }+ var attempted, filled, missed, errored int+ for _, row := range rows {+ if ctx.Err() != nil {+ return+ }+ if row.BotUnionID.Valid && row.BotUnionID.String != "" {+ continue+ }+ attempted+++ secret, err := creds.DecryptAppSecret(row)+ if err != nil {+ log.Warn("lark backfill: decrypt app_secret failed",+ "installation_id", uuidString(row.ID),+ "app_id", row.AppID,+ "err", err)+ errored+++ continue+ }+ // Bound the Lark round-trip so a single hung install row+ // does not pin the backfill goroutine. 10s matches the+ // http client's defaultRequestTimeout.+ fetchCtx, cancel := context.WithTimeout(ctx, 10*time.Second)+ info, err := api.GetBotInfo(fetchCtx, InstallationCredentials{+ AppID: row.AppID,+ AppSecret: secret,+ TenantKey: row.TenantKey.String,+ })+ cancel()+ if err != nil {+ log.Warn("lark backfill: GetBotInfo failed",+ "installation_id", uuidString(row.ID),+ "app_id", row.AppID,+ "err", err)+ errored+++ continue+ }+ if info.UnionID == "" {+ log.Warn("lark backfill: union_id absent in Lark response; leaving NULL",+ "installation_id", uuidString(row.ID),+ "app_id", row.AppID,+ "bot_open_id", string(info.OpenID))+ missed+++ continue+ }+ if err := queries.SetLarkInstallationBotUnionID(ctx, db.SetLarkInstallationBotUnionIDParams{+ ID: row.ID,+ BotUnionID: textOrNull(info.UnionID),+ }); err != nil {+ log.Warn("lark backfill: persist union_id failed",+ "installation_id", uuidString(row.ID),+ "err", err)+ errored+++ continue+ }+ filled+++ log.Info("lark backfill: stamped union_id",+ "installation_id", uuidString(row.ID),+ "app_id", row.AppID,+ "bot_open_id", string(info.OpenID))+ }+ log.Info("lark backfill: union_id pass complete",+ "attempted", attempted,+ "filled", filled,+ "missed", missed,+ "errored", errored)+}++// CredentialsDecrypter is the narrow surface BackfillBotUnionIDs needs+// from InstallationService. Defined here (rather than imported as a+// concrete *InstallationService) so the backfill can be unit-tested+// with a stub that returns canned plaintext without spinning up the+// secretbox machinery.+type CredentialsDecrypter interface {+ DecryptAppSecret(inst db.LarkInstallation) (string, error)+}diff --git a/server/internal/integrations/lark/ws_chunk_assembler.go b/server/internal/integrations/lark/ws_chunk_assembler.gonew file mode 100644index 0000000000..f028826a56--- /dev/null+++ b/server/internal/integrations/lark/ws_chunk_assembler.go@@ -0,0 +1,170 @@+package lark++import (+ "strconv"+ "sync"+ "time"+)++// chunkAssembler buffers multi-frame Lark data payloads keyed by+// message_id and returns the concatenated bytes once every chunk has+// arrived. Lark splits large event payloads across multiple binary+// Frames with the headers:+//+// sum — total number of chunks (>=2 means multi-frame)+// seq — 0-based index of THIS chunk within the message+// message_id — common key across the N chunks+//+// The SDK reference (larksuite/oapi-sdk-go/v3/ws/client.go combine())+// uses a 5-second TTL on partial state — anything older than that is+// considered abandoned and dropped. Without TTL, a Lark-side packet+// drop on an intermediate chunk would leak the buffered bytes forever.+//+// The assembler is goroutine-safe: a single instance serves every+// supervisor goroutine. State lives in-process only — Frame chunks do+// not arrive across server restarts (Lark re-sends the full event on+// reconnect), so durability is not required.+type chunkAssembler struct {+ ttl time.Duration+ now func() time.Time++ mu sync.Mutex+ buf map[string]*chunkEntry+}++type chunkEntry struct {+ chunks [][]byte // indexed by seq; nil slots = still missing+ received int // count of non-empty slots+ deadline time.Time+}++// newChunkAssembler returns an assembler with the given partial-state+// TTL. A non-positive ttl falls back to the SDK default (5s).+func newChunkAssembler(ttl time.Duration, now func() time.Time) *chunkAssembler {+ if ttl <= 0 {+ ttl = 5 * time.Second+ }+ if now == nil {+ now = time.Now+ }+ return &chunkAssembler{+ ttl: ttl,+ now: now,+ buf: make(map[string]*chunkEntry),+ }+}++// admit records a single chunk and returns:+//+// - (payload, true) — every chunk has now arrived; payload is the+// concatenated bytes in seq order and the per-message entry has+// been removed.+// - (nil, false) — partial state; caller should NOT emit yet and+// SHOULD NOT ACK this frame (mirroring SDK behaviour where ACK only+// fires after full assembly so the server can retry the whole event).+//+// admit rejects malformed inputs (sum<=0, seq<0, seq>=sum, duplicate+// seq) by returning (nil, false) and treating the chunk as ignored.+// In production these conditions never fire because Lark enforces them+// server-side, but the function stays defensive — one malformed header+// must not corrupt the buffer for the next event.+func (a *chunkAssembler) admit(messageID string, sum, seq int, payload []byte) ([]byte, bool) {+ if messageID == "" || sum <= 0 || seq < 0 || seq >= sum {+ return nil, false+ }+ a.mu.Lock()+ defer a.mu.Unlock()++ // Lazy GC every admit: cheap (single map walk) and avoids needing a+ // separate sweeper goroutine. Bounded by the live message_id count,+ // which is small (Lark caps in-flight chunked events per connection).+ a.gcExpiredLocked()++ entry, ok := a.buf[messageID]+ if !ok {+ entry = &chunkEntry{+ chunks: make([][]byte, sum),+ deadline: a.now().Add(a.ttl),+ }+ a.buf[messageID] = entry+ }+ // Duplicate chunk (network retry / out-of-order Lark resend): we+ // silently overwrite. Lark guarantees the payload bytes are stable+ // for a given (message_id, seq), so re-admitting cannot change the+ // final assembled output.+ if entry.chunks[seq] == nil {+ entry.received+++ }+ entry.chunks[seq] = append([]byte(nil), payload...)+ // Sliding deadline: every fresh chunk extends the per-message TTL+ // because Lark might pace a multi-frame event across several+ // hundred ms; the static 5s is for "we got chunk 0 and then+ // nothing", not "chunks 0..N-1 arrived steadily over 4.9s".+ entry.deadline = a.now().Add(a.ttl)++ if entry.received < len(entry.chunks) {+ return nil, false+ }++ total := 0+ for _, c := range entry.chunks {+ total += len(c)+ }+ out := make([]byte, 0, total)+ for _, c := range entry.chunks {+ out = append(out, c...)+ }+ delete(a.buf, messageID)+ return out, true+}++// gcExpired removes entries whose deadline has passed. Exposed for+// tests; production path runs it lazily in admit.+func (a *chunkAssembler) gcExpired() int {+ a.mu.Lock()+ defer a.mu.Unlock()+ return a.gcExpiredLocked()+}++func (a *chunkAssembler) gcExpiredLocked() int {+ now := a.now()+ n := 0+ for id, e := range a.buf {+ if now.After(e.deadline) {+ delete(a.buf, id)+ n+++ }+ }+ return n+}++// pendingCount reports the number of partially-assembled messages+// currently buffered. Used by tests; useful for ops dashboards.+func (a *chunkAssembler) pendingCount() int {+ a.mu.Lock()+ defer a.mu.Unlock()+ return len(a.buf)+}++// parseChunkHeaders extracts the chunking metadata from a Frame's+// headers. Missing or unparseable headers yield (sum=0, seq=0, ""),+// which the connector reads as "single-frame event" and bypasses the+// assembler entirely. Lark's docs state sum is omitted (effectively 1)+// for non-chunked events; SDK's GetInt returns 0 on missing header.+func parseChunkHeaders(f *Frame) (sum, seq int, messageID string) {+ if f == nil {+ return 0, 0, ""+ }+ if s := f.HeaderValue(FrameHeaderSumKey); s != "" {+ if n, err := strconv.Atoi(s); err == nil {+ sum = n+ }+ }+ if s := f.HeaderValue(FrameHeaderSeqKey); s != "" {+ if n, err := strconv.Atoi(s); err == nil {+ seq = n+ }+ }+ messageID = f.HeaderValue(FrameHeaderMessageIDKey)+ return+}diff --git a/server/internal/integrations/lark/ws_chunk_assembler_test.go b/server/internal/integrations/lark/ws_chunk_assembler_test.gonew file mode 100644index 0000000000..ac5ab5e9f8--- /dev/null+++ b/server/internal/integrations/lark/ws_chunk_assembler_test.go@@ -0,0 +1,225 @@+package lark++import (+ "bytes"+ "testing"+ "time"+)++func TestChunkAssemblerSingleFramePassthrough(t *testing.T) {+ t.Parallel()+ // sum<=0 means non-chunked event; the connector should never call+ // admit for these, but we still verify the defensive path.+ a := newChunkAssembler(time.Second, nil)+ out, ok := a.admit("msg-1", 0, 0, []byte("not chunked"))+ if ok || out != nil {+ t.Fatalf("admit(sum=0) should return (nil,false); got (%v,%v)", out, ok)+ }+}++func TestChunkAssemblerReassemblesInOrder(t *testing.T) {+ t.Parallel()+ a := newChunkAssembler(time.Second, nil)+ if _, ok := a.admit("om-1", 3, 0, []byte("hello ")); ok {+ t.Fatal("seq=0/3: should be partial")+ }+ if _, ok := a.admit("om-1", 3, 1, []byte("brave ")); ok {+ t.Fatal("seq=1/3: should be partial")+ }+ out, ok := a.admit("om-1", 3, 2, []byte("world"))+ if !ok {+ t.Fatal("seq=2/3: should complete")+ }+ if !bytes.Equal(out, []byte("hello brave world")) {+ t.Errorf("assembled = %q; want %q", string(out), "hello brave world")+ }+ if a.pendingCount() != 0 {+ t.Errorf("pendingCount after complete = %d; want 0", a.pendingCount())+ }+}++func TestChunkAssemblerReassemblesOutOfOrder(t *testing.T) {+ t.Parallel()+ a := newChunkAssembler(time.Second, nil)+ if _, ok := a.admit("om-2", 3, 2, []byte("C")); ok {+ t.Fatal("seq=2/3: should be partial")+ }+ if _, ok := a.admit("om-2", 3, 0, []byte("A")); ok {+ t.Fatal("seq=0/3: should be partial")+ }+ out, ok := a.admit("om-2", 3, 1, []byte("B"))+ if !ok {+ t.Fatal("seq=1/3: should complete")+ }+ if !bytes.Equal(out, []byte("ABC")) {+ t.Errorf("assembled = %q; want ABC", string(out))+ }+}++func TestChunkAssemblerDuplicateSeqIsIdempotent(t *testing.T) {+ t.Parallel()+ a := newChunkAssembler(time.Second, nil)+ if _, ok := a.admit("om-3", 2, 0, []byte("X")); ok {+ t.Fatal("seq=0/2: should be partial")+ }+ // Duplicate seq 0 — must not advance received counter.+ if _, ok := a.admit("om-3", 2, 0, []byte("X")); ok {+ t.Fatal("duplicate seq=0: should still be partial")+ }+ out, ok := a.admit("om-3", 2, 1, []byte("Y"))+ if !ok {+ t.Fatal("seq=1/2: should complete")+ }+ if !bytes.Equal(out, []byte("XY")) {+ t.Errorf("assembled = %q; want XY", string(out))+ }+}++func TestChunkAssemblerMultipleConcurrentMessages(t *testing.T) {+ t.Parallel()+ a := newChunkAssembler(time.Second, nil)+ a.admit("om-A", 2, 0, []byte("a0"))+ a.admit("om-B", 2, 0, []byte("b0"))+ a.admit("om-A", 2, 1, []byte("a1"))+ outA, okA := a.admit("om-A", 2, 1, []byte("a1")) // duplicate complete: already gone+ // "om-A" was already completed and removed; admitting a chunk for a+ // removed entry should treat it as a new entry, which won't complete.+ if okA {+ t.Errorf("re-admit of completed message should not return complete; got %v", string(outA))+ }+ outB, okB := a.admit("om-B", 2, 1, []byte("b1"))+ if !okB || !bytes.Equal(outB, []byte("b0b1")) {+ t.Errorf("om-B assembled = %q ok=%v; want b0b1", string(outB), okB)+ }+}++func TestChunkAssemblerTTLExpiresPartial(t *testing.T) {+ t.Parallel()+ now := time.Now()+ clock := &fakeClock{now: now}+ a := newChunkAssembler(100*time.Millisecond, clock.Now)+ a.admit("om-stale", 2, 0, []byte("first"))+ if a.pendingCount() != 1 {+ t.Fatalf("pendingCount after first admit = %d; want 1", a.pendingCount())+ }++ // Advance past TTL.+ clock.Advance(200 * time.Millisecond)+ if n := a.gcExpired(); n != 1 {+ t.Errorf("gcExpired = %d; want 1", n)+ }+ if a.pendingCount() != 0 {+ t.Errorf("pendingCount after gc = %d; want 0", a.pendingCount())+ }++ // The follow-up chunk arrives after gc — treated as a brand-new+ // entry, must not auto-complete with stale data.+ out, ok := a.admit("om-stale", 2, 1, []byte("second"))+ if ok {+ t.Errorf("late chunk after TTL should not complete; got %q", string(out))+ }+}++func TestChunkAssemblerSlidingTTLAllowsSteadyProgress(t *testing.T) {+ t.Parallel()+ now := time.Now()+ clock := &fakeClock{now: now}+ a := newChunkAssembler(100*time.Millisecond, clock.Now)++ a.admit("om-slow", 3, 0, []byte("A"))+ clock.Advance(80 * time.Millisecond) // < TTL since last chunk+ a.admit("om-slow", 3, 1, []byte("B"))+ clock.Advance(80 * time.Millisecond) // still < TTL since last chunk+ out, ok := a.admit("om-slow", 3, 2, []byte("C"))+ if !ok || !bytes.Equal(out, []byte("ABC")) {+ t.Errorf("steady progress should complete; got ok=%v out=%q", ok, string(out))+ }+}++func TestChunkAssemblerLazyGCRunsOnAdmit(t *testing.T) {+ t.Parallel()+ now := time.Now()+ clock := &fakeClock{now: now}+ a := newChunkAssembler(50*time.Millisecond, clock.Now)++ // Stash a partial entry that will expire.+ a.admit("om-stale", 4, 0, []byte("x"))+ clock.Advance(200 * time.Millisecond)++ // Admit on an unrelated message — the lazy GC inside admit should+ // reap "om-stale" without us needing to call gcExpired manually.+ a.admit("om-fresh", 2, 0, []byte("a"))+ // Only "om-fresh" should remain.+ if got := a.pendingCount(); got != 1 {+ t.Errorf("pendingCount after lazy gc = %d; want 1", got)+ }+}++func TestChunkAssemblerRejectsBadInputs(t *testing.T) {+ t.Parallel()+ a := newChunkAssembler(time.Second, nil)+ cases := []struct {+ name string+ messageID string+ sum, seq int+ }{+ {"empty message_id", "", 2, 0},+ {"seq>=sum", "om-1", 2, 2},+ {"negative seq", "om-1", 2, -1},+ {"sum=-1", "om-1", -1, 0},+ }+ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ out, ok := a.admit(tc.messageID, tc.sum, tc.seq, []byte("x"))+ if ok || out != nil {+ t.Errorf("admit(%+v) should reject; got (%v,%v)", tc, out, ok)+ }+ })+ }+}++func TestParseChunkHeaders(t *testing.T) {+ t.Parallel()+ tests := []struct {+ name string+ headers []FrameHeader+ wantSum int+ wantSeq int+ wantMsgID string+ }{+ {+ name: "all present",+ headers: []FrameHeader{{Key: "sum", Value: "3"}, {Key: "seq", Value: "1"}, {Key: "message_id", Value: "om-7"}},+ wantSum: 3, wantSeq: 1, wantMsgID: "om-7",+ },+ {+ name: "missing sum/seq",+ headers: []FrameHeader{{Key: "message_id", Value: "om-8"}},+ wantSum: 0, wantSeq: 0, wantMsgID: "om-8",+ },+ {+ name: "unparseable sum",+ headers: []FrameHeader{{Key: "sum", Value: "abc"}, {Key: "seq", Value: "0"}, {Key: "message_id", Value: "om-9"}},+ wantSum: 0, wantSeq: 0, wantMsgID: "om-9",+ },+ {+ name: "nil frame",+ headers: nil,+ },+ }+ for _, tc := range tests {+ t.Run(tc.name, func(t *testing.T) {+ f := &Frame{Headers: tc.headers}+ if tc.name == "nil frame" {+ f = nil+ }+ gotSum, gotSeq, gotMsgID := parseChunkHeaders(f)+ if gotSum != tc.wantSum || gotSeq != tc.wantSeq || gotMsgID != tc.wantMsgID {+ t.Errorf("parseChunkHeaders = (%d,%d,%q); want (%d,%d,%q)",+ gotSum, gotSeq, gotMsgID, tc.wantSum, tc.wantSeq, tc.wantMsgID)+ }+ })+ }+}++// fakeClock is defined in http_client_test.go (same package).diff --git a/server/internal/integrations/lark/ws_connector.go b/server/internal/integrations/lark/ws_connector.gonew file mode 100644index 0000000000..8734f94cd2--- /dev/null+++ b/server/internal/integrations/lark/ws_connector.go@@ -0,0 +1,526 @@+package lark++import (+ "context"+ "errors"+ "fmt"+ "log/slog"+ "net/http"+ "sync"+ "time"++ "github.com/gorilla/websocket"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++// WSLongConnConnector is the production EventConnector that holds the+// Lark long-conn WebSocket open, decodes the binary Frame envelope+// the open-platform server pushes, and forwards normalized inbound+// events to the Hub's Dispatcher.+//+// Protocol layer (aligned with `larksuite/oapi-sdk-go/v3/ws`):+//+// 1. EndpointFetcher does the POST /callback/ws/endpoint bootstrap.+// Lark returns a single-use wss URL with `device_id` + `service_id`+// query parameters acting as the credential. The `service_id` is+// extracted and used as Frame.Service on every outbound frame.+// 2. Every WebSocket frame is a binary protobuf Frame. JSON envelopes+// are wrapped inside Frame.Payload for data events; control,+// ping, pong, ack frames are pure-binary.+// 3. The client emits an app-layer ping frame (NewPingFrame) on the+// PingInterval the server returned in the bootstrap ClientConfig.+// WebSocket protocol-level PING is NOT used — Lark's server+// ignores it. The server can also push pings at any time; we+// reply with NewPongFrame.+// 4. Every data frame requires an ACK back. The ACK reuses the+// inbound frame's Headers verbatim (Lark correlates by+// message_id) and writes a JSON Response{code:200, ...} as the+// Payload. We send ACK 200 on successful Dispatcher emit, 500+// when the Dispatcher reported an infra failure so Lark retries.+//+// Ownership of the §4.4 invariant (ctx cancel breaks blocking read):+//+// gorilla/websocket.ReadMessage blocks on the TCP socket and does NOT+// observe a context. Cancelling our ctx flips ctx.Done but does not+// touch the read syscall. We bridge ctx → read interrupt with a+// watchdog goroutine that calls conn.Close once ctx fires;+// gorilla.Close causes any in-flight Read to return immediately with+// a "use of closed connection" error. The watchdog also runs on a+// normal exit (so we never leak a goroutine) and is idempotent+// because conn.Close is safe to call multiple times. This invariant+// MUST be preserved by any future protocol change: without it,+// renewLeaseUntil's cancelRun is meaningless and two replicas can+// process the same installation during a healthy-but-silent socket.+//+// PersonalAgent compatibility risk: the official Feishu docs describe+// long-conn as "supports 企业自建应用 only". PersonalAgent device-flow+// apps are not listed as supported. If the bootstrap call returns a+// structured error from Lark, this connector exits Run with the error+// wrapped and the Hub's backoff loop logs it on every retry — making+// the misconfiguration visible. See MUL-2671 review thread for the+// smoke-test path.+type WSLongConnConnector struct {+ cfg WSConnectorConfig+}++// WSConnectorConfig wires the connector's dependencies. All injected+// interfaces are required; nil dependencies cause NewWSLongConnConnector+// to return an error rather than producing a connector that would panic+// at first use. Time / logger fields default at construction.+type WSConnectorConfig struct {+ // Dialer opens the WebSocket transport. Defaults to gorilla's+ // DefaultDialer with a bounded HandshakeTimeout. Tests inject a+ // fake that points at an httptest server.+ Dialer WSDialer++ // EndpointFetcher resolves the per-installation WS URL + server+ // config (ping interval, service id) via the bootstrap POST. The+ // connector calls it once per Run, so a transient failure here+ // causes a Hub-level backoff retry rather than an in-Run reconnect+ // storm.+ EndpointFetcher EndpointFetcher++ // FrameDecoder turns a single decoded Frame into either a+ // normalized InboundMessage (to be emitted upstream) or a+ // "control / heartbeat / unknown" signal that the connector+ // drops silently. Errors from the decoder do NOT exit the loop+ // — they log + drop — because one malformed Lark event payload+ // should not tear down the entire connection.+ FrameDecoder FrameDecoder++ // CredentialsProvider returns the InstallationCredentials the+ // EndpointFetcher needs. Typically wraps+ // InstallationService.DecryptAppSecret so the plaintext secret+ // never sits on the LarkInstallation row in memory.+ CredentialsProvider CredentialsProvider++ // PingInterval is the fallback cadence for the app-layer ping.+ // In production it is overridden per-installation by the+ // PingInterval Lark returns in the bootstrap ClientConfig.+ // Zero defaults to 2 minutes (matches the SDK default in+ // `larksuite/oapi-sdk-go/v3/ws/client.go`).+ PingInterval time.Duration++ // ReadDeadline bounds a single ReadMessage call. Re-armed before+ // each read; expiry yields a transient read error which the+ // connector logs and uses to exit, deferring to the Hub's+ // reconnect backoff. Zero defaults to 6 minutes so a healthy+ // connection with the 2-minute default ping never trips it.+ ReadDeadline time.Duration++ // WriteTimeout bounds a single WriteMessage. Zero defaults to 10s.+ WriteTimeout time.Duration++ // ChunkTTL bounds how long the chunk assembler holds a partial+ // multi-frame event before discarding the buffered chunks. Mirrors+ // the SDK's 5-second default — long enough to absorb pacing across+ // several chunks, short enough that an abandoned multi-frame event+ // does not leak memory. Zero defaults to 5 seconds.+ ChunkTTL time.Duration++ // Now is overridable for deterministic tests. Defaults to time.Now.+ Now func() time.Time++ // Logger optional; defaults to slog.Default.+ Logger *slog.Logger+}++func (c WSConnectorConfig) withDefaults() WSConnectorConfig {+ if c.PingInterval == 0 {+ c.PingInterval = 2 * time.Minute+ }+ if c.ReadDeadline == 0 {+ c.ReadDeadline = 6 * time.Minute+ }+ if c.WriteTimeout == 0 {+ c.WriteTimeout = 10 * time.Second+ }+ if c.ChunkTTL == 0 {+ c.ChunkTTL = 5 * time.Second+ }+ if c.Now == nil {+ c.Now = time.Now+ }+ if c.Logger == nil {+ c.Logger = slog.Default()+ }+ return c+}++// NewWSLongConnConnector validates the supplied config and returns a+// reusable connector.+func NewWSLongConnConnector(cfg WSConnectorConfig) (*WSLongConnConnector, error) {+ if cfg.Dialer == nil {+ return nil, errors.New("lark ws connector: Dialer is required")+ }+ if cfg.EndpointFetcher == nil {+ return nil, errors.New("lark ws connector: EndpointFetcher is required")+ }+ if cfg.FrameDecoder == nil {+ return nil, errors.New("lark ws connector: FrameDecoder is required")+ }+ if cfg.CredentialsProvider == nil {+ return nil, errors.New("lark ws connector: CredentialsProvider is required")+ }+ return &WSLongConnConnector{cfg: cfg.withDefaults()}, nil+}++// Run satisfies EventConnector. Opens one WebSocket session, reads+// binary Frame envelopes until either the ctx is cancelled or the+// connection errors, and returns. Nil return = clean exit; non-nil+// return = connection failed (Hub steps up backoff).+func (c *WSLongConnConnector) Run(ctx context.Context, inst db.LarkInstallation, emit EventEmitter) error {+ log := c.cfg.Logger.With(+ "installation_id", uuidString(inst.ID),+ "app_id", inst.AppID,+ )++ creds, err := c.cfg.CredentialsProvider.Credentials(ctx, inst)+ if err != nil {+ return fmt.Errorf("resolve credentials: %w", err)+ }++ endpoint, err := c.cfg.EndpointFetcher.Endpoint(ctx, creds)+ if err != nil {+ return fmt.Errorf("resolve ws endpoint: %w", err)+ }++ // Server-pushed PingInterval beats the static default; this is the+ // SDK behaviour. A zero (server omitted the field) falls back to+ // our static default so we never degenerate to "ping every 0s".+ pingInterval := endpoint.PingInterval+ if pingInterval <= 0 {+ pingInterval = c.cfg.PingInterval+ }++ conn, _, err := c.cfg.Dialer.DialContext(ctx, endpoint.URL, endpoint.Headers)+ if err != nil {+ return fmt.Errorf("dial ws: %w", err)+ }++ // runCtx fans out cancellation to the watchdog + ping goroutines+ // on EVERY Run exit, not just on outer-ctx cancel. A read error or+ // emit-infra failure would otherwise leave the ping goroutine+ // ticking on the outer ctx — and the deferred join would deadlock.+ runCtx, runCancel := context.WithCancel(ctx)++ var closeOnce sync.Once+ closeConn := func() {+ closeOnce.Do(func() {+ _ = conn.Close()+ })+ }++ // Watchdog: ctx fires → close the socket so blocking ReadMessage+ // returns immediately. Also runs on any other exit path so we+ // never leak the goroutine.+ done := make(chan struct{})+ go func() {+ select {+ case <-runCtx.Done():+ closeConn()+ case <-done:+ }+ }()++ // writeMu serializes WriteMessage from the read loop (ACK send)+ // and the ping goroutine. gorilla/websocket forbids concurrent+ // writers; without this, ack + ping interleaving would corrupt+ // the binary frame stream.+ var writeMu sync.Mutex++ // Per-Run chunk assembler. State does not need to outlive a single+ // long-conn session — Lark re-sends multi-frame events from chunk 0+ // after a reconnect — so the assembler is built here and dropped+ // when Run returns, which also releases any partial buffers held by+ // an abandoned event.+ assembler := newChunkAssembler(c.cfg.ChunkTTL, c.cfg.Now)++ // Ping loop: app-layer binary ping frames at the server's PingInterval.+ pingDone := make(chan struct{})+ go c.pingLoop(runCtx, conn, &writeMu, endpoint.ServiceID, pingInterval, log, pingDone)++ defer func() {+ runCancel()+ closeConn()+ close(done)+ <-pingDone+ }()++ log.Info("lark ws connector: connected",+ "service_id", endpoint.ServiceID,+ "ping_interval", pingInterval.String(),+ )++ for {+ // Re-arm the read deadline before every Read so a stalled+ // connection eventually unblocks the syscall.+ if err := conn.SetReadDeadline(c.cfg.Now().Add(c.cfg.ReadDeadline)); err != nil {+ if ctx.Err() != nil {+ return nil+ }+ return fmt.Errorf("set read deadline: %w", err)+ }++ msgType, raw, err := conn.ReadMessage()+ if err != nil {+ if ctx.Err() != nil {+ log.Info("lark ws connector: ctx cancelled, read returned",+ "close_err", err.Error(),+ )+ return nil+ }+ if websocket.IsCloseError(err, websocket.CloseNormalClosure, websocket.CloseGoingAway) {+ log.Info("lark ws connector: server closed connection", "err", err.Error())+ return nil+ }+ return fmt.Errorf("read message: %w", err)+ }+ // Lark only sends binary frames. A text frame is a Lark-side+ // schema regression — log + drop to be safe.+ if msgType != websocket.BinaryMessage {+ log.Warn("lark ws connector: dropped non-binary frame",+ "type", msgType,+ "len", len(raw),+ )+ continue+ }++ frame, err := UnmarshalFrame(raw)+ if err != nil {+ log.Warn("lark ws connector: frame protobuf decode failed",+ "err", err.Error(),+ "raw_len", len(raw),+ )+ continue+ }++ // Control frames carry ping / pong / config updates. We+ // only have to act on pings (reply with a pong); pongs and+ // config payloads are accepted silently.+ if frame.Method == FrameMethodControl {+ if frame.HeaderValue(FrameHeaderTypeKey) == FrameHeaderTypePing {+ if werr := c.writeFrame(&writeMu, conn, NewPongFrame(endpoint.ServiceID)); werr != nil {+ log.Warn("lark ws connector: pong write failed", "err", werr.Error())+ }+ }+ continue+ }++ // Multi-frame events: stash the chunk and skip ACK until the+ // full payload has arrived. This mirrors the SDK's combine()+ // behaviour — the SDK does NOT ACK partial chunks; Lark+ // reconciles delivery on its side using sum/seq, so ACKing+ // partials would tell Lark "we got it" before we actually+ // have the assembled payload.+ sum, seq, msgID := parseChunkHeaders(frame)+ payload := frame.Payload+ if sum > 1 {+ assembled, complete := assembler.admit(msgID, sum, seq, frame.Payload)+ if !complete {+ log.Debug("lark ws connector: partial chunk buffered",+ "message_id", msgID,+ "seq", seq,+ "sum", sum,+ "pending", assembler.pendingCount(),+ )+ continue+ }+ payload = assembled+ log.Debug("lark ws connector: chunk reassembly complete",+ "message_id", msgID,+ "chunks", sum,+ "bytes", len(payload),+ )+ }++ // Data frames: hand the (possibly reassembled) JSON payload to+ // the decoder, emit if it resolved to a message, and ACK back.+ msg, ok, derr := c.cfg.FrameDecoder.Decode(payload, inst)+ if derr != nil {+ log.Warn("lark ws connector: frame decode failed",+ "err", derr.Error(),+ "payload_len", len(frame.Payload),+ )+ // A decode failure still gets a 200 ACK: the message is+ // valid wire-wise, we just can't act on it. NACKing would+ // trigger a Lark-side retry storm of a payload we've+ // already proven we can't parse.+ if werr := c.writeFrame(&writeMu, conn, NewAckFrame(frame, true)); werr != nil {+ log.Warn("lark ws connector: ack-after-decode-error write failed", "err", werr.Error())+ return fmt.Errorf("write ack: %w", werr)+ }+ continue+ }+ if !ok {+ // Heartbeat / unhandled event type. ACK 200 so the server+ // stops sending it; the decoder owns the "what we handle"+ // policy.+ if werr := c.writeFrame(&writeMu, conn, NewAckFrame(frame, true)); werr != nil {+ log.Warn("lark ws connector: ack-after-drop write failed", "err", werr.Error())+ return fmt.Errorf("write ack: %w", werr)+ }+ continue+ }++ _, emitErr := emit(ctx, msg)+ if emitErr != nil {+ // Infra failure from Dispatcher (DB down, etc.). NACK so+ // Lark retries this event on a healthy replica; then+ // return so the Hub backs off and reconnects.+ if werr := c.writeFrame(&writeMu, conn, NewAckFrame(frame, false)); werr != nil {+ log.Warn("lark ws connector: nack write failed", "err", werr.Error())+ }+ log.Error("lark ws connector: emit infra error",+ "event_id", msg.EventID,+ "err", emitErr.Error(),+ )+ return fmt.Errorf("dispatch: %w", emitErr)+ }+ if werr := c.writeFrame(&writeMu, conn, NewAckFrame(frame, true)); werr != nil {+ log.Warn("lark ws connector: ack write failed", "err", werr.Error())+ return fmt.Errorf("write ack: %w", werr)+ }+ }+}++// writeFrame serializes a Frame and writes it as a binary WebSocket+// message under the connector's write mutex. Caller MUST NOT hold+// writeMu when calling.+func (c *WSLongConnConnector) writeFrame(mu *sync.Mutex, conn WSConn, f *Frame) error {+ payload := f.Marshal()+ mu.Lock()+ defer mu.Unlock()+ deadline := c.cfg.Now().Add(c.cfg.WriteTimeout)+ if err := conn.SetWriteDeadline(deadline); err != nil {+ return err+ }+ return conn.WriteMessage(websocket.BinaryMessage, payload)+}++// pingLoop sends a periodic app-layer ping frame on the cadence Lark+// asked for. The previous implementation used WebSocket protocol PING+// (WriteControl), which the SDK source confirms Lark ignores.+func (c *WSLongConnConnector) pingLoop(ctx context.Context, conn WSConn, writeMu *sync.Mutex, serviceID int32, interval time.Duration, log *slog.Logger, done chan<- struct{}) {+ defer close(done)+ if interval <= 0 {+ // A zero / negative interval would tick infinitely; bail out+ // quietly. We logged the chosen interval at connect time.+ <-ctx.Done()+ return+ }+ t := time.NewTicker(interval)+ defer t.Stop()+ for {+ select {+ case <-ctx.Done():+ return+ case <-t.C:+ if err := c.writeFrame(writeMu, conn, NewPingFrame(serviceID)); err != nil {+ log.Warn("lark ws connector: ping write failed", "err", err.Error())+ // Don't tear down here — the read loop will exit on+ // its own when the conn dies. Closing here would race+ // with the read loop's own cleanup.+ return+ }+ }+ }+}++// WSDialer is the dialer surface this connector consumes. *websocket.Dialer+// satisfies it directly (via DialContext); tests inject a fake.+type WSDialer interface {+ DialContext(ctx context.Context, urlStr string, requestHeader http.Header) (WSConn, *http.Response, error)+}++// WSConn is the subset of *websocket.Conn this connector uses.+type WSConn interface {+ ReadMessage() (messageType int, p []byte, err error)+ WriteMessage(messageType int, data []byte) error+ SetReadDeadline(t time.Time) error+ SetWriteDeadline(t time.Time) error+ Close() error+}++// EndpointFetcher resolves the per-installation bootstrap response.+// The implementation is responsible for the POST /callback/ws/endpoint+// call and surfacing the server-pushed ClientConfig.+type EndpointFetcher interface {+ Endpoint(ctx context.Context, creds InstallationCredentials) (WSEndpoint, error)+}++// WSEndpoint is the resolved transport target plus the server-pushed+// runtime configuration the connector needs to honor (ping cadence,+// reconnect hints). ServiceID is parsed out of the wss URL's+// `service_id` query parameter — it identifies which Lark backend+// service ID our outbound frames belong to.+type WSEndpoint struct {+ URL string+ Headers http.Header+ ServiceID int32+ PingInterval time.Duration+ ReconnectInterval time.Duration+ ReconnectNonce time.Duration+ ReconnectCount int+}++// FrameDecoder turns the JSON payload of a data Frame into either an+// InboundMessage (ok=true) or a no-op (ok=false). The connector+// treats a decoder error as per-frame: log + drop, do not tear down+// the connection. The decoder receives the JSON payload bytes — the+// outer binary Frame envelope is stripped by the connector.+type FrameDecoder interface {+ Decode(payload []byte, inst db.LarkInstallation) (msg InboundMessage, ok bool, err error)+}++// CredentialsProvider supplies the plaintext InstallationCredentials a+// connector needs for its EndpointFetcher call.+type CredentialsProvider interface {+ Credentials(ctx context.Context, inst db.LarkInstallation) (InstallationCredentials, error)+}++// CredentialsProviderFunc adapts a free function.+type CredentialsProviderFunc func(ctx context.Context, inst db.LarkInstallation) (InstallationCredentials, error)++func (f CredentialsProviderFunc) Credentials(ctx context.Context, inst db.LarkInstallation) (InstallationCredentials, error) {+ return f(ctx, inst)+}++// EndpointFetcherFunc adapts a plain function to EndpointFetcher.+type EndpointFetcherFunc func(ctx context.Context, creds InstallationCredentials) (WSEndpoint, error)++func (f EndpointFetcherFunc) Endpoint(ctx context.Context, creds InstallationCredentials) (WSEndpoint, error) {+ return f(ctx, creds)+}++// FrameDecoderFunc adapts a plain function to FrameDecoder.+type FrameDecoderFunc func(payload []byte, inst db.LarkInstallation) (InboundMessage, bool, error)++func (f FrameDecoderFunc) Decode(payload []byte, inst db.LarkInstallation) (InboundMessage, bool, error) {+ return f(payload, inst)+}++// GorillaDialer is the production WSDialer.+type GorillaDialer struct {+ Dialer *websocket.Dialer+}++func NewGorillaDialer() *GorillaDialer {+ return &GorillaDialer{+ Dialer: &websocket.Dialer{+ HandshakeTimeout: 15 * time.Second,+ },+ }+}++func (g *GorillaDialer) DialContext(ctx context.Context, urlStr string, requestHeader http.Header) (WSConn, *http.Response, error) {+ d := g.Dialer+ if d == nil {+ d = websocket.DefaultDialer+ }+ c, resp, err := d.DialContext(ctx, urlStr, requestHeader)+ if err != nil {+ return nil, resp, err+ }+ return c, resp, nil+}diff --git a/server/internal/integrations/lark/ws_connector_test.go b/server/internal/integrations/lark/ws_connector_test.gonew file mode 100644index 0000000000..c1e0b65d3f--- /dev/null+++ b/server/internal/integrations/lark/ws_connector_test.go@@ -0,0 +1,675 @@+package lark++import (+ "bytes"+ "context"+ "errors"+ "io"+ "log/slog"+ "net/http"+ "strconv"+ "sync"+ "sync/atomic"+ "testing"+ "time"++ "github.com/gorilla/websocket"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++// fakeWSConn is a programmable WSConn driven by tests. ReadMessage+// blocks until either Push delivers a frame or Close is invoked —+// this is how we simulate the "blocked in TCP read" condition the+// watchdog has to break.+//+// Frames sent via WriteMessage are buffered into writes[] so tests+// can assert on outbound traffic (ACK, ping) without race conditions.+type fakeWSConn struct {+ mu sync.Mutex+ writes [][]byte++ frames chan []byte+ closeOnce sync.Once+ closed chan struct{}+ writeErr error // optional injection for WriteMessage+}++func newFakeWSConn() *fakeWSConn {+ return &fakeWSConn{+ frames: make(chan []byte, 16),+ closed: make(chan struct{}),+ }+}++// Push enqueues a binary frame for the next ReadMessage call.+func (f *fakeWSConn) Push(b []byte) {+ select {+ case f.frames <- b:+ case <-f.closed:+ }+}++func (f *fakeWSConn) ReadMessage() (int, []byte, error) {+ select {+ case b, ok := <-f.frames:+ if !ok {+ return 0, nil, io.EOF+ }+ return websocket.BinaryMessage, b, nil+ case <-f.closed:+ return 0, nil, &websocket.CloseError{Code: websocket.CloseAbnormalClosure, Text: "fake closed"}+ }+}++func (f *fakeWSConn) WriteMessage(messageType int, data []byte) error {+ f.mu.Lock()+ defer f.mu.Unlock()+ if f.writeErr != nil {+ return f.writeErr+ }+ cp := make([]byte, len(data))+ copy(cp, data)+ f.writes = append(f.writes, cp)+ return nil+}++func (f *fakeWSConn) SetReadDeadline(t time.Time) error { return nil }+func (f *fakeWSConn) SetWriteDeadline(t time.Time) error { return nil }++func (f *fakeWSConn) Close() error {+ f.closeOnce.Do(func() {+ close(f.closed)+ })+ return nil+}++func (f *fakeWSConn) snapshot() [][]byte {+ f.mu.Lock()+ defer f.mu.Unlock()+ out := make([][]byte, len(f.writes))+ for i, w := range f.writes {+ out[i] = append([]byte(nil), w...)+ }+ return out+}++// fakeWSDialer hands back a pre-built fakeWSConn so tests can drive+// frames + observe closes deterministically.+type fakeWSDialer struct {+ conn *fakeWSConn+ dialErr error+}++func (d *fakeWSDialer) DialContext(ctx context.Context, urlStr string, h http.Header) (WSConn, *http.Response, error) {+ if d.dialErr != nil {+ return nil, nil, d.dialErr+ }+ return d.conn, nil, nil+}++// quietConnector wires a connector with a deterministic decoder + the+// fakeWSConn. Caller controls the decoder so each test can assert+// per-payload behaviour.+func quietConnector(t *testing.T, conn *fakeWSConn, decoder FrameDecoder, pingInterval time.Duration) *WSLongConnConnector {+ t.Helper()+ c, err := NewWSLongConnConnector(WSConnectorConfig{+ Dialer: &fakeWSDialer{conn: conn},+ EndpointFetcher: EndpointFetcherFunc(func(context.Context, InstallationCredentials) (WSEndpoint, error) {+ return WSEndpoint{URL: "wss://test/ignored", ServiceID: 7, PingInterval: pingInterval}, nil+ }),+ FrameDecoder: decoder,+ CredentialsProvider: CredentialsProviderFunc(func(context.Context, db.LarkInstallation) (InstallationCredentials, error) {+ return InstallationCredentials{AppID: "test_app", AppSecret: "secret"}, nil+ }),+ PingInterval: pingInterval,+ ReadDeadline: time.Second,+ WriteTimeout: time.Second,+ Logger: slog.New(slog.NewTextHandler(io.Discard, nil)),+ })+ if err != nil {+ t.Fatalf("NewWSLongConnConnector: %v", err)+ }+ return c+}++// pushDataFrame writes a Lark long-conn data Frame envelope wrapping+// the supplied JSON payload onto the conn's read queue.+func pushDataFrame(conn *fakeWSConn, payload []byte, messageID string) {+ f := &Frame{+ Method: FrameMethodData,+ Service: 7,+ Headers: []FrameHeader{+ {Key: FrameHeaderTypeKey, Value: FrameHeaderTypeEvent},+ {Key: FrameHeaderMessageIDKey, Value: messageID},+ },+ Payload: payload,+ }+ conn.Push(f.Marshal())+}++func TestWSConnectorRunReturnsOnCtxCancelEvenWhenReadIsBlocked(t *testing.T) {+ t.Parallel()+ conn := newFakeWSConn()+ decoder := FrameDecoderFunc(func([]byte, db.LarkInstallation) (InboundMessage, bool, error) {+ return InboundMessage{}, false, nil+ })+ c := quietConnector(t, conn, decoder, 10*time.Millisecond)++ ctx, cancel := context.WithCancel(context.Background())+ done := make(chan error, 1)+ go func() {+ done <- c.Run(ctx, db.LarkInstallation{AppID: "test_app"}, func(context.Context, InboundMessage) (DispatchResult, error) {+ t.Errorf("emit unexpectedly called")+ return DispatchResult{}, nil+ })+ }()++ // Give the connector a moment to dial + park in ReadMessage.+ time.Sleep(20 * time.Millisecond)++ cancel()++ select {+ case err := <-done:+ if err != nil {+ t.Fatalf("Run returned error on ctx cancel: %v", err)+ }+ case <-time.After(2 * time.Second):+ t.Fatal("Run did not return within 2s of ctx cancel — watchdog broken")+ }+}++// TestWSConnectorEmitsDecodedFramesAndAcks verifies that:+// - data frames whose decoder returns ok=true reach emit;+// - every data frame yields an ACK Frame written back to the conn;+// - heartbeat / non-event payloads are dropped but still ACKed (so+// the server stops resending them).+func TestWSConnectorEmitsDecodedFramesAndAcks(t *testing.T) {+ t.Parallel()+ conn := newFakeWSConn()+ decoder := FrameDecoderFunc(func(payload []byte, _ db.LarkInstallation) (InboundMessage, bool, error) {+ if string(payload) == "heartbeat" {+ return InboundMessage{}, false, nil+ }+ return InboundMessage{+ EventID: string(payload),+ AppID: "test_app",+ MessageID: "msg-" + string(payload),+ }, true, nil+ })+ c := quietConnector(t, conn, decoder, time.Hour) // disable ping cadence++ var emitted []InboundMessage+ var emitMu sync.Mutex+ emit := func(_ context.Context, msg InboundMessage) (DispatchResult, error) {+ emitMu.Lock()+ emitted = append(emitted, msg)+ emitMu.Unlock()+ return DispatchResult{Outcome: OutcomeIngested}, nil+ }++ ctx, cancel := context.WithCancel(context.Background())+ defer cancel()++ done := make(chan error, 1)+ go func() {+ done <- c.Run(ctx, db.LarkInstallation{AppID: "test_app"}, emit)+ }()++ pushDataFrame(conn, []byte("evt-1"), "m1")+ pushDataFrame(conn, []byte("heartbeat"), "m2")+ pushDataFrame(conn, []byte("evt-2"), "m3")++ deadline := time.After(2 * time.Second)+ for {+ emitMu.Lock()+ n := len(emitted)+ emitMu.Unlock()+ if n >= 2 {+ break+ }+ select {+ case <-deadline:+ t.Fatalf("only %d emits in 2s", n)+ case <-time.After(5 * time.Millisecond):+ }+ }++ cancel()+ select {+ case <-done:+ case <-time.After(2 * time.Second):+ t.Fatal("Run did not return after cancel")+ }++ if emitted[0].EventID != "evt-1" || emitted[1].EventID != "evt-2" {+ t.Errorf("emit ordering wrong: %+v", emitted)+ }++ // Every data frame should have produced an ACK frame on the wire+ // regardless of decode outcome (drop or emit).+ writes := conn.snapshot()+ if len(writes) < 3 {+ t.Fatalf("expected >=3 outbound ACK frames, got %d", len(writes))+ }+ for i, w := range writes[:3] {+ f, err := UnmarshalFrame(w)+ if err != nil {+ t.Fatalf("write[%d] unmarshal: %v", i, err)+ }+ if f.Method != FrameMethodData {+ t.Errorf("ack[%d] Method = %d; want Data", i, f.Method)+ }+ if f.HeaderValue(FrameHeaderTypeKey) != FrameHeaderTypeEvent {+ t.Errorf("ack[%d] type header = %q", i, f.HeaderValue(FrameHeaderTypeKey))+ }+ if len(f.Payload) == 0 || !contains(string(f.Payload), `"code":200`) {+ t.Errorf("ack[%d] payload missing code=200: %s", i, string(f.Payload))+ }+ }+}++func TestWSConnectorRespondsToServerPingWithPong(t *testing.T) {+ t.Parallel()+ conn := newFakeWSConn()+ decoder := FrameDecoderFunc(func([]byte, db.LarkInstallation) (InboundMessage, bool, error) {+ return InboundMessage{}, false, nil+ })+ c := quietConnector(t, conn, decoder, time.Hour)++ ctx, cancel := context.WithCancel(context.Background())+ defer cancel()++ done := make(chan error, 1)+ go func() {+ done <- c.Run(ctx, db.LarkInstallation{AppID: "test_app"}, func(context.Context, InboundMessage) (DispatchResult, error) {+ return DispatchResult{}, nil+ })+ }()++ // Server-initiated ping (control frame, type=ping).+ pingFrame := &Frame{+ Method: FrameMethodControl,+ Service: 7,+ Headers: []FrameHeader{{Key: FrameHeaderTypeKey, Value: FrameHeaderTypePing}},+ }+ conn.Push(pingFrame.Marshal())++ // Allow the read loop to react.+ deadline := time.After(2 * time.Second)+ for {+ writes := conn.snapshot()+ if len(writes) >= 1 {+ f, err := UnmarshalFrame(writes[0])+ if err != nil {+ t.Fatalf("pong unmarshal: %v", err)+ }+ if f.HeaderValue(FrameHeaderTypeKey) != FrameHeaderTypePong {+ t.Errorf("response type = %q; want pong", f.HeaderValue(FrameHeaderTypeKey))+ }+ if f.Service != 7 {+ t.Errorf("response Service = %d; want 7", f.Service)+ }+ break+ }+ select {+ case <-deadline:+ t.Fatal("connector did not pong in 2s")+ case <-time.After(5 * time.Millisecond):+ }+ }++ cancel()+ <-done+}++func TestWSConnectorEmitInfraErrorSendsNackAndReturns(t *testing.T) {+ t.Parallel()+ conn := newFakeWSConn()+ decoder := FrameDecoderFunc(func([]byte, db.LarkInstallation) (InboundMessage, bool, error) {+ return InboundMessage{EventID: "x"}, true, nil+ })+ c := quietConnector(t, conn, decoder, time.Hour)++ infra := errors.New("dispatcher infra failure")+ ctx, cancel := context.WithCancel(context.Background())+ defer cancel()++ done := make(chan error, 1)+ go func() {+ done <- c.Run(ctx, db.LarkInstallation{AppID: "test_app"}, func(context.Context, InboundMessage) (DispatchResult, error) {+ return DispatchResult{}, infra+ })+ }()++ pushDataFrame(conn, []byte("triggers-infra"), "m-infra")++ select {+ case err := <-done:+ if err == nil || !errors.Is(err, infra) {+ t.Fatalf("expected Run to wrap infra error, got %v", err)+ }+ case <-time.After(2 * time.Second):+ t.Fatal("Run did not return after infra error")+ }++ // NACK should have been written on the way out (code=500).+ writes := conn.snapshot()+ found := false+ for _, w := range writes {+ f, err := UnmarshalFrame(w)+ if err != nil {+ continue+ }+ if f.Method == FrameMethodData && contains(string(f.Payload), `"code":500`) {+ found = true+ break+ }+ }+ if !found {+ t.Errorf("expected NACK (code=500) frame written on infra error path")+ }+}++func TestWSConnectorSendsAppLayerPings(t *testing.T) {+ t.Parallel()+ conn := newFakeWSConn()+ decoder := FrameDecoderFunc(func([]byte, db.LarkInstallation) (InboundMessage, bool, error) {+ return InboundMessage{}, false, nil+ })+ c := quietConnector(t, conn, decoder, 10*time.Millisecond)++ ctx, cancel := context.WithCancel(context.Background())+ defer cancel()++ done := make(chan error, 1)+ go func() {+ done <- c.Run(ctx, db.LarkInstallation{AppID: "test_app"}, func(context.Context, InboundMessage) (DispatchResult, error) {+ return DispatchResult{}, nil+ })+ }()++ deadline := time.After(500 * time.Millisecond)+ for {+ writes := conn.snapshot()+ pings := 0+ for _, w := range writes {+ f, err := UnmarshalFrame(w)+ if err != nil {+ continue+ }+ if f.Method == FrameMethodControl && f.HeaderValue(FrameHeaderTypeKey) == FrameHeaderTypePing {+ pings+++ }+ }+ if pings >= 3 {+ break+ }+ select {+ case <-deadline:+ t.Fatalf("expected >=3 app-layer pings, got %d writes total", len(writes))+ case <-time.After(5 * time.Millisecond):+ }+ }++ cancel()+ <-done+}++func TestWSConnectorDecoderErrorAcksAndContinues(t *testing.T) {+ t.Parallel()+ conn := newFakeWSConn()+ decodeCount := int32(0)+ decoder := FrameDecoderFunc(func(payload []byte, _ db.LarkInstallation) (InboundMessage, bool, error) {+ n := atomic.AddInt32(&decodeCount, 1)+ if n == 1 {+ return InboundMessage{}, false, errors.New("synthetic decode failure")+ }+ return InboundMessage{EventID: "good"}, true, nil+ })+ c := quietConnector(t, conn, decoder, time.Hour)++ emits := make(chan InboundMessage, 1)+ emit := func(_ context.Context, msg InboundMessage) (DispatchResult, error) {+ emits <- msg+ return DispatchResult{}, nil+ }++ ctx, cancel := context.WithCancel(context.Background())+ defer cancel()+ done := make(chan error, 1)+ go func() {+ done <- c.Run(ctx, db.LarkInstallation{AppID: "test_app"}, emit)+ }()++ pushDataFrame(conn, []byte("bad"), "mb")+ pushDataFrame(conn, []byte("good"), "mg")++ select {+ case msg := <-emits:+ if msg.EventID != "good" {+ t.Errorf("emit EventID = %q, want good", msg.EventID)+ }+ case <-time.After(2 * time.Second):+ t.Fatal("connector exited after first decode error instead of dropping the frame")+ }++ cancel()+ <-done+}++func TestWSConnectorReadErrorReturnsToHub(t *testing.T) {+ t.Parallel()+ conn := newFakeWSConn()+ decoder := FrameDecoderFunc(func([]byte, db.LarkInstallation) (InboundMessage, bool, error) {+ return InboundMessage{}, false, nil+ })+ c := quietConnector(t, conn, decoder, time.Hour)++ ctx := context.Background()+ done := make(chan error, 1)+ go func() {+ done <- c.Run(ctx, db.LarkInstallation{AppID: "test_app"}, func(context.Context, InboundMessage) (DispatchResult, error) {+ return DispatchResult{}, nil+ })+ }()++ // Close out from under the read loop. Because ctx is NOT cancelled,+ // the connector should treat this as a connection failure and+ // return the wrapped error so the Hub steps up its backoff.+ _ = conn.Close()++ select {+ case err := <-done:+ if err == nil {+ t.Fatal("Run returned nil on read error; expected wrapped err for Hub backoff")+ }+ case <-time.After(2 * time.Second):+ t.Fatal("Run did not return after underlying conn closed")+ }+}++func TestWSConnectorRequiresAllDeps(t *testing.T) {+ t.Parallel()+ cases := []struct {+ name string+ cfg WSConnectorConfig+ }{+ {"no dialer", WSConnectorConfig{+ EndpointFetcher: EndpointFetcherFunc(func(context.Context, InstallationCredentials) (WSEndpoint, error) { return WSEndpoint{}, nil }),+ FrameDecoder: FrameDecoderFunc(func([]byte, db.LarkInstallation) (InboundMessage, bool, error) { return InboundMessage{}, false, nil }),+ CredentialsProvider: CredentialsProviderFunc(func(context.Context, db.LarkInstallation) (InstallationCredentials, error) { return InstallationCredentials{}, nil }),+ }},+ {"no endpoint fetcher", WSConnectorConfig{+ Dialer: &fakeWSDialer{},+ FrameDecoder: FrameDecoderFunc(func([]byte, db.LarkInstallation) (InboundMessage, bool, error) { return InboundMessage{}, false, nil }),+ CredentialsProvider: CredentialsProviderFunc(func(context.Context, db.LarkInstallation) (InstallationCredentials, error) { return InstallationCredentials{}, nil }),+ }},+ {"no decoder", WSConnectorConfig{+ Dialer: &fakeWSDialer{},+ EndpointFetcher: EndpointFetcherFunc(func(context.Context, InstallationCredentials) (WSEndpoint, error) { return WSEndpoint{}, nil }),+ CredentialsProvider: CredentialsProviderFunc(func(context.Context, db.LarkInstallation) (InstallationCredentials, error) { return InstallationCredentials{}, nil }),+ }},+ {"no credentials provider", WSConnectorConfig{+ Dialer: &fakeWSDialer{},+ EndpointFetcher: EndpointFetcherFunc(func(context.Context, InstallationCredentials) (WSEndpoint, error) { return WSEndpoint{}, nil }),+ FrameDecoder: FrameDecoderFunc(func([]byte, db.LarkInstallation) (InboundMessage, bool, error) { return InboundMessage{}, false, nil }),+ }},+ }+ for _, tc := range cases {+ tc := tc+ t.Run(tc.name, func(t *testing.T) {+ t.Parallel()+ if _, err := NewWSLongConnConnector(tc.cfg); err == nil {+ t.Fatalf("expected error for missing dep")+ }+ })+ }+}++func TestWSConnectorDialErrorIsReturned(t *testing.T) {+ t.Parallel()+ dialErr := errors.New("dial blew up")+ c, err := NewWSLongConnConnector(WSConnectorConfig{+ Dialer: &fakeWSDialer{dialErr: dialErr},+ EndpointFetcher: EndpointFetcherFunc(func(context.Context, InstallationCredentials) (WSEndpoint, error) { return WSEndpoint{URL: "wss://x", ServiceID: 1}, nil }),+ FrameDecoder: FrameDecoderFunc(func([]byte, db.LarkInstallation) (InboundMessage, bool, error) { return InboundMessage{}, false, nil }),+ CredentialsProvider: CredentialsProviderFunc(func(context.Context, db.LarkInstallation) (InstallationCredentials, error) {+ return InstallationCredentials{AppID: "a"}, nil+ }),+ Logger: slog.New(slog.NewTextHandler(io.Discard, nil)),+ })+ if err != nil {+ t.Fatalf("constructor: %v", err)+ }+ err = c.Run(context.Background(), db.LarkInstallation{}, func(context.Context, InboundMessage) (DispatchResult, error) {+ return DispatchResult{}, nil+ })+ if err == nil || !errors.Is(err, dialErr) {+ t.Fatalf("expected wrapped dial error, got %v", err)+ }+}++// pushChunkedDataFrame pushes a Lark long-conn data Frame carrying one+// chunk of a multi-frame event. Lark splits big events across N frames+// with sum/seq/message_id headers; the connector reassembles before+// invoking the decoder.+func pushChunkedDataFrame(conn *fakeWSConn, payload []byte, messageID string, sum, seq int) {+ f := &Frame{+ Method: FrameMethodData,+ Service: 7,+ Headers: []FrameHeader{+ {Key: FrameHeaderTypeKey, Value: FrameHeaderTypeEvent},+ {Key: FrameHeaderMessageIDKey, Value: messageID},+ {Key: FrameHeaderSumKey, Value: strconv.Itoa(sum)},+ {Key: FrameHeaderSeqKey, Value: strconv.Itoa(seq)},+ },+ Payload: payload,+ }+ conn.Push(f.Marshal())+}++// TestWSConnectorReassemblesChunkedDataFrame verifies that:+// - intermediate chunks (sum>1, seq<sum-1) are NOT ACKed and NOT+// emitted — the SDK's combine() contract;+// - the final chunk completes the buffer, the decoder receives the+// concatenated payload, and ONE ACK is written for the whole event.+//+// This is the regression test for the prior MVP behaviour where every+// data frame was decoded individually and chunked events were silently+// truncated then ACKed (server would never retry).+func TestWSConnectorReassemblesChunkedDataFrame(t *testing.T) {+ t.Parallel()+ conn := newFakeWSConn()+ var decodedPayloads [][]byte+ var decodeMu sync.Mutex+ decoder := FrameDecoderFunc(func(payload []byte, _ db.LarkInstallation) (InboundMessage, bool, error) {+ decodeMu.Lock()+ decodedPayloads = append(decodedPayloads, append([]byte(nil), payload...))+ decodeMu.Unlock()+ return InboundMessage{EventID: string(payload)}, true, nil+ })+ c := quietConnector(t, conn, decoder, time.Hour) // disable ping cadence++ emits := make(chan InboundMessage, 4)+ emit := func(_ context.Context, msg InboundMessage) (DispatchResult, error) {+ emits <- msg+ return DispatchResult{Outcome: OutcomeIngested}, nil+ }++ ctx, cancel := context.WithCancel(context.Background())+ defer cancel()+ done := make(chan error, 1)+ go func() {+ done <- c.Run(ctx, db.LarkInstallation{AppID: "test_app"}, emit)+ }()++ // Three chunks of a single logical event "ABC".+ pushChunkedDataFrame(conn, []byte("A"), "om-multi", 3, 0)+ pushChunkedDataFrame(conn, []byte("B"), "om-multi", 3, 1)+ pushChunkedDataFrame(conn, []byte("C"), "om-multi", 3, 2)++ select {+ case msg := <-emits:+ if msg.EventID != "ABC" {+ t.Errorf("emit EventID = %q; want ABC", msg.EventID)+ }+ case <-time.After(2 * time.Second):+ t.Fatal("reassembled event did not reach emit in 2s")+ }++ // Drain the read loop briefly to let any pending ACK write land.+ time.Sleep(50 * time.Millisecond)++ // Exactly one ACK should have been written — only the final chunk+ // triggers ACK; intermediate chunks are silently buffered.+ cancel()+ <-done++ writes := conn.snapshot()+ dataAcks := 0+ for _, w := range writes {+ f, err := UnmarshalFrame(w)+ if err != nil {+ continue+ }+ if f.Method == FrameMethodData && bytes.Contains(f.Payload, []byte(`"code":200`)) {+ dataAcks+++ }+ }+ if dataAcks != 1 {+ t.Errorf("data-frame ACK count = %d; want exactly 1 (only the final chunk should ACK)", dataAcks)+ }++ decodeMu.Lock()+ defer decodeMu.Unlock()+ if len(decodedPayloads) != 1 {+ t.Fatalf("decoder invoked %d times; want exactly 1 (reassembled payload)", len(decodedPayloads))+ }+ if string(decodedPayloads[0]) != "ABC" {+ t.Errorf("decoder saw payload = %q; want ABC", string(decodedPayloads[0]))+ }+}++func TestWSConnectorCredentialsErrorIsReturned(t *testing.T) {+ t.Parallel()+ credsErr := errors.New("decrypt failed")+ c, err := NewWSLongConnConnector(WSConnectorConfig{+ Dialer: &fakeWSDialer{conn: newFakeWSConn()},+ EndpointFetcher: EndpointFetcherFunc(func(context.Context, InstallationCredentials) (WSEndpoint, error) { return WSEndpoint{URL: "wss://x"}, nil }),+ FrameDecoder: FrameDecoderFunc(func([]byte, db.LarkInstallation) (InboundMessage, bool, error) { return InboundMessage{}, false, nil }),+ CredentialsProvider: CredentialsProviderFunc(func(context.Context, db.LarkInstallation) (InstallationCredentials, error) {+ return InstallationCredentials{}, credsErr+ }),+ Logger: slog.New(slog.NewTextHandler(io.Discard, nil)),+ })+ if err != nil {+ t.Fatalf("constructor: %v", err)+ }+ err = c.Run(context.Background(), db.LarkInstallation{}, func(context.Context, InboundMessage) (DispatchResult, error) {+ return DispatchResult{}, nil+ })+ if err == nil || !errors.Is(err, credsErr) {+ t.Fatalf("expected wrapped credentials error, got %v", err)+ }+}diff --git a/server/internal/integrations/lark/ws_endpoint.go b/server/internal/integrations/lark/ws_endpoint.gonew file mode 100644index 0000000000..1667300171--- /dev/null+++ b/server/internal/integrations/lark/ws_endpoint.go@@ -0,0 +1,189 @@+package lark++import (+ "bytes"+ "context"+ "encoding/json"+ "errors"+ "fmt"+ "io"+ "log/slog"+ "net/http"+ "net/url"+ "strings"+ "strconv"+ "time"+)++// defaultLarkCallbackBaseURL is the bootstrap host for the long-conn+// `/callback/ws/endpoint` request. Note this is `open.feishu.cn`+// (mainland) regardless of where the WS itself ends up — Lark returns+// the wss URL in the response body. Operators on the international+// tenant override via MULTICA_LARK_CALLBACK_BASE_URL to+// `https://open.larksuite.com`.+const defaultLarkCallbackBaseURL = "https://open.feishu.cn"++// HTTPConnectionTokenFetcher is the production EndpointFetcher. It+// exchanges per-installation app credentials for a short-lived+// WebSocket URL + ClientConfig by calling+// `POST /callback/ws/endpoint` on Lark's open-platform host — the+// same bootstrap path the official `larksuite/oapi-sdk-go/v3/ws`+// client uses. The request body carries `{AppID, AppSecret}` plain+// (no tenant_access_token bearer); the response carries the wss URL+// (single-use, embedded device_id/service_id auth) and a ClientConfig+// with PingInterval / ReconnectInterval / ReconnectNonce /+// ReconnectCount in seconds.+//+// We do NOT cache the response. The wss URL is single-use by design+// (the embedded `device_id` is rotated on every bootstrap call), so+// re-using it on a reconnect would yield an auth rejection that looks+// like a Lark outage. The connector calls Endpoint() once per Run.+//+// PersonalAgent compatibility — OPEN RISK (MUL-2671 review thread):+// the official Feishu docs describe long-conn mode as "supports+// 企业自建应用 only". The PersonalAgent device-flow archetype is not+// listed as supported; live confirmation is pending. If the bootstrap+// call returns a structured "app type not supported" error, this code+// surfaces the code+msg directly so the Hub's backoff loop logs the+// real reason instead of looping silently. The smoke test path is+// `multica` -> register a PersonalAgent -> enable WS -> watch logs.+type HTTPConnectionTokenFetcher struct {+ cfg HTTPConnectionTokenConfig+}++// HTTPConnectionTokenConfig wires the fetcher's dependencies. BaseURL+// defaults to defaultLarkCallbackBaseURL; tests substitute an+// httptest.Server URL.+type HTTPConnectionTokenConfig struct {+ BaseURL string+ HTTPClient *http.Client+ Now func() time.Time+ Logger *slog.Logger+}++func (c HTTPConnectionTokenConfig) withDefaults() HTTPConnectionTokenConfig {+ if c.BaseURL == "" {+ c.BaseURL = defaultLarkCallbackBaseURL+ }+ c.BaseURL = strings.TrimRight(c.BaseURL, "/")+ if c.HTTPClient == nil {+ c.HTTPClient = &http.Client{Timeout: defaultRequestTimeout}+ }+ if c.Now == nil {+ c.Now = time.Now+ }+ if c.Logger == nil {+ c.Logger = slog.Default()+ }+ return c+}++// NewHTTPConnectionTokenFetcher returns the production EndpointFetcher+// bound to the supplied configuration.+func NewHTTPConnectionTokenFetcher(cfg HTTPConnectionTokenConfig) (*HTTPConnectionTokenFetcher, error) {+ return &HTTPConnectionTokenFetcher{cfg: cfg.withDefaults()}, nil+}++// bootstrapRequest mirrors the SDK's BootstrapRequest. Field names use+// PascalCase exactly because the server-side JSON tags are PascalCase+// (`AppID`, not `app_id`); the SDK's pbbp2 schema dictates the format+// and lower-snake_case would not match.+type bootstrapRequest struct {+ AppID string `json:"AppID"`+ AppSecret string `json:"AppSecret"`+}++// endpointResponse mirrors the SDK's EndpointResp + Endpoint ++// ClientConfig. Field naming is PascalCase to match Lark's wire shape.+type endpointResponse struct {+ Code int `json:"code"`+ Msg string `json:"msg"`+ Data struct {+ URL string `json:"URL"`+ ClientConfig struct {+ ReconnectCount int `json:"ReconnectCount"`+ ReconnectInterval int `json:"ReconnectInterval"`+ ReconnectNonce int `json:"ReconnectNonce"`+ PingInterval int `json:"PingInterval"`+ } `json:"ClientConfig"`+ } `json:"data"`+}++// Endpoint implements EndpointFetcher.+func (f *HTTPConnectionTokenFetcher) Endpoint(ctx context.Context, creds InstallationCredentials) (WSEndpoint, error) {+ if creds.AppID == "" || creds.AppSecret == "" {+ return WSEndpoint{}, errors.New("lark ws endpoint: missing app_id / app_secret")+ }+ body := bootstrapRequest{AppID: creds.AppID, AppSecret: creds.AppSecret}+ raw, err := json.Marshal(body)+ if err != nil {+ return WSEndpoint{}, fmt.Errorf("marshal body: %w", err)+ }+ req, err := http.NewRequestWithContext(ctx, http.MethodPost, f.cfg.BaseURL+"/callback/ws/endpoint", bytes.NewReader(raw))+ if err != nil {+ return WSEndpoint{}, fmt.Errorf("new request: %w", err)+ }+ req.Header.Set("Content-Type", "application/json; charset=utf-8")+ // Locale header is sent verbatim by the SDK — Lark uses it for the+ // error `msg` field (Chinese vs English). We pick zh because that's+ // the audience Multica server logs are read by today; if i18n+ // matters later this becomes an env or a per-installation knob.+ req.Header.Set("locale", "zh")+ resp, err := f.cfg.HTTPClient.Do(req)+ if err != nil {+ return WSEndpoint{}, fmt.Errorf("http do: %w", err)+ }+ defer resp.Body.Close()+ rawResp, err := io.ReadAll(resp.Body)+ if err != nil {+ return WSEndpoint{}, fmt.Errorf("read body: %w", err)+ }+ if resp.StatusCode < 200 || resp.StatusCode >= 300 {+ return WSEndpoint{}, fmt.Errorf("http %d: %s", resp.StatusCode, truncate(string(rawResp), 512))+ }+ var decoded endpointResponse+ if err := json.Unmarshal(rawResp, &decoded); err != nil {+ return WSEndpoint{}, fmt.Errorf("decode response: %w (raw=%s)", err, truncate(string(rawResp), 256))+ }+ if decoded.Code != 0 || decoded.Data.URL == "" {+ // Surface the structured Lark error verbatim — that's what+ // operators need to disambiguate "app type not supported"+ // (PersonalAgent risk) from "credentials wrong" from "Lark+ // outage". The downstream Hub backoff logs this on each+ // reconnect attempt.+ return WSEndpoint{}, fmt.Errorf("lark ws endpoint: code=%d msg=%q", decoded.Code, decoded.Msg)+ }+ serviceID, err := parseServiceIDFromURL(decoded.Data.URL)+ if err != nil {+ return WSEndpoint{}, fmt.Errorf("parse service_id from wss url: %w", err)+ }+ return WSEndpoint{+ URL: decoded.Data.URL,+ Headers: http.Header{},+ ServiceID: serviceID,+ PingInterval: time.Duration(decoded.Data.ClientConfig.PingInterval) * time.Second,+ ReconnectInterval: time.Duration(decoded.Data.ClientConfig.ReconnectInterval) * time.Second,+ ReconnectNonce: time.Duration(decoded.Data.ClientConfig.ReconnectNonce) * time.Second,+ ReconnectCount: decoded.Data.ClientConfig.ReconnectCount,+ }, nil+}++// parseServiceIDFromURL extracts the `service_id` query parameter Lark+// embeds in the wss URL. The connector needs this value to address+// outbound Frame.Service for ping/pong and ACK frames; the SDK does+// the same.+func parseServiceIDFromURL(rawURL string) (int32, error) {+ u, err := url.Parse(rawURL)+ if err != nil {+ return 0, err+ }+ sid := u.Query().Get("service_id")+ if sid == "" {+ return 0, errors.New("missing service_id query parameter")+ }+ n, err := strconv.ParseInt(sid, 10, 32)+ if err != nil {+ return 0, fmt.Errorf("service_id %q is not an int: %w", sid, err)+ }+ return int32(n), nil+}diff --git a/server/internal/integrations/lark/ws_endpoint_test.go b/server/internal/integrations/lark/ws_endpoint_test.gonew file mode 100644index 0000000000..c90aba02f7--- /dev/null+++ b/server/internal/integrations/lark/ws_endpoint_test.go@@ -0,0 +1,159 @@+package lark++import (+ "context"+ "encoding/json"+ "io"+ "log/slog"+ "net/http"+ "net/http/httptest"+ "testing"+ "time"+)++// TestHTTPConnectionTokenFetcherCallbackEndpointSuccess exercises the+// happy path of the official /callback/ws/endpoint bootstrap: AppID ++// AppSecret in the body, no tenant_access_token bearer, response+// shape mirrors the SDK's EndpointResp + ClientConfig.+func TestHTTPConnectionTokenFetcherCallbackEndpointSuccess(t *testing.T) {+ t.Parallel()+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if r.URL.Path != "/callback/ws/endpoint" {+ t.Errorf("path = %q; want /callback/ws/endpoint", r.URL.Path)+ }+ if r.Method != http.MethodPost {+ t.Errorf("method = %q; want POST", r.Method)+ }+ if r.Header.Get("Authorization") != "" {+ t.Errorf("Authorization header should be empty for callback bootstrap")+ }+ var body bootstrapRequest+ _ = json.NewDecoder(r.Body).Decode(&body)+ if body.AppID != "cli_app_x" || body.AppSecret != "secret-xyz" {+ t.Errorf("body = %+v", body)+ }+ _, _ = io.WriteString(w, `{+ "code":0,+ "data":{+ "URL":"wss://lark.example/ws/foo?device_id=dev-1&service_id=42",+ "ClientConfig":{+ "ReconnectCount":-1,+ "ReconnectInterval":120,+ "ReconnectNonce":30,+ "PingInterval":120+ }+ }+ }`)+ }))+ defer srv.Close()++ f, err := NewHTTPConnectionTokenFetcher(HTTPConnectionTokenConfig{+ BaseURL: srv.URL,+ Logger: slog.New(slog.NewTextHandler(io.Discard, nil)),+ })+ if err != nil {+ t.Fatalf("constructor: %v", err)+ }+ ep, err := f.Endpoint(context.Background(), InstallationCredentials{AppID: "cli_app_x", AppSecret: "secret-xyz"})+ if err != nil {+ t.Fatalf("Endpoint: %v", err)+ }+ if ep.URL != "wss://lark.example/ws/foo?device_id=dev-1&service_id=42" {+ t.Errorf("URL = %q", ep.URL)+ }+ if ep.ServiceID != 42 {+ t.Errorf("ServiceID = %d; want 42", ep.ServiceID)+ }+ if ep.PingInterval != 120*time.Second {+ t.Errorf("PingInterval = %s; want 120s", ep.PingInterval)+ }+ if ep.ReconnectInterval != 120*time.Second {+ t.Errorf("ReconnectInterval = %s", ep.ReconnectInterval)+ }+ if ep.ReconnectNonce != 30*time.Second {+ t.Errorf("ReconnectNonce = %s", ep.ReconnectNonce)+ }+ if ep.ReconnectCount != -1 {+ t.Errorf("ReconnectCount = %d", ep.ReconnectCount)+ }+}++// TestHTTPConnectionTokenFetcherSurfacesLarkErrorCode confirms that+// app-type / auth errors from Lark (e.g. PersonalAgent not eligible)+// surface verbatim so the Hub backoff loop logs them.+func TestHTTPConnectionTokenFetcherSurfacesLarkErrorCode(t *testing.T) {+ t.Parallel()+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ _, _ = io.WriteString(w, `{"code":403,"msg":"app type not supported"}`)+ }))+ defer srv.Close()++ f, _ := NewHTTPConnectionTokenFetcher(HTTPConnectionTokenConfig{+ BaseURL: srv.URL,+ })+ _, err := f.Endpoint(context.Background(), InstallationCredentials{AppID: "a", AppSecret: "s"})+ if err == nil {+ t.Fatal("expected error for non-zero Lark code")+ }+ if !contains(err.Error(), "app type not supported") {+ t.Errorf("error should surface Lark msg: %v", err)+ }+}++func TestHTTPConnectionTokenFetcherRejectsHTTPErrorStatus(t *testing.T) {+ t.Parallel()+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ w.WriteHeader(http.StatusInternalServerError)+ _, _ = io.WriteString(w, `boom`)+ }))+ defer srv.Close()++ f, _ := NewHTTPConnectionTokenFetcher(HTTPConnectionTokenConfig{+ BaseURL: srv.URL,+ })+ _, err := f.Endpoint(context.Background(), InstallationCredentials{AppID: "a", AppSecret: "s"})+ if err == nil {+ t.Fatal("expected error on 5xx")+ }+}++func TestHTTPConnectionTokenFetcherRejectsMissingCredentials(t *testing.T) {+ t.Parallel()+ f, _ := NewHTTPConnectionTokenFetcher(HTTPConnectionTokenConfig{BaseURL: "http://unused"})+ if _, err := f.Endpoint(context.Background(), InstallationCredentials{AppID: ""}); err == nil {+ t.Fatal("expected error on missing app_id")+ }+ if _, err := f.Endpoint(context.Background(), InstallationCredentials{AppID: "a"}); err == nil {+ t.Fatal("expected error on missing app_secret")+ }+}++func TestHTTPConnectionTokenFetcherRejectsURLWithoutServiceID(t *testing.T) {+ t.Parallel()+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ // Response URL is well-formed but missing the service_id+ // query param — the connector can't address outbound frames+ // without it, so the fetcher must reject the bootstrap.+ _, _ = io.WriteString(w, `{"code":0,"data":{"URL":"wss://lark.example/ws?device_id=dev-1","ClientConfig":{"PingInterval":120}}}`)+ }))+ defer srv.Close()++ f, _ := NewHTTPConnectionTokenFetcher(HTTPConnectionTokenConfig{BaseURL: srv.URL})+ _, err := f.Endpoint(context.Background(), InstallationCredentials{AppID: "a", AppSecret: "s"})+ if err == nil {+ t.Fatal("expected error when service_id is missing from response URL")+ }+}++func contains(s, sub string) bool {+ return s != "" && sub != "" && (s == sub || (len(s) > len(sub) && indexOf(s, sub) >= 0))+}++func indexOf(s, sub string) int {+ for i := 0; i+len(sub) <= len(s); i++ {+ if s[i:i+len(sub)] == sub {+ return i+ }+ }+ return -1+}diff --git a/server/internal/integrations/lark/ws_frame.go b/server/internal/integrations/lark/ws_frame.gonew file mode 100644index 0000000000..17de574af7--- /dev/null+++ b/server/internal/integrations/lark/ws_frame.go@@ -0,0 +1,387 @@+package lark++import (+ "errors"+ "fmt"++ "google.golang.org/protobuf/encoding/protowire"+)++// Wire-compatible re-implementation of the Lark/Feishu long-connection+// binary Frame envelope. The encoded bytes are byte-identical to what+// the official SDK's github.com/larksuite/oapi-sdk-go/v3/ws Frame+// produces, which matters because Lark's server rejects frames whose+// required fields are missing — and the SDK is generated from+// pbbp2.proto using proto2 + gogo `req` semantics, so SeqID / LogID /+// Service / Method are emitted unconditionally (even when zero) and the+// opt string fields (PayloadEncoding / PayloadType / LogIDNew) are also+// emitted unconditionally because gogo's generated code skips the+// zero-guard for opt strings on this message. Only Payload uses the+// `nil` guard. See the SDK's pbbp2.pb.go MarshalToSizedBuffer for the+// reference; mismatches against that function silently corrupt the+// stream because round-tripping against our own UnmarshalFrame masks+// the bug.+//+// We re-encode by hand using google.golang.org/protobuf/encoding/protowire+// rather than importing the official SDK's pbbp2 package: the SDK has+// a large transitive dependency tree (full open-platform client,+// generated code for every API surface) and we only need this one+// message type. Hand-rolling the encode/decode for a 9-field message+// is bounded while the dependency surface stays small. The golden+// tests in ws_frame_test.go pin the exact byte sequence the SDK would+// produce for a handful of canonical frames; that is the load-bearing+// compatibility check.++const (+ // FrameMethodControl identifies a frame whose Method=Control(0).+ // Control frames carry ping/pong and server-pushed ClientConfig+ // updates; they never carry an inbound event payload.+ FrameMethodControl int32 = 0++ // FrameMethodData identifies a frame whose Method=Data(1). Data+ // frames carry the actual event payload (im.message.receive_v1,+ // card interaction, etc.) and require an ACK response.+ FrameMethodData int32 = 1+)++// FrameHeaderType enumerates the values Lark puts in the Frame+// header keyed `type`. These drive per-frame routing logic.+const (+ FrameHeaderTypeKey = "type"+ FrameHeaderTypeEvent = "event"+ FrameHeaderTypeCard = "card"+ FrameHeaderTypePing = "ping"+ FrameHeaderTypePong = "pong"++ // FrameHeaderMessageIDKey is the dedup / chunk key Lark sets on+ // each data frame; reused as-is in the ACK so server can correlate.+ FrameHeaderMessageIDKey = "message_id"++ // FrameHeaderSumKey / FrameHeaderSeqKey carry chunking metadata+ // for multi-frame payloads (sum>1 means N chunks indexed by seq).+ // The chunk assembler in ws_chunk_assembler.go uses these to+ // reassemble a single JSON payload from multiple Frames before+ // invoking the decoder.+ FrameHeaderSumKey = "sum"+ FrameHeaderSeqKey = "seq"+)++// FrameHeader is one (key, value) pair in Frame.Headers. Equivalent to+// the SDK's pbbp2.Header.+type FrameHeader struct {+ Key string+ Value string+}++// Frame mirrors pbbp2.Frame. Field numbers match the SDK proto so the+// on-wire bytes are byte-identical to what oapi-sdk-go produces.+//+// The Marshal implementation matches the SDK's gogo-generated code:+// SeqID, LogID, Service, Method are emitted unconditionally as proto2+// required fields; PayloadEncoding, PayloadType, LogIDNew are emitted+// unconditionally with zero-length values when empty (matches the+// generated code's unconditional copy + length-encoding); Payload is+// emitted only when non-nil. The golden tests pin exact byte sequences.+type Frame struct {+ SeqID uint64 // proto field 1 (req)+ LogID uint64 // proto field 2 (req)+ Service int32 // proto field 3 (req)+ Method int32 // proto field 4 (req)+ Headers []FrameHeader // proto field 5 (rep)+ PayloadEncoding string // proto field 6 (opt)+ PayloadType string // proto field 7 (opt)+ Payload []byte // proto field 8 (opt)+ LogIDNew string // proto field 9 (opt)+}++// HeaderValue returns the value for the first header with the supplied+// key, or "" if absent. Lark uses headers as a flat map, but the SDK's+// proto schema is a repeated field — we treat duplicates as "first+// wins" because that's what the SDK does in practice.+func (f *Frame) HeaderValue(key string) string {+ for _, h := range f.Headers {+ if h.Key == key {+ return h.Value+ }+ }+ return ""+}++// Marshal encodes the frame to the wire format Lark expects. The+// returned bytes are sent verbatim as the WebSocket binary payload.+//+// Field emission order matches the SDK's MarshalToSizedBuffer reverse+// build (fields 1→9 in the final byte stream). DO NOT change which+// fields are emitted unconditionally without re-checking the SDK's+// generated MarshalToSizedBuffer — it is the authority on wire shape+// and divergence is invisible until Lark's server starts dropping+// frames in production.+func (f *Frame) Marshal() []byte {+ buf := make([]byte, 0, 64+len(f.Payload))++ // Required fields (proto2 req): always emit tag + varint, even when+ // the value is zero. The SDK's generated code unconditionally writes+ // these; a Lark server reading a Frame missing one of them returns+ // a RequiredNotSetError and discards the frame.+ buf = protowire.AppendTag(buf, 1, protowire.VarintType)+ buf = protowire.AppendVarint(buf, f.SeqID)+ buf = protowire.AppendTag(buf, 2, protowire.VarintType)+ buf = protowire.AppendVarint(buf, f.LogID)+ buf = protowire.AppendTag(buf, 3, protowire.VarintType)+ buf = protowire.AppendVarint(buf, uint64(uint32(f.Service)))+ buf = protowire.AppendTag(buf, 4, protowire.VarintType)+ buf = protowire.AppendVarint(buf, uint64(uint32(f.Method)))++ // Repeated headers — emit one length-prefixed entry per FrameHeader.+ // Empty Headers list emits nothing, matching the SDK guard.+ for _, h := range f.Headers {+ buf = protowire.AppendTag(buf, 5, protowire.BytesType)+ buf = protowire.AppendVarint(buf, uint64(headerSize(h)))+ // Header.Key (field 1) and Header.Value (field 2) are both+ // proto2 req — emit unconditionally.+ buf = protowire.AppendTag(buf, 1, protowire.BytesType)+ buf = protowire.AppendString(buf, h.Key)+ buf = protowire.AppendTag(buf, 2, protowire.BytesType)+ buf = protowire.AppendString(buf, h.Value)+ }++ // PayloadEncoding (field 6) — gogo's generated code copies the+ // string unconditionally and emits the tag + length prefix even+ // when len==0. Empty string still produces tag + zero-length.+ buf = protowire.AppendTag(buf, 6, protowire.BytesType)+ buf = protowire.AppendString(buf, f.PayloadEncoding)++ // PayloadType (field 7) — same unconditional emission as PayloadEncoding.+ buf = protowire.AppendTag(buf, 7, protowire.BytesType)+ buf = protowire.AppendString(buf, f.PayloadType)++ // Payload (field 8) — the SDK uses `if m.Payload != nil`. We mirror+ // that: nil omits the tag entirely; non-nil emits, even if len==0.+ if f.Payload != nil {+ buf = protowire.AppendTag(buf, 8, protowire.BytesType)+ buf = protowire.AppendBytes(buf, f.Payload)+ }++ // LogIDNew (field 9) — unconditional like PayloadEncoding/Type.+ buf = protowire.AppendTag(buf, 9, protowire.BytesType)+ buf = protowire.AppendString(buf, f.LogIDNew)++ return buf+}++func headerSize(h FrameHeader) int {+ // Both fields are req and always emitted; their byte cost is+ // tag + length-prefix(len) + len.+ return protowire.SizeTag(1) + protowire.SizeBytes(len(h.Key)) ++ protowire.SizeTag(2) + protowire.SizeBytes(len(h.Value))+}++// UnmarshalFrame parses one binary protobuf message into a Frame.+// Unknown fields are skipped (proto3 behaviour) so server-side schema+// additions do not break us. Truncated / malformed bytes return an+// error and the caller (the WS connector) treats the frame as bad+// and drops it without tearing down the connection.+func UnmarshalFrame(b []byte) (*Frame, error) {+ if len(b) == 0 {+ return nil, errors.New("ws frame: empty buffer")+ }+ f := &Frame{}+ for len(b) > 0 {+ num, typ, n := protowire.ConsumeTag(b)+ if err := protowire.ParseError(n); err != nil {+ return nil, fmt.Errorf("ws frame: consume tag: %w", err)+ }+ b = b[n:]+ switch num {+ case 1: // SeqID uint64+ if typ != protowire.VarintType {+ return nil, fmt.Errorf("ws frame: field 1 expects varint, got %v", typ)+ }+ v, m := protowire.ConsumeVarint(b)+ if err := protowire.ParseError(m); err != nil {+ return nil, fmt.Errorf("ws frame: consume seq_id: %w", err)+ }+ f.SeqID = v+ b = b[m:]+ case 2: // LogID uint64+ if typ != protowire.VarintType {+ return nil, fmt.Errorf("ws frame: field 2 expects varint, got %v", typ)+ }+ v, m := protowire.ConsumeVarint(b)+ if err := protowire.ParseError(m); err != nil {+ return nil, fmt.Errorf("ws frame: consume log_id: %w", err)+ }+ f.LogID = v+ b = b[m:]+ case 3: // Service int32+ if typ != protowire.VarintType {+ return nil, fmt.Errorf("ws frame: field 3 expects varint, got %v", typ)+ }+ v, m := protowire.ConsumeVarint(b)+ if err := protowire.ParseError(m); err != nil {+ return nil, fmt.Errorf("ws frame: consume service: %w", err)+ }+ f.Service = int32(v)+ b = b[m:]+ case 4: // Method int32+ if typ != protowire.VarintType {+ return nil, fmt.Errorf("ws frame: field 4 expects varint, got %v", typ)+ }+ v, m := protowire.ConsumeVarint(b)+ if err := protowire.ParseError(m); err != nil {+ return nil, fmt.Errorf("ws frame: consume method: %w", err)+ }+ f.Method = int32(v)+ b = b[m:]+ case 5: // Headers (repeated)+ if typ != protowire.BytesType {+ return nil, fmt.Errorf("ws frame: field 5 expects bytes, got %v", typ)+ }+ hb, m := protowire.ConsumeBytes(b)+ if err := protowire.ParseError(m); err != nil {+ return nil, fmt.Errorf("ws frame: consume header: %w", err)+ }+ h, herr := unmarshalHeader(hb)+ if herr != nil {+ return nil, herr+ }+ f.Headers = append(f.Headers, h)+ b = b[m:]+ case 6: // PayloadEncoding string+ if typ != protowire.BytesType {+ return nil, fmt.Errorf("ws frame: field 6 expects bytes, got %v", typ)+ }+ s, m := protowire.ConsumeString(b)+ if err := protowire.ParseError(m); err != nil {+ return nil, fmt.Errorf("ws frame: consume payload_encoding: %w", err)+ }+ f.PayloadEncoding = s+ b = b[m:]+ case 7: // PayloadType string+ if typ != protowire.BytesType {+ return nil, fmt.Errorf("ws frame: field 7 expects bytes, got %v", typ)+ }+ s, m := protowire.ConsumeString(b)+ if err := protowire.ParseError(m); err != nil {+ return nil, fmt.Errorf("ws frame: consume payload_type: %w", err)+ }+ f.PayloadType = s+ b = b[m:]+ case 8: // Payload bytes+ if typ != protowire.BytesType {+ return nil, fmt.Errorf("ws frame: field 8 expects bytes, got %v", typ)+ }+ raw, m := protowire.ConsumeBytes(b)+ if err := protowire.ParseError(m); err != nil {+ return nil, fmt.Errorf("ws frame: consume payload: %w", err)+ }+ // Copy out so the Frame outlives the input buffer+ // (ConsumeBytes returns a sub-slice).+ f.Payload = append([]byte(nil), raw...)+ b = b[m:]+ case 9: // LogIDNew string+ if typ != protowire.BytesType {+ return nil, fmt.Errorf("ws frame: field 9 expects bytes, got %v", typ)+ }+ s, m := protowire.ConsumeString(b)+ if err := protowire.ParseError(m); err != nil {+ return nil, fmt.Errorf("ws frame: consume log_id_new: %w", err)+ }+ f.LogIDNew = s+ b = b[m:]+ default:+ m := protowire.ConsumeFieldValue(num, typ, b)+ if err := protowire.ParseError(m); err != nil {+ return nil, fmt.Errorf("ws frame: skip unknown field %d: %w", num, err)+ }+ b = b[m:]+ }+ }+ return f, nil+}++func unmarshalHeader(b []byte) (FrameHeader, error) {+ var h FrameHeader+ for len(b) > 0 {+ num, typ, n := protowire.ConsumeTag(b)+ if err := protowire.ParseError(n); err != nil {+ return FrameHeader{}, fmt.Errorf("ws frame: header tag: %w", err)+ }+ b = b[n:]+ switch num {+ case 1:+ if typ != protowire.BytesType {+ return FrameHeader{}, fmt.Errorf("ws frame: header.key expects bytes, got %v", typ)+ }+ s, m := protowire.ConsumeString(b)+ if err := protowire.ParseError(m); err != nil {+ return FrameHeader{}, fmt.Errorf("ws frame: header.key: %w", err)+ }+ h.Key = s+ b = b[m:]+ case 2:+ if typ != protowire.BytesType {+ return FrameHeader{}, fmt.Errorf("ws frame: header.value expects bytes, got %v", typ)+ }+ s, m := protowire.ConsumeString(b)+ if err := protowire.ParseError(m); err != nil {+ return FrameHeader{}, fmt.Errorf("ws frame: header.value: %w", err)+ }+ h.Value = s+ b = b[m:]+ default:+ m := protowire.ConsumeFieldValue(num, typ, b)+ if err := protowire.ParseError(m); err != nil {+ return FrameHeader{}, fmt.Errorf("ws frame: skip header field %d: %w", num, err)+ }+ b = b[m:]+ }+ }+ return h, nil+}++// NewPingFrame builds the client-side keepalive frame. Lark's long+// connection uses an app-layer ping (binary Frame with type=ping),+// NOT a WebSocket protocol-level PING — gorilla's WriteControl pings+// would be ignored.+func NewPingFrame(serviceID int32) *Frame {+ return &Frame{+ Method: FrameMethodControl,+ Service: serviceID,+ Headers: []FrameHeader{{Key: FrameHeaderTypeKey, Value: FrameHeaderTypePing}},+ }+}++// NewPongFrame builds the client-side response to a server-initiated+// ping. Lark may push ping frames at any cadence; we reply in kind.+func NewPongFrame(serviceID int32) *Frame {+ return &Frame{+ Method: FrameMethodControl,+ Service: serviceID,+ Headers: []FrameHeader{{Key: FrameHeaderTypeKey, Value: FrameHeaderTypePong}},+ }+}++// NewAckFrame builds the ACK response for an inbound data frame.+// Per the SDK, the ACK reuses the inbound frame's Headers verbatim+// (so the server can correlate by message_id) and writes a JSON-+// encoded Response struct as the Payload.+//+// codeOK is true on successful dispatch (Response.code=200); false+// surfaces 500 to the server (it will retry the event). The payload+// shape mirrors the SDK's NewResponseByCode JSON: a nil Headers map+// and nil Data slice both marshal to JSON null in stdlib encoding/json,+// which is what the server expects to receive.+func NewAckFrame(inbound *Frame, codeOK bool) *Frame {+ code := 200+ if !codeOK {+ code = 500+ }+ payload := fmt.Sprintf(`{"code":%d,"headers":null,"data":null}`, code)+ return &Frame{+ Method: inbound.Method,+ Service: inbound.Service,+ Headers: inbound.Headers,+ Payload: []byte(payload),+ }+}diff --git a/server/internal/integrations/lark/ws_frame_decoder.go b/server/internal/integrations/lark/ws_frame_decoder.gonew file mode 100644index 0000000000..682c5c4500--- /dev/null+++ b/server/internal/integrations/lark/ws_frame_decoder.go@@ -0,0 +1,316 @@+package lark++import (+ "encoding/json"+ "errors"+ "fmt"+ "sort"+ "strings"++ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++// LarkJSONFrameDecoder decodes the JSON event payload Lark nests+// inside a long-conn data Frame. The outer binary Frame envelope+// (ws_frame.go) is stripped by the connector; the decoder only sees+// the bytes from Frame.Payload, which Lark formats as the standard+// event-subscription envelope: {schema, header, event}.+//+// Three outcomes:+//+// - (msg, true, nil) — `im.message.receive_v1` event. The Hub+// forwards through the Dispatcher.+// - (zero, false, nil) — heartbeat-shaped JSON or an event_type we+// don't yet handle (im.chat.access_event_v1, etc.). The connector+// drops these silently and still sends a 200 ACK to Lark so the+// server stops resending.+// - (zero, false, err) — malformed JSON or schema we couldn't+// parse. The connector logs + drops the single frame; the WS+// connection stays up because one bad payload shouldn't amplify+// into a reconnect storm.+//+// The decoder is stateless and goroutine-safe — a single instance+// serves every supervisor goroutine.+type LarkJSONFrameDecoder struct{}++func NewLarkJSONFrameDecoder() *LarkJSONFrameDecoder { return &LarkJSONFrameDecoder{} }++// Decode implements FrameDecoder.+func (d *LarkJSONFrameDecoder) Decode(payload []byte, inst db.LarkInstallation) (InboundMessage, bool, error) {+ if len(payload) == 0 {+ return InboundMessage{}, false, nil+ }+ var env larkEventEnvelope+ if err := json.Unmarshal(payload, &env); err != nil {+ return InboundMessage{}, false, fmt.Errorf("envelope: %w", err)+ }++ // Lark long-conn data frames are always v2 event envelopes+ // (schema "2.0"). The legacy webhook v1 "type":"event_callback"+ // shape is not used on long-conn — we accept it defensively in+ // case Lark adds a back-compat mode, but the canonical path is+ // schema-driven.+ if env.Type != "" && env.Type != "event_callback" {+ return InboundMessage{}, false, nil+ }++ if env.Header.EventType != "im.message.receive_v1" {+ return InboundMessage{}, false, nil+ }++ if env.Event == nil {+ return InboundMessage{}, false, errors.New("event_callback with empty event payload")+ }+ var evt larkMessageReceiveEvent+ if err := json.Unmarshal(env.Event, &evt); err != nil {+ return InboundMessage{}, false, fmt.Errorf("event: %w", err)+ }++ msg := InboundMessage{+ EventType: env.Header.EventType,+ EventID: env.Header.EventID,+ AppID: env.Header.AppID,+ ChatID: ChatID(evt.Message.ChatID),+ ChatType: normalizeChatType(evt.Message.ChatType),+ MessageID: evt.Message.MessageID,+ SenderOpenID: OpenID(evt.Sender.SenderID.OpenID),+ }++ botUnionID := ""+ if inst.BotUnionID.Valid {+ botUnionID = inst.BotUnionID.String+ }++ switch evt.Message.MessageType {+ case "text":+ msg.Body = resolveMentions(extractTextBody(evt.Message.Content),+ evt.Message.Mentions, inst.BotOpenID, botUnionID)+ }++ if msg.ChatType == ChatTypeGroup {+ msg.AddressedToBot = containsMention(evt.Message.Mentions, inst.BotOpenID, botUnionID)+ }++ return msg, true, nil+}++// larkEventEnvelope mirrors the outer JSON Lark wraps every push in.+type larkEventEnvelope struct {+ Schema string `json:"schema"`+ Type string `json:"type"`+ Header larkEventHeader `json:"header"`+ Event json.RawMessage `json:"event"`+}++type larkEventHeader struct {+ EventID string `json:"event_id"`+ EventType string `json:"event_type"`+ CreateTime string `json:"create_time"`+ AppID string `json:"app_id"`+ TenantKey string `json:"tenant_key"`+}++// larkMessageReceiveEvent is the documented payload of+// im.message.receive_v1.+type larkMessageReceiveEvent struct {+ Sender struct {+ SenderID struct {+ OpenID string `json:"open_id"`+ UnionID string `json:"union_id"`+ UserID string `json:"user_id"`+ } `json:"sender_id"`+ SenderType string `json:"sender_type"`+ TenantKey string `json:"tenant_key"`+ } `json:"sender"`+ Message struct {+ MessageID string `json:"message_id"`+ ChatID string `json:"chat_id"`+ ChatType string `json:"chat_type"`+ MessageType string `json:"message_type"`+ Content string `json:"content"`+ Mentions []larkMention `json:"mentions"`+ CreateTime string `json:"create_time"`+ } `json:"message"`+}++type larkMention struct {+ Key string `json:"key"`+ ID struct {+ OpenID string `json:"open_id"`+ UnionID string `json:"union_id"`+ UserID string `json:"user_id"`+ } `json:"id"`+ Name string `json:"name"`+}++// resolveMentions substitutes Lark's `@_user_N` placeholders so the+// agent receives a body that reads naturally and does not require+// resolving the mentions array itself. The bot's OWN mention is+// stripped (the dispatcher already routes the event on+// AddressedToBot — re-emitting `@<bot>` in front of every message+// makes both the chat transcript and any downstream LLM context+// noisier without adding signal). Other participants render as+// `@<displayName>`, falling back to leaving the placeholder alone+// when name is empty (defensive — Lark always populates it in+// practice).+//+// Replacement is a single-pass token scan, not naive ReplaceAll. Two+// reasons:+//+// - Prefix collision: a chat with eleven @-mentions exposes keys+// `@_user_1` and `@_user_10`; ReplaceAll for `@_user_1` would+// mangle the substring of `@_user_10`. We sort keys by length+// DESC and try the longest match at each scan position so the+// longer placeholder always wins.+//+// - Whitespace fidelity: when we strip the bot mention we only+// touch a single space immediately adjacent to it — either the+// space after the placeholder, or, if there is none, a single+// trailing space already in the output. Tabs, indentation, code+// blocks, table pipes, and any other intentional whitespace in+// the user's message are preserved verbatim.+func resolveMentions(text string, mentions []larkMention, botOpenID, botUnionID string) string {+ if text == "" || len(mentions) == 0 {+ return text+ }+ // Filter empty keys and sort longest first so `@_user_10` is+ // matched before `@_user_1` at any scan position.+ sorted := make([]larkMention, 0, len(mentions))+ for _, m := range mentions {+ if m.Key != "" {+ sorted = append(sorted, m)+ }+ }+ sort.SliceStable(sorted, func(i, j int) bool {+ return len(sorted[i].Key) > len(sorted[j].Key)+ })++ out := make([]byte, 0, len(text))+ i := 0+ for i < len(text) {+ var matched *larkMention+ for idx := range sorted {+ if strings.HasPrefix(text[i:], sorted[idx].Key) {+ matched = &sorted[idx]+ break+ }+ }+ if matched == nil {+ out = append(out, text[i])+ i+++ continue+ }+ end := i + len(matched.Key)+ switch {+ case isBotMention(*matched, botOpenID, botUnionID):+ // Strip: eat one adjacent space (after the placeholder+ // preferred; else backtrack one space we already emitted)+ // so the seam is not left with a double space or a+ // dangling leading space. Tabs / newlines / other chars+ // are untouched.+ if end < len(text) && text[end] == ' ' {+ end+++ } else if n := len(out); n > 0 && out[n-1] == ' ' {+ out = out[:n-1]+ }+ case matched.Name != "":+ out = append(out, '@')+ out = append(out, matched.Name...)+ default:+ // Unknown mention — leave the placeholder intact so the+ // agent at least sees a stable token.+ out = append(out, matched.Key...)+ }+ i = end+ }+ return string(out)+}++// isBotMention identifies whether a payload mention refers to THIS+// bot. Stays in lockstep with containsMention: when union_id is+// known we trust it exclusively (open_id is structurally inverted+// in multi-bot groups — matching on it would re-introduce the+// MUL-2671 routing bug). Only when union_id is missing do we fall+// back to open_id, which is correct in single-bot installs and the+// best we can do in pre-backfill rows.+func isBotMention(m larkMention, botOpenID, botUnionID string) bool {+ if botUnionID != "" {+ return m.ID.UnionID == botUnionID+ }+ if botOpenID == "" {+ return false+ }+ return m.ID.OpenID == botOpenID+}++func extractTextBody(content string) string {+ if content == "" {+ return ""+ }+ var doc struct {+ Text string `json:"text"`+ }+ if err := json.Unmarshal([]byte(content), &doc); err != nil {+ return ""+ }+ return doc.Text+}++func normalizeChatType(t string) ChatType {+ switch strings.ToLower(t) {+ case "p2p":+ return ChatTypeP2P+ case "group":+ return ChatTypeGroup+ default:+ return ChatType(t)+ }+}++// containsMention answers "was THIS bot @-mentioned in this group event".+//+// The bot's stable identifier across WS perspectives is `union_id` —+// see MUL-2671 group-@-mention triage. In a Lark group with several+// Multica bots, each bot's WS receives the event, and Lark fills+// `mentions[].id.open_id` with the per-app form for whichever bot it+// is talking to: bot X's WS sees X's payload-form open_id when bot Y+// was @-ed, and a different payload-form open_id when X itself was+// the target. Only `union_id` is consistent across both WS streams.+//+// Match order:+//+// 1. When we know the bot's `union_id` (captured by GetBotInfo at+// install time, persisted in lark_installation.bot_union_id),+// compare against `mentions[].id.union_id`. This is the correct+// path and is unambiguous in multi-bot deployments.+//+// 2. When `union_id` is unknown — single-bot installs created+// before migration 112, or contact-scope-restricted operators+// where /contact/v3/users denied the lookup — fall back to the+// per-app `open_id` comparison. This is structurally inverted+// in multi-bot group chats but is fine for the p2p/single-bot+// case the WS sees most of the time, and avoids hard-failing+// pre-backfill installations.+//+// Empty inputs short-circuit to false rather than matching every+// mention; that defends against an installation row that somehow+// has both identifiers blank.+func containsMention(mentions []larkMention, botOpenID, botUnionID string) bool {+ if botUnionID != "" {+ for _, m := range mentions {+ if m.ID.UnionID == botUnionID {+ return true+ }+ }+ return false+ }+ if botOpenID == "" {+ return false+ }+ for _, m := range mentions {+ if m.ID.OpenID == botOpenID {+ return true+ }+ }+ return false+}diff --git a/server/internal/integrations/lark/ws_frame_decoder_test.go b/server/internal/integrations/lark/ws_frame_decoder_test.gonew file mode 100644index 0000000000..f1ba451c96--- /dev/null+++ b/server/internal/integrations/lark/ws_frame_decoder_test.go@@ -0,0 +1,453 @@+package lark++import (+ "encoding/json"+ "testing"++ "github.com/jackc/pgx/v5/pgtype"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++func TestLarkJSONFrameDecoderTextMessageInP2P(t *testing.T) {+ t.Parallel()+ raw := []byte(`{+ "type":"event_callback",+ "header":{+ "event_id":"evt-1",+ "event_type":"im.message.receive_v1",+ "app_id":"cli_app_x"+ },+ "event":{+ "sender":{+ "sender_id":{"open_id":"ou_user"},+ "sender_type":"user"+ },+ "message":{+ "message_id":"om_1",+ "chat_id":"oc_1",+ "chat_type":"p2p",+ "message_type":"text",+ "content":"{\"text\":\"hello\"}"+ }+ }+ }`)++ d := NewLarkJSONFrameDecoder()+ msg, ok, err := d.Decode(raw, db.LarkInstallation{BotOpenID: "ou_bot"})+ if err != nil || !ok {+ t.Fatalf("Decode ok=%v err=%v", ok, err)+ }+ if msg.EventID != "evt-1" {+ t.Errorf("EventID = %q", msg.EventID)+ }+ if msg.AppID != "cli_app_x" {+ t.Errorf("AppID = %q", msg.AppID)+ }+ if msg.ChatType != ChatTypeP2P {+ t.Errorf("ChatType = %q", msg.ChatType)+ }+ if msg.MessageID != "om_1" {+ t.Errorf("MessageID = %q", msg.MessageID)+ }+ if msg.SenderOpenID != "ou_user" {+ t.Errorf("SenderOpenID = %q", msg.SenderOpenID)+ }+ if msg.Body != "hello" {+ t.Errorf("Body = %q", msg.Body)+ }+ if msg.AddressedToBot {+ t.Errorf("P2P AddressedToBot should not be true")+ }+}++func TestLarkJSONFrameDecoderGroupMentionDiscrimination(t *testing.T) {+ t.Parallel()+ mkRaw := func(mentionOpenID string) []byte {+ return []byte(`{+ "type":"event_callback",+ "header":{"event_id":"e","event_type":"im.message.receive_v1","app_id":"a"},+ "event":{+ "sender":{"sender_id":{"open_id":"ou_user"}},+ "message":{+ "message_id":"m","chat_id":"c","chat_type":"group",+ "message_type":"text","content":"{\"text\":\"hi\"}",+ "mentions":[{"id":{"open_id":"` + mentionOpenID + `"}}]+ }+ }+ }`)+ }+ d := NewLarkJSONFrameDecoder()++ t.Run("mentions bot", func(t *testing.T) {+ msg, ok, err := d.Decode(mkRaw("ou_bot"), db.LarkInstallation{BotOpenID: "ou_bot"})+ if err != nil || !ok {+ t.Fatalf("ok=%v err=%v", ok, err)+ }+ if msg.ChatType != ChatTypeGroup {+ t.Errorf("ChatType = %q", msg.ChatType)+ }+ if !msg.AddressedToBot {+ t.Error("AddressedToBot = false; expected true")+ }+ })++ t.Run("mentions other user", func(t *testing.T) {+ msg, ok, err := d.Decode(mkRaw("ou_other"), db.LarkInstallation{BotOpenID: "ou_bot"})+ if err != nil || !ok {+ t.Fatalf("ok=%v err=%v", ok, err)+ }+ if msg.AddressedToBot {+ t.Error("AddressedToBot = true; expected false")+ }+ })+}++// TestLarkJSONFrameDecoderGroupMentionUnionID exercises the MUL-2671+// fix: in a multi-bot group chat the per-app `mentions[].id.open_id`+// is structurally inverted across WS perspectives, so we route on+// `union_id` (the stable, cross-app identifier captured at install+// time) when the installation row knows it. The open_id path remains+// as a transitional fallback for installations that haven't been+// backfilled yet.+func TestLarkJSONFrameDecoderGroupMentionUnionID(t *testing.T) {+ t.Parallel()++ mkRaw := func(mentionOpenID, mentionUnionID string) []byte {+ return []byte(`{+ "type":"event_callback",+ "header":{"event_id":"e","event_type":"im.message.receive_v1","app_id":"a"},+ "event":{+ "sender":{"sender_id":{"open_id":"ou_user"}},+ "message":{+ "message_id":"m","chat_id":"c","chat_type":"group",+ "message_type":"text","content":"{\"text\":\"hi\"}",+ "mentions":[{"id":{"open_id":"` + mentionOpenID + `","union_id":"` + mentionUnionID + `"}}]+ }+ }+ }`)+ }+ d := NewLarkJSONFrameDecoder()+ pgText := func(s string) pgtype.Text { return pgtype.Text{String: s, Valid: true} }++ t.Run("union_id match wins even when open_id mismatches", func(t *testing.T) {+ // Two-bot group chat, this bot's WS perspective:+ // payload.mentions[0].open_id is the WIRE-form open_id Lark+ // hands us (not equal to our installation's bot_open_id,+ // which is what /bot/v3/info returned), but the union_id is+ // the stable identifier we captured at install. The match+ // must succeed.+ inst := db.LarkInstallation{+ BotOpenID: "ou_bot_a_canonical",+ BotUnionID: pgText("on_bot_a_union"),+ }+ msg, ok, err := d.Decode(mkRaw("ou_bot_a_wire", "on_bot_a_union"), inst)+ if err != nil || !ok {+ t.Fatalf("ok=%v err=%v", ok, err)+ }+ if !msg.AddressedToBot {+ t.Error("AddressedToBot = false; expected true via union_id")+ }+ })++ t.Run("union_id mismatch wins even when open_id matches", func(t *testing.T) {+ // The other bot in the group was @-mentioned; Lark hands+ // THIS bot's WS a payload whose mentions[].id.open_id+ // happens to equal our bot_open_id (the inverse-mapping+ // quirk Bohan's live triage surfaced). The match must NOT+ // fire — union_id is the source of truth.+ inst := db.LarkInstallation{+ BotOpenID: "ou_bot_a_canonical",+ BotUnionID: pgText("on_bot_a_union"),+ }+ msg, ok, err := d.Decode(mkRaw("ou_bot_a_canonical", "on_bot_b_union"), inst)+ if err != nil || !ok {+ t.Fatalf("ok=%v err=%v", ok, err)+ }+ if msg.AddressedToBot {+ t.Error("AddressedToBot = true; expected false because union_id points at the OTHER bot")+ }+ })++ t.Run("falls back to open_id when union_id is unknown", func(t *testing.T) {+ // Pre-backfill installation row: no union_id yet. Decoder+ // must keep working in the single-bot case via the legacy+ // open_id comparison.+ inst := db.LarkInstallation{BotOpenID: "ou_bot_a_canonical"}+ msg, ok, err := d.Decode(mkRaw("ou_bot_a_canonical", "on_anything"), inst)+ if err != nil || !ok {+ t.Fatalf("ok=%v err=%v", ok, err)+ }+ if !msg.AddressedToBot {+ t.Error("AddressedToBot = false; expected true via legacy open_id fallback")+ }+ })+}++// TestLarkJSONFrameDecoderMentionPlaceholderRewrite covers the body+// cleanup: Lark inlines `@_user_N` placeholders inside the text and+// resolves them via the `mentions` array. We strip the bot's own+// mention (the dispatcher already routes the event), substitute+// other users with `@<displayName>`, and leave the agent with a+// natural-looking message body.+func TestLarkJSONFrameDecoderMentionPlaceholderRewrite(t *testing.T) {+ t.Parallel()+ pgText := func(s string) pgtype.Text { return pgtype.Text{String: s, Valid: true} }++ mkRaw := func(text, mentionsJSON string) []byte {+ // Lark wraps text in a `{"text": ...}` JSON envelope inside+ // `message.content`; we double-encode below to match wire.+ contentDoc := map[string]string{"text": text}+ contentBytes, _ := json.Marshal(contentDoc)+ contentEsc, _ := json.Marshal(string(contentBytes))+ return []byte(`{+ "type":"event_callback",+ "header":{"event_id":"e","event_type":"im.message.receive_v1","app_id":"a"},+ "event":{+ "sender":{"sender_id":{"open_id":"ou_user"}},+ "message":{+ "message_id":"m","chat_id":"c","chat_type":"group",+ "message_type":"text",+ "content":` + string(contentEsc) + `,+ "mentions":` + mentionsJSON + `+ }+ }+ }`)+ }+ d := NewLarkJSONFrameDecoder()++ t.Run("strips bot self-mention via union_id", func(t *testing.T) {+ inst := db.LarkInstallation{+ BotOpenID: "ou_bot",+ BotUnionID: pgText("on_bot"),+ }+ mentions := `[{"key":"@_user_1","name":"My Bot","id":{"open_id":"ou_bot_wire","union_id":"on_bot"}}]`+ msg, ok, err := d.Decode(mkRaw("@_user_1 ping test", mentions), inst)+ if err != nil || !ok {+ t.Fatalf("ok=%v err=%v", ok, err)+ }+ if msg.Body != "ping test" {+ t.Errorf("Body = %q; want %q", msg.Body, "ping test")+ }+ })++ t.Run("substitutes other-user mention with display name", func(t *testing.T) {+ inst := db.LarkInstallation{+ BotOpenID: "ou_bot",+ BotUnionID: pgText("on_bot"),+ }+ mentions := `[+ {"key":"@_user_1","name":"My Bot","id":{"open_id":"ou_bot_wire","union_id":"on_bot"}},+ {"key":"@_user_2","name":"Alice","id":{"open_id":"ou_alice","union_id":"on_alice"}}+ ]`+ msg, ok, err := d.Decode(mkRaw("@_user_1 hey @_user_2 take a look", mentions), inst)+ if err != nil || !ok {+ t.Fatalf("ok=%v err=%v", ok, err)+ }+ if msg.Body != "hey @Alice take a look" {+ t.Errorf("Body = %q; want %q", msg.Body, "hey @Alice take a look")+ }+ })++ t.Run("preserves newlines after stripped mention", func(t *testing.T) {+ // Strip the bot mention + one adjacent space; the newline that+ // follows stays put so the rest of the message keeps its+ // shape. User-typed extra spaces (the double space here) are+ // preserved verbatim — we do not globally collapse whitespace.+ inst := db.LarkInstallation{+ BotOpenID: "ou_bot",+ BotUnionID: pgText("on_bot"),+ }+ mentions := `[{"key":"@_user_1","name":"My Bot","id":{"open_id":"ou_bot_wire","union_id":"on_bot"}}]`+ msg, ok, err := d.Decode(mkRaw("@_user_1 first line\nsecond line", mentions), inst)+ if err != nil || !ok {+ t.Fatalf("ok=%v err=%v", ok, err)+ }+ if msg.Body != " first line\nsecond line" {+ t.Errorf("Body = %q; want %q", msg.Body, " first line\nsecond line")+ }+ })++ t.Run("no mentions leaves body unchanged", func(t *testing.T) {+ inst := db.LarkInstallation{+ BotOpenID: "ou_bot",+ BotUnionID: pgText("on_bot"),+ }+ msg, ok, err := d.Decode(mkRaw("just a normal message", `[]`), inst)+ if err != nil || !ok {+ t.Fatalf("ok=%v err=%v", ok, err)+ }+ if msg.Body != "just a normal message" {+ t.Errorf("Body = %q; want %q", msg.Body, "just a normal message")+ }+ })++ t.Run("preserves indentation and tabs around stripped mention", func(t *testing.T) {+ // Code-block / indented messages: stripping the bot mention+ // must not eat the surrounding indent, tabs, or any internal+ // whitespace the user intentionally typed. We only consume a+ // single space directly adjacent to the placeholder.+ inst := db.LarkInstallation{+ BotOpenID: "ou_bot",+ BotUnionID: pgText("on_bot"),+ }+ mentions := `[{"key":"@_user_1","name":"My Bot","id":{"open_id":"ou_bot_wire","union_id":"on_bot"}}]`+ raw := " @_user_1 review this snippet:\n\tfunc add(a, b int) int {\n\t\treturn a + b\n\t}"+ want := " review this snippet:\n\tfunc add(a, b int) int {\n\t\treturn a + b\n\t}"+ msg, ok, err := d.Decode(mkRaw(raw, mentions), inst)+ if err != nil || !ok {+ t.Fatalf("ok=%v err=%v", ok, err)+ }+ if msg.Body != want {+ t.Errorf("Body = %q; want %q", msg.Body, want)+ }+ })++ t.Run("avoids @_user_1 / @_user_10 prefix collision", func(t *testing.T) {+ // Lark assigns mention keys positionally; a chat with eleven++ // participants exposes both `@_user_1` and `@_user_10`. Naive+ // ReplaceAll for `@_user_1` would mangle `@_user_10`, so we+ // match longest-first.+ inst := db.LarkInstallation{+ BotOpenID: "ou_bot",+ BotUnionID: pgText("on_bot"),+ }+ mentions := `[+ {"key":"@_user_1","name":"My Bot","id":{"open_id":"ou_bot_wire","union_id":"on_bot"}},+ {"key":"@_user_10","name":"Alice","id":{"open_id":"ou_alice","union_id":"on_alice"}}+ ]`+ raw := "@_user_1 forward this to @_user_10 please"+ want := "forward this to @Alice please"+ msg, ok, err := d.Decode(mkRaw(raw, mentions), inst)+ if err != nil || !ok {+ t.Fatalf("ok=%v err=%v", ok, err)+ }+ if msg.Body != want {+ t.Errorf("Body = %q; want %q", msg.Body, want)+ }+ })++ t.Run("@-ing both bots in one message strips only self, renders other by name", func(t *testing.T) {+ // Multi-bot group chat where the user @-mentions BOTH bots in+ // the same message. From this WS's perspective only the self+ // mention should be stripped; the sibling bot renders as+ // @<displayName> so the agent receives a faithful transcript+ // of the user intent.+ inst := db.LarkInstallation{+ BotOpenID: "ou_self_canonical",+ BotUnionID: pgText("on_self_union"),+ }+ mentions := `[+ {"key":"@_user_1","name":"Self Bot","id":{"open_id":"ou_self_wire","union_id":"on_self_union"}},+ {"key":"@_user_2","name":"Sibling Bot","id":{"open_id":"ou_sibling_wire","union_id":"on_sibling_union"}}+ ]`+ raw := "@_user_1 @_user_2 please coordinate"+ want := "@Sibling Bot please coordinate"+ msg, ok, err := d.Decode(mkRaw(raw, mentions), inst)+ if err != nil || !ok {+ t.Fatalf("ok=%v err=%v", ok, err)+ }+ if msg.Body != want {+ t.Errorf("Body = %q; want %q", msg.Body, want)+ }+ })++ t.Run("open_id match does NOT strip when union_id known but differs", func(t *testing.T) {+ // Mirror of containsMention's union_id-first rule: when we+ // know our union_id, an open_id-only match means the mention+ // is for the OTHER bot (the inverse-mapping quirk), so we+ // must render it as @<name>, not strip it.+ inst := db.LarkInstallation{+ BotOpenID: "ou_self_canonical",+ BotUnionID: pgText("on_self_union"),+ }+ mentions := `[{"key":"@_user_1","name":"Sibling Bot","id":{"open_id":"ou_self_canonical","union_id":"on_sibling_union"}}]`+ raw := "@_user_1 hi"+ want := "@Sibling Bot hi"+ msg, ok, err := d.Decode(mkRaw(raw, mentions), inst)+ if err != nil || !ok {+ t.Fatalf("ok=%v err=%v", ok, err)+ }+ if msg.Body != want {+ t.Errorf("Body = %q; want %q", msg.Body, want)+ }+ })+}++func TestLarkJSONFrameDecoderDropsHeartbeat(t *testing.T) {+ t.Parallel()+ d := NewLarkJSONFrameDecoder()+ cases := [][]byte{+ []byte(`{"type":"heartbeat"}`),+ []byte(`{"type":"frame_ack","data":{"id":"1"}}`),+ []byte(`{"type":"event_callback","header":{"event_type":"im.message.unknown_kind"}}`),+ }+ for _, raw := range cases {+ msg, ok, err := d.Decode(raw, db.LarkInstallation{})+ if err != nil || ok {+ t.Errorf("Decode(%q) ok=%v err=%v; expected (false, nil)", raw, ok, err)+ }+ if msg.EventID != "" {+ t.Errorf("expected zero-value InboundMessage on drop, got %+v", msg)+ }+ }+}++func TestLarkJSONFrameDecoderEmptyRaw(t *testing.T) {+ t.Parallel()+ msg, ok, err := NewLarkJSONFrameDecoder().Decode(nil, db.LarkInstallation{})+ if ok || err != nil {+ t.Fatalf("expected (zero, false, nil) for empty raw; got ok=%v err=%v msg=%+v", ok, err, msg)+ }+}++func TestLarkJSONFrameDecoderMalformedReturnsError(t *testing.T) {+ t.Parallel()+ _, ok, err := NewLarkJSONFrameDecoder().Decode([]byte("not-json"), db.LarkInstallation{})+ if err == nil {+ t.Fatal("expected error on malformed envelope")+ }+ if ok {+ t.Error("ok should be false on decode failure")+ }+}++func TestLarkJSONFrameDecoderMessageContentEmptyOnInvalidContentJSON(t *testing.T) {+ t.Parallel()+ raw := []byte(`{+ "type":"event_callback",+ "header":{"event_id":"e","event_type":"im.message.receive_v1","app_id":"a"},+ "event":{+ "sender":{"sender_id":{"open_id":"ou_user"}},+ "message":{"message_id":"m","chat_id":"c","chat_type":"p2p","message_type":"text","content":"not-json"}+ }+ }`)+ msg, ok, err := NewLarkJSONFrameDecoder().Decode(raw, db.LarkInstallation{})+ if err != nil || !ok {+ t.Fatalf("ok=%v err=%v", ok, err)+ }+ if msg.Body != "" {+ t.Errorf("Body = %q; expected empty on unparseable content", msg.Body)+ }+}++func TestLarkJSONFrameDecoderNonTextMessageHasEmptyBody(t *testing.T) {+ t.Parallel()+ raw := []byte(`{+ "type":"event_callback",+ "header":{"event_id":"e","event_type":"im.message.receive_v1","app_id":"a"},+ "event":{+ "sender":{"sender_id":{"open_id":"ou_user"}},+ "message":{"message_id":"m","chat_id":"c","chat_type":"p2p","message_type":"image","content":"{\"image_key\":\"img1\"}"}+ }+ }`)+ msg, ok, err := NewLarkJSONFrameDecoder().Decode(raw, db.LarkInstallation{})+ if err != nil || !ok {+ t.Fatalf("ok=%v err=%v", ok, err)+ }+ if msg.Body != "" {+ t.Errorf("Body = %q; non-text messages should have empty body in MVP", msg.Body)+ }+ if msg.MessageID == "" {+ t.Error("MessageID should still be populated for non-text events")+ }+}diff --git a/server/internal/integrations/lark/ws_frame_test.go b/server/internal/integrations/lark/ws_frame_test.gonew file mode 100644index 0000000000..31e8b12d48--- /dev/null+++ b/server/internal/integrations/lark/ws_frame_test.go@@ -0,0 +1,250 @@+package lark++import (+ "bytes"+ "encoding/hex"+ "testing"+)++// TestFrameRoundTripPreservesAllFields ensures every set field on the+// outbound Frame survives marshal+unmarshal. This catches symmetric+// bugs (where our marshal and unmarshal agree but neither matches the+// SDK); the golden-byte tests below are the actual byte-compat check.+func TestFrameRoundTripPreservesAllFields(t *testing.T) {+ t.Parallel()+ in := &Frame{+ SeqID: 42,+ LogID: 99,+ Service: 7,+ Method: FrameMethodData,+ Headers: []FrameHeader{{Key: "type", Value: "event"}, {Key: "message_id", Value: "om-1"}},+ PayloadEncoding: "json",+ PayloadType: "im.message.receive_v1",+ Payload: []byte(`{"schema":"2.0"}`),+ LogIDNew: "log-new",+ }+ out, err := UnmarshalFrame(in.Marshal())+ if err != nil {+ t.Fatalf("UnmarshalFrame: %v", err)+ }+ if out.SeqID != in.SeqID || out.LogID != in.LogID || out.Service != in.Service || out.Method != in.Method {+ t.Errorf("scalar fields differ: in=%+v out=%+v", in, out)+ }+ if len(out.Headers) != len(in.Headers) {+ t.Fatalf("Headers len = %d; want %d", len(out.Headers), len(in.Headers))+ }+ for i, h := range out.Headers {+ if h != in.Headers[i] {+ t.Errorf("Headers[%d] = %+v; want %+v", i, h, in.Headers[i])+ }+ }+ if out.PayloadEncoding != in.PayloadEncoding {+ t.Errorf("PayloadEncoding = %q; want %q", out.PayloadEncoding, in.PayloadEncoding)+ }+ if out.PayloadType != in.PayloadType {+ t.Errorf("PayloadType = %q; want %q", out.PayloadType, in.PayloadType)+ }+ if !bytes.Equal(out.Payload, in.Payload) {+ t.Errorf("Payload = %q; want %q", string(out.Payload), string(in.Payload))+ }+ if out.LogIDNew != in.LogIDNew {+ t.Errorf("LogIDNew = %q; want %q", out.LogIDNew, in.LogIDNew)+ }+}++// TestFrameMarshalIsSDKByteCompatible pins the exact byte sequences the+// official SDK's pbbp2.Frame.MarshalToSizedBuffer would produce for the+// canonical frames we emit on the wire (ping, pong, ACK, full event).+//+// These goldens were computed by hand-replicating the SDK's MarshalTo+// SizedBuffer logic (which itself is gogo-generated code from+// pbbp2.proto, see the SDK at v3_main/ws/pbbp2.pb.go) — reversed byte+// build, proto2 req fields emitted unconditionally, gogo opt strings+// emitted unconditionally with zero-length when empty, opt Payload+// gated by nil. Any divergence between our Marshal() and these bytes+// means Lark's server will reject the frame as a RequiredNotSetError.+//+// DO NOT alter the goldens to match a refactor of Marshal(). Goldens+// pin SDK behaviour; if they drift, either the SDK changed or our+// implementation broke compatibility. Verify against the SDK source+// before touching them.+func TestFrameMarshalIsSDKByteCompatible(t *testing.T) {+ t.Parallel()+ cases := []struct {+ name string+ frame *Frame+ expected string // hex+ }{+ {+ name: "ping_frame",+ frame: NewPingFrame(7),+ // Field 1 (SeqID=0): 08 00+ // Field 2 (LogID=0): 10 00+ // Field 3 (Service=7): 18 07+ // Field 4 (Method=0/Control): 20 00+ // Field 5 (one header "type"="ping"): 2a 0c 0a 04 74 79 70 65 12 04 70 69 6e 67+ // Field 6 (PayloadEncoding=""): 32 00+ // Field 7 (PayloadType=""): 3a 00+ // Field 8 (Payload nil): omitted+ // Field 9 (LogIDNew=""): 4a 00+ expected: "08001000180720002a0c0a0474797065120470696e6732003a004a00",+ },+ {+ name: "pong_frame_service_42",+ frame: NewPongFrame(42),+ expected: "08001000182a20002a0c0a04747970651204706f6e6732003a004a00",+ },+ {+ name: "ack_data_frame",+ frame: NewAckFrame(&Frame{+ Method: FrameMethodData,+ Service: 7,+ Headers: []FrameHeader{+ {Key: FrameHeaderTypeKey, Value: FrameHeaderTypeEvent},+ {Key: FrameHeaderMessageIDKey, Value: "om-42"},+ },+ }, true),+ // Payload bytes are the JSON {"code":200,"headers":null,"data":null}+ // which the SDK's NewResponseByCode + json.Marshal produces.+ expected: "08001000180720012a0d0a047479706512056576656e742a130a0a6d6573736167655f696412056f6d2d343232003a0042277b22636f6465223a3230302c2268656164657273223a6e756c6c2c2264617461223a6e756c6c7d4a00",+ },+ {+ name: "full_data_frame_all_fields",+ frame: &Frame{+ SeqID: 42,+ LogID: 99,+ Service: 7,+ Method: FrameMethodData,+ Headers: []FrameHeader{{Key: "type", Value: "event"}, {Key: "message_id", Value: "om-1"}},+ PayloadEncoding: "json",+ PayloadType: "im.message.receive_v1",+ Payload: []byte(`{"schema":"2.0"}`),+ LogIDNew: "log-new",+ },+ expected: "082a1063180720012a0d0a047479706512056576656e742a120a0a6d6573736167655f696412046f6d2d3132046a736f6e3a15696d2e6d6573736167652e726563656976655f763142107b22736368656d61223a22322e30227d4a076c6f672d6e6577",+ },+ {+ // Zero-valued frame still has all req + opt-string fields+ // emitted; only Payload (nil) is omitted. Matches the SDK+ // "no fields set" baseline.+ name: "zero_frame_emits_required_and_opt_strings",+ frame: &Frame{},+ expected: "080010001800200032003a004a00",+ },+ }+ for _, c := range cases {+ t.Run(c.name, func(t *testing.T) {+ t.Parallel()+ got := c.frame.Marshal()+ want, err := hex.DecodeString(c.expected)+ if err != nil {+ t.Fatalf("decode golden hex: %v", err)+ }+ if !bytes.Equal(got, want) {+ t.Errorf("Marshal bytes mismatch\n got: %s\n want: %s",+ hex.EncodeToString(got), c.expected)+ }+ })+ }+}++// TestFrameMarshalEmitsRequiredZeroFields verifies the proto2 `req`+// semantics: SeqID/LogID/Service/Method must appear in the byte stream+// even when their values are zero. A previous implementation skipped+// these on zero (proto3 semantics), which would cause Lark's server to+// reject every ping frame.+func TestFrameMarshalEmitsRequiredZeroFields(t *testing.T) {+ t.Parallel()+ raw := (&Frame{}).Marshal()+ // Required fields are written as: tag(1byte) + value-varint.+ // All zero values varint-encode to a single 0x00 byte.+ // So we expect the prefix to contain field 1..4 tags + 0x00 each.+ wantPrefix := []byte{+ 0x08, 0x00, // field 1 (SeqID=0)+ 0x10, 0x00, // field 2 (LogID=0)+ 0x18, 0x00, // field 3 (Service=0)+ 0x20, 0x00, // field 4 (Method=0)+ }+ if !bytes.HasPrefix(raw, wantPrefix) {+ t.Errorf("required zero fields missing\n got prefix: %x\n want: %x",+ raw[:min(len(raw), len(wantPrefix))], wantPrefix)+ }+}++func TestFrameMarshalPayloadNilVsEmpty(t *testing.T) {+ t.Parallel()+ // Nil payload: field 8 omitted entirely.+ noPayload := (&Frame{}).Marshal()+ if bytes.Contains(noPayload, []byte{0x42}) {+ t.Errorf("nil Payload should not emit field 8 tag; got %x", noPayload)+ }+ // Empty (non-nil) payload: field 8 emitted with zero length.+ emptyPayload := (&Frame{Payload: []byte{}}).Marshal()+ // Look for "42 00" (tag, length=0) appearing between PayloadType+ // (field 7, tag=0x3a) and LogIDNew (field 9, tag=0x4a).+ if !bytes.Contains(emptyPayload, []byte{0x3a, 0x00, 0x42, 0x00, 0x4a, 0x00}) {+ t.Errorf("empty non-nil Payload should emit tag+0-length; got %x", emptyPayload)+ }+}++func TestNewAckFrameReusesInboundHeaders(t *testing.T) {+ t.Parallel()+ inbound := &Frame{+ Method: FrameMethodData,+ Service: 7,+ Headers: []FrameHeader{+ {Key: FrameHeaderTypeKey, Value: FrameHeaderTypeEvent},+ {Key: FrameHeaderMessageIDKey, Value: "om-42"},+ },+ }+ ack := NewAckFrame(inbound, true)+ if ack.Method != inbound.Method || ack.Service != inbound.Service {+ t.Errorf("ack method/service mismatch")+ }+ if len(ack.Headers) != len(inbound.Headers) {+ t.Errorf("ack headers length mismatch")+ }+ if ack.HeaderValue(FrameHeaderMessageIDKey) != "om-42" {+ t.Errorf("ack should echo message_id; got %q", ack.HeaderValue(FrameHeaderMessageIDKey))+ }+ if !bytes.Contains(ack.Payload, []byte(`"code":200`)) {+ t.Errorf("ack payload missing code=200: %s", string(ack.Payload))+ }+ if !bytes.Contains(ack.Payload, []byte(`"headers":null`)) {+ t.Errorf("ack payload should have null headers (SDK shape): %s", string(ack.Payload))+ }+ if !bytes.Contains(ack.Payload, []byte(`"data":null`)) {+ t.Errorf("ack payload should have null data (SDK shape): %s", string(ack.Payload))+ }++ nack := NewAckFrame(inbound, false)+ if !bytes.Contains(nack.Payload, []byte(`"code":500`)) {+ t.Errorf("nack payload missing code=500: %s", string(nack.Payload))+ }+}++func TestUnmarshalFrameRejectsTruncatedBuffer(t *testing.T) {+ t.Parallel()+ if _, err := UnmarshalFrame(nil); err == nil {+ t.Error("expected error on empty buffer")+ }+ if _, err := UnmarshalFrame([]byte{0x08}); err == nil {+ t.Error("expected error on truncated varint")+ }+}++func TestUnmarshalFrameSkipsUnknownFields(t *testing.T) {+ t.Parallel()+ buf := []byte{}+ // field 3 (varint): tag = 3<<3|0 = 0x18, value = 5+ buf = append(buf, 0x18, 0x05)+ // field 31 (varint): tag = 31<<3|0 = 0xF8 0x01, value = 99 (0x63)+ buf = append(buf, 0xF8, 0x01, 0x63)+ f, err := UnmarshalFrame(buf)+ if err != nil {+ t.Fatalf("expected unknown field to be skipped, got error: %v", err)+ }+ if f.Service != 5 {+ t.Errorf("Service = %d; want 5", f.Service)+ }+}diff --git a/server/internal/service/issue.go b/server/internal/service/issue.gonew file mode 100644index 0000000000..a18a0badc7--- /dev/null+++ b/server/internal/service/issue.go@@ -0,0 +1,473 @@+package service++import (+ "context"+ "errors"+ "fmt"+ "log/slog"++ "github.com/jackc/pgx/v5/pgtype"+ "github.com/multica-ai/multica/server/internal/analytics"+ "github.com/multica-ai/multica/server/internal/events"+ "github.com/multica-ai/multica/server/internal/issueguard"+ "github.com/multica-ai/multica/server/internal/issueposition"+ obsmetrics "github.com/multica-ai/multica/server/internal/metrics"+ "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"+)++// IssueService is the single service-layer entry point for creating issues.+// Both the HTTP `POST /issues` handler and the future Lark `/issue` command+// call into Create so that duplicate guard, issue numbering, attachment+// linking, broadcast, analytics, and agent/squad enqueue stay aligned. The+// service deliberately does NOT depend on http.Request — callers parse+// their own transport and pass a fully-resolved IssueCreateParams.+type IssueService struct {+ Queries *db.Queries+ TxStarter TxStarter+ Bus *events.Bus+ Analytics analytics.Client+ // Metrics is the shared business-metrics collector. Wired by+ // cmd/server/router.go after construction; nil in tests / self-hosted+ // without the metrics listener — obsmetrics.RecordEvent treats a nil+ // Metrics as "PostHog only", so leaving it unset is safe.+ Metrics *obsmetrics.BusinessMetrics+ TaskService *TaskService+}++func NewIssueService(q *db.Queries, tx TxStarter, bus *events.Bus, ac analytics.Client, ts *TaskService) *IssueService {+ return &IssueService{+ Queries: q,+ TxStarter: tx,+ Bus: bus,+ Analytics: ac,+ TaskService: ts,+ }+}++// IssueCreateParams carries the already-validated, already-resolved inputs+// to IssueService.Create. The handler owns the parsing step that turns its+// request payload into this struct; the service stays transport-agnostic.+type IssueCreateParams struct {+ WorkspaceID pgtype.UUID+ Title string+ Description pgtype.Text+ Status string+ Priority string+ AssigneeType pgtype.Text+ AssigneeID pgtype.UUID+ CreatorType string // "agent" or "member"+ CreatorID pgtype.UUID+ ParentIssueID pgtype.UUID+ ProjectID pgtype.UUID+ StartDate pgtype.Date+ DueDate pgtype.Date+ OriginType pgtype.Text+ OriginID pgtype.UUID+ AttachmentIDs []pgtype.UUID+ AllowDuplicate bool+}++// IssueCreateOpts groups optional knobs for IssueService.Create. Most+// callers leave it zero-valued.+type IssueCreateOpts struct {+ // BroadcastPayload, if non-nil, is invoked after the issue row is+ // created and attachments are linked. Its return value is sent as+ // the EventIssueCreated payload via the event bus. The HTTP handler+ // uses this hook to inject its IssueResponse without forcing this+ // package to depend on handler-layer types. If nil, the service+ // emits a minimal `{"issue_id": <uuid>}` payload — enough for cache+ // invalidation, but front-ends that expect the full response shape+ // must provide BroadcastPayload.+ BroadcastPayload func(issue db.Issue, attachments []db.Attachment) map[string]any++ // ActorID overrides the actor ID used for broadcast + analytics+ // when it differs from the creator on the row. Agent-created issues+ // use the agent UUID here (the creator_id column is the daemon+ // owner). Empty falls back to CreatorID.+ ActorID string++ // AnalyticsAgentID is the agent associated with the issue for+ // analytics purposes (assignee agent or, for agent-created issues,+ // the creator agent). Resolved by the caller because it depends on+ // transport context.+ AnalyticsAgentID string++ // Platform tags the IssueCreated analytics + business-metrics event+ // with the client surface the request came in on (web / desktop /+ // daemon / lark / autopilot). Derived from middleware's client+ // metadata at the handler layer.+ Platform string+}++// ErrActiveDuplicate signals that the duplicate guard found an active+// issue with the same (workspace, project, parent, title) tuple and+// AllowDuplicate was false. The IssueCreateResult.DuplicateIssue field is+// populated when this error is returned so callers can render the+// conflict (HTTP 409, Lark card, etc.).+var ErrActiveDuplicate = errors.New("active duplicate issue exists")++// ErrParentIssueNotFound signals that the supplied ParentIssueID does+// not exist in the issue's workspace. The service refuses to create+// orphaned or cross-workspace child issues; callers translate this into+// their transport's 400 / Lark card error.+var ErrParentIssueNotFound = errors.New("parent issue not found in this workspace")++// ErrProjectNotFound signals that the supplied ProjectID does not exist+// in the issue's workspace. Cross-workspace project IDs are rejected+// here so every create entry (HTTP `POST /issues`, Lark `/issue`, future+// MCP / API key callers) enforces the same workspace boundary without+// having to remember it. Callers translate this into 400.+var ErrProjectNotFound = errors.New("project not found in this workspace")++// IssueCreateResult is the typed return from IssueService.Create.+//+// - On the happy path: Issue is the new row, Attachments lists the+// linked attachments (may be empty), DuplicateIssue is nil.+// - On ErrActiveDuplicate: DuplicateIssue is the row that blocked the+// create; Issue and Attachments are zero.+type IssueCreateResult struct {+ Issue db.Issue+ Attachments []db.Attachment+ DuplicateIssue *db.Issue+}++// Create runs the full issue-creation pipeline atomically end-to-end:+//+// 1. Begin transaction.+// 2. Resolve & validate parent / project belong to the same workspace.+// 3. Lock & check the duplicate guard.+// 4. Increment the workspace issue counter.+// 5. Insert the issue row (with optional origin stamping).+// 6. Commit.+// 7. Link any pre-uploaded attachments (post-commit, idempotent).+// 8. Publish EventIssueCreated to the bus (payload via opts.BroadcastPayload).+// 9. Capture the IssueCreated analytics event.+// 10. Enqueue an agent task or trigger the squad leader when the issue is+// assigned and not in `backlog`.+//+// Validation that lives in the service (parent existence, project+// workspace membership, parent → project back-fill) is enforced here so+// every create entry — HTTP `POST /issues`, Lark `/issue`, future+// MCP/API-key callers — shares the same workspace boundary semantics.+// Caller-owned validation is limited to transport-shaped checks: title+// required, RFC3339 date format, assignee pair sanity.+func (s *IssueService) Create(ctx context.Context, p IssueCreateParams, opts IssueCreateOpts) (IssueCreateResult, error) {+ tx, err := s.TxStarter.Begin(ctx)+ if err != nil {+ return IssueCreateResult{}, fmt.Errorf("begin tx: %w", err)+ }+ defer tx.Rollback(ctx)+ qtx := s.Queries.WithTx(tx)++ // Resolve and validate parent / project before reading from the+ // duplicate guard so a forged parent or project ID is rejected+ // before we touch the issue counter. Both checks scope by+ // WorkspaceID — there is no path from this service to a row in a+ // foreign workspace.+ projectID := p.ProjectID+ if p.ParentIssueID.Valid {+ parent, err := qtx.GetIssueInWorkspace(ctx, db.GetIssueInWorkspaceParams{+ ID: p.ParentIssueID,+ WorkspaceID: p.WorkspaceID,+ })+ if err != nil || !parent.ID.Valid {+ return IssueCreateResult{}, ErrParentIssueNotFound+ }+ // Back-fill project from parent when the caller did not pin+ // one explicitly. Matches the long-standing HTTP behavior: a+ // sub-issue inherits its parent's project unless overridden.+ if !projectID.Valid {+ projectID = parent.ProjectID+ }+ }+ if projectID.Valid {+ if _, err := qtx.GetProjectInWorkspace(ctx, db.GetProjectInWorkspaceParams{+ ID: projectID,+ WorkspaceID: p.WorkspaceID,+ }); err != nil {+ return IssueCreateResult{}, ErrProjectNotFound+ }+ }++ duplicate, found, err := issueguard.LockAndFindActiveDuplicate(ctx, qtx, p.WorkspaceID, projectID, p.ParentIssueID, p.Title, p.AllowDuplicate)+ if err != nil {+ return IssueCreateResult{}, fmt.Errorf("duplicate guard: %w", err)+ }+ if found {+ dup := duplicate+ return IssueCreateResult{DuplicateIssue: &dup}, ErrActiveDuplicate+ }++ issueNumber, err := qtx.IncrementIssueCounter(ctx, p.WorkspaceID)+ if err != nil {+ return IssueCreateResult{}, fmt.Errorf("increment counter: %w", err)+ }++ // New issues sort to the top of their (workspace, status) column for+ // manual ordering. Computed inside the tx, after IncrementIssueCounter+ // has already taken the workspace row lock, so two concurrent creates+ // in the same workspace see each other's positions and don't both+ // land on the same min-1 slot. Concurrent manual reorder via+ // UpdateIssue(position) does NOT take this lock, so a create racing+ // a reorder is still allowed to collide on position — manual ordering+ // is best-effort and the UI tolerates equal positions by falling back+ // to the secondary ORDER BY key.+ newPosition, err := issueposition.NextTopPosition(ctx, tx, p.WorkspaceID, p.Status)+ if err != nil {+ return IssueCreateResult{}, fmt.Errorf("next top position: %w", err)+ }++ var issue db.Issue+ if p.OriginType.Valid {+ issue, err = qtx.CreateIssueWithOrigin(ctx, db.CreateIssueWithOriginParams{+ WorkspaceID: p.WorkspaceID,+ Title: p.Title,+ Description: p.Description,+ Status: p.Status,+ Priority: p.Priority,+ AssigneeType: p.AssigneeType,+ AssigneeID: p.AssigneeID,+ CreatorType: p.CreatorType,+ CreatorID: p.CreatorID,+ ParentIssueID: p.ParentIssueID,+ Position: newPosition,+ StartDate: p.StartDate,+ DueDate: p.DueDate,+ Number: issueNumber,+ ProjectID: projectID,+ OriginType: p.OriginType,+ OriginID: p.OriginID,+ })+ } else {+ issue, err = qtx.CreateIssue(ctx, db.CreateIssueParams{+ WorkspaceID: p.WorkspaceID,+ Title: p.Title,+ Description: p.Description,+ Status: p.Status,+ Priority: p.Priority,+ AssigneeType: p.AssigneeType,+ AssigneeID: p.AssigneeID,+ CreatorType: p.CreatorType,+ CreatorID: p.CreatorID,+ ParentIssueID: p.ParentIssueID,+ Position: newPosition,+ StartDate: p.StartDate,+ DueDate: p.DueDate,+ Number: issueNumber,+ ProjectID: projectID,+ })+ }+ if err != nil {+ return IssueCreateResult{}, fmt.Errorf("create issue: %w", err)+ }++ if err := tx.Commit(ctx); err != nil {+ return IssueCreateResult{}, fmt.Errorf("commit: %w", err)+ }++ attachments := s.linkAttachments(ctx, issue, p.AttachmentIDs)++ actorID := opts.ActorID+ if actorID == "" {+ actorID = util.UUIDToString(issue.CreatorID)+ }++ s.publishIssueCreated(issue, attachments, p.CreatorType, actorID, opts)+ s.captureCreatedAnalytics(issue, p.CreatorType, actorID, opts)+ s.maybeEnqueueOnAssign(ctx, issue, p.CreatorType, actorID)++ return IssueCreateResult{Issue: issue, Attachments: attachments}, nil+}++// linkAttachments links the given attachment IDs to the newly created+// issue and returns the re-fetched attachment rows so callers can build+// their response without a second query. Errors are logged and swallowed+// — attachment linking is a best-effort post-commit step, and a stale+// attachment row doesn't justify failing the whole create.+func (s *IssueService) linkAttachments(ctx context.Context, issue db.Issue, ids []pgtype.UUID) []db.Attachment {+ if len(ids) == 0 {+ return nil+ }+ if err := s.Queries.LinkAttachmentsToIssue(ctx, db.LinkAttachmentsToIssueParams{+ IssueID: issue.ID,+ WorkspaceID: issue.WorkspaceID,+ Column3: ids,+ }); err != nil {+ slog.Error("failed to link attachments to issue",+ "issue_id", util.UUIDToString(issue.ID),+ "error", err)+ return nil+ }+ list, err := s.Queries.ListAttachmentsByIssue(ctx, db.ListAttachmentsByIssueParams{+ IssueID: issue.ID,+ WorkspaceID: issue.WorkspaceID,+ })+ if err != nil {+ slog.Warn("failed to list attachments for new issue",+ "issue_id", util.UUIDToString(issue.ID),+ "error", err)+ return nil+ }+ return list+}++func (s *IssueService) publishIssueCreated(issue db.Issue, attachments []db.Attachment, creatorType, actorID string, opts IssueCreateOpts) {+ if s.Bus == nil {+ return+ }+ var payload map[string]any+ if opts.BroadcastPayload != nil {+ payload = opts.BroadcastPayload(issue, attachments)+ } else {+ // Minimal fallback so cache invalidations still fire even if the+ // caller forgot to supply a builder. Front-ends that expect the+ // full IssueResponse must pass BroadcastPayload.+ payload = map[string]any{"issue_id": util.UUIDToString(issue.ID)}+ }+ s.Bus.Publish(events.Event{+ Type: protocol.EventIssueCreated,+ WorkspaceID: util.UUIDToString(issue.WorkspaceID),+ ActorType: creatorType,+ ActorID: actorID,+ Payload: payload,+ })+}++func (s *IssueService) captureCreatedAnalytics(issue db.Issue, creatorType, actorID string, opts IssueCreateOpts) {+ if s.Analytics == nil {+ return+ }+ source, taskID, autopilotRunID := classifyOrigin(issue, opts)+ analyticsActorID := actorID+ if creatorType == "agent" {+ analyticsActorID = "agent:" + actorID+ }+ obsmetrics.RecordEvent(s.Analytics, s.Metrics, analytics.IssueCreated(+ analyticsActorID,+ util.UUIDToString(issue.WorkspaceID),+ util.UUIDToString(issue.ID),+ opts.AnalyticsAgentID,+ taskID,+ autopilotRunID,+ source,+ opts.Platform,+ ))+}++// classifyOrigin maps the issue's origin_type / origin_id columns into the+// analytics source labels. Unknown origin_type falls back to SourceManual+// with the warning logged — analytics drift is preferable to dropping the+// event entirely.+func classifyOrigin(issue db.Issue, opts IssueCreateOpts) (source, taskID, autopilotRunID string) {+ source = analytics.SourceManual+ if !issue.OriginType.Valid {+ return source, "", ""+ }+ originID := util.UUIDToString(issue.OriginID)+ switch issue.OriginType.String {+ case "quick_create":+ return analytics.SourceManual, originID, ""+ case "autopilot":+ return analytics.SourceAutopilot, "", originID+ default:+ slog.Warn("analytics: unknown issue origin type",+ "origin_type", issue.OriginType.String,+ "issue_id", util.UUIDToString(issue.ID),+ )+ return analytics.SourceManual, "", ""+ }+}++func (s *IssueService) maybeEnqueueOnAssign(ctx context.Context, issue db.Issue, creatorType, actorID string) {+ if !issue.AssigneeType.Valid || !issue.AssigneeID.Valid {+ return+ }+ if s.shouldEnqueueAgentTask(ctx, issue) {+ if _, err := s.TaskService.EnqueueTaskForIssue(ctx, issue); err != nil {+ slog.Warn("enqueue agent task on create failed",+ "issue_id", util.UUIDToString(issue.ID),+ "error", err)+ }+ }+ if s.shouldEnqueueSquadLeaderOnAssign(ctx, issue) {+ s.enqueueSquadLeaderTask(ctx, issue, pgtype.UUID{}, creatorType, actorID)+ }+}++// shouldEnqueueAgentTask returns true when an issue create or assignment+// should trigger the assigned agent. Backlog issues are skipped — backlog+// acts as a parking lot for pre-assigning without immediate execution.+// Mirrors handler.shouldEnqueueAgentTask; kept here to make the service+// self-contained, since both code paths must move together.+func (s *IssueService) shouldEnqueueAgentTask(ctx context.Context, issue db.Issue) bool {+ if issue.Status == "backlog" {+ return false+ }+ return s.isAgentAssigneeReady(ctx, issue)+}++func (s *IssueService) isAgentAssigneeReady(ctx context.Context, issue db.Issue) bool {+ if !issue.AssigneeType.Valid || issue.AssigneeType.String != "agent" || !issue.AssigneeID.Valid {+ return false+ }+ agent, err := s.Queries.GetAgent(ctx, issue.AssigneeID)+ if err != nil || !agent.RuntimeID.Valid || agent.ArchivedAt.Valid {+ return false+ }+ return true+}++func (s *IssueService) shouldEnqueueSquadLeaderOnAssign(ctx context.Context, issue db.Issue) bool {+ if issue.Status == "backlog" {+ return false+ }+ return s.isSquadLeaderReady(ctx, issue)+}++func (s *IssueService) isSquadLeaderReady(ctx context.Context, issue db.Issue) bool {+ if !issue.AssigneeType.Valid || issue.AssigneeType.String != "squad" || !issue.AssigneeID.Valid {+ return false+ }+ squad, err := s.Queries.GetSquadInWorkspace(ctx, db.GetSquadInWorkspaceParams{+ ID: issue.AssigneeID,+ WorkspaceID: issue.WorkspaceID,+ })+ if err != nil {+ return false+ }+ agent, err := s.Queries.GetAgent(ctx, squad.LeaderID)+ if err != nil {+ return false+ }+ ready, _, err := AgentReadiness(ctx, s.Queries, agent)+ if err != nil {+ return false+ }+ return ready+}++func (s *IssueService) enqueueSquadLeaderTask(ctx context.Context, issue db.Issue, triggerCommentID pgtype.UUID, authorType, authorID string) {+ squad, err := s.Queries.GetSquadInWorkspace(ctx, db.GetSquadInWorkspaceParams{+ ID: issue.AssigneeID,+ WorkspaceID: issue.WorkspaceID,+ })+ if err != nil {+ return+ }+ hasPending, err := s.Queries.HasPendingTaskForIssueAndAgent(ctx, db.HasPendingTaskForIssueAndAgentParams{+ IssueID: issue.ID,+ AgentID: squad.LeaderID,+ })+ if err != nil || hasPending {+ return+ }+ if _, err := s.TaskService.EnqueueTaskForSquadLeader(ctx, issue, squad.LeaderID, triggerCommentID); err != nil {+ slog.Warn("enqueue squad leader task on create failed",+ "issue_id", util.UUIDToString(issue.ID),+ "squad_id", util.UUIDToString(squad.ID),+ "leader_id", util.UUIDToString(squad.LeaderID),+ "error", err)+ }+}diff --git a/server/internal/service/task.go b/server/internal/service/task.goindex bc6ae760a7..2c17522608 100644--- a/server/internal/service/task.go+++ b/server/internal/service/task.go@@ -724,8 +724,35 @@ func (s *TaskService) EnqueueQuickCreateTask(ctx context.Context, workspaceID, rreturn task, nil}+// ErrChatTaskAgentArchived signals that EnqueueChatTask refused to+// queue work because the destination agent has been archived. This+// is a productizable state — surface it to the user as "this agent+// has been archived" rather than retrying.+var ErrChatTaskAgentArchived = errors.New("chat task: agent archived")++// ErrChatTaskAgentNoRuntime signals that EnqueueChatTask refused to+// queue work because the agent has never been associated with a+// runtime (agent.runtime_id IS NULL). This is the "agent has no+// daemon configured" case — productizable as "agent offline".+//+// IMPORTANT: this is NOT the same as "the daemon is currently+// disconnected". When agent.runtime_id IS set, EnqueueChatTask+// enqueues the task and the daemon claims it on next online; that+// path returns a task row, not this error.+var ErrChatTaskAgentNoRuntime = errors.New("chat task: agent has no runtime")+// EnqueueChatTask creates a queued task for a chat session.// Unlike issue tasks, chat tasks have no issue_id.+//+// Errors split into two layers:+//+// - Productizable rejections (agent archived, no runtime) return+// the sentinel errors above. Callers (e.g. the Lark dispatcher)+// can errors.Is them to decide a user-visible outcome.+//+// - Infrastructure failures (DB load / insert errors) are wrapped+// as ordinary errors. The caller should treat them as retryable+// or page-worthy, NOT as user-facing state.func (s *TaskService) EnqueueChatTask(ctx context.Context, chatSession db.ChatSession) (db.AgentTaskQueue, error) {agent, err := s.Queries.GetAgent(ctx, chatSession.AgentID)if err != nil {@@ -733,10 +760,10 @@ func (s *TaskService) EnqueueChatTask(ctx context.Context, chatSession db.ChatSereturn db.AgentTaskQueue{}, fmt.Errorf("load agent: %w", err)}if agent.ArchivedAt.Valid {- return db.AgentTaskQueue{}, fmt.Errorf("agent is archived")+ return db.AgentTaskQueue{}, ErrChatTaskAgentArchived}if !agent.RuntimeID.Valid {- return db.AgentTaskQueue{}, fmt.Errorf("agent has no runtime")+ return db.AgentTaskQueue{}, ErrChatTaskAgentNoRuntime}task, err := s.Queries.CreateChatTask(ctx, db.CreateChatTaskParams{diff --git a/server/internal/util/secretbox/secretbox.go b/server/internal/util/secretbox/secretbox.gonew file mode 100644index 0000000000..2f98f2989d--- /dev/null+++ b/server/internal/util/secretbox/secretbox.go@@ -0,0 +1,107 @@+// Package secretbox provides authenticated symmetric encryption for+// secrets stored at rest — primarily Lark `app_secret` and any future+// per-tenant secret column that must not appear in plaintext in a DB+// dump (MUL-2671 §4.4).+//+// Construction: AES-256-GCM with a per-message 12-byte random nonce+// prepended to the ciphertext. GCM provides both confidentiality and+// integrity, so a tampered row decrypts to an error instead of+// silently garbled plaintext.+//+// Key: 32 bytes. Loaded from an env var as base64 (LoadKey). Rotation+// is not supported in this iteration — once we have multiple keys in+// production we add a single-byte prefix to ciphertext for key id;+// today every ciphertext is keyed by the one current master key.+package secretbox++import (+ "crypto/aes"+ "crypto/cipher"+ "crypto/rand"+ "encoding/base64"+ "errors"+ "fmt"+ "os"+)++// KeySize is the required master-key length in bytes (AES-256).+const KeySize = 32++// ErrInvalidKey is returned by New when the key length is not KeySize.+var ErrInvalidKey = errors.New("secretbox: key must be 32 bytes")++// ErrCiphertextTooShort is returned when the input to Open is smaller+// than the nonce + GCM tag overhead.+var ErrCiphertextTooShort = errors.New("secretbox: ciphertext too short")++// Box encrypts and decrypts byte slices using a fixed master key.+// Box instances are safe for concurrent use after construction —+// cipher.AEAD itself is goroutine-safe.+type Box struct {+ aead cipher.AEAD+}++// New constructs a Box bound to the given 32-byte master key. Callers+// should hold the returned *Box for the process lifetime; constructing+// it per request needlessly re-derives the AES round keys.+func New(key []byte) (*Box, error) {+ if len(key) != KeySize {+ return nil, ErrInvalidKey+ }+ block, err := aes.NewCipher(key)+ if err != nil {+ return nil, fmt.Errorf("secretbox: aes.NewCipher: %w", err)+ }+ aead, err := cipher.NewGCM(block)+ if err != nil {+ return nil, fmt.Errorf("secretbox: cipher.NewGCM: %w", err)+ }+ return &Box{aead: aead}, nil+}++// Seal encrypts plaintext and returns nonce || ciphertext || tag. The+// nonce is randomly generated per call; callers must NOT cache or+// reuse the output as if it were deterministic (e.g. don't index a+// secret by its ciphertext — two Seal calls on the same plaintext+// produce different bytes).+func (b *Box) Seal(plaintext []byte) ([]byte, error) {+ nonce := make([]byte, b.aead.NonceSize())+ if _, err := rand.Read(nonce); err != nil {+ return nil, fmt.Errorf("secretbox: read nonce: %w", err)+ }+ // b.aead.Seal appends ciphertext+tag to its first argument; we+ // pass `nonce` so the caller receives a single contiguous slice+ // laid out as nonce||ciphertext||tag, which Open then splits.+ return b.aead.Seal(nonce, nonce, plaintext, nil), nil+}++// Open reverses Seal. Returns ErrCiphertextTooShort or an+// authentication error (from GCM) if the input is malformed or+// tampered.+func (b *Box) Open(sealed []byte) ([]byte, error) {+ ns := b.aead.NonceSize()+ if len(sealed) < ns+b.aead.Overhead() {+ return nil, ErrCiphertextTooShort+ }+ nonce, ciphertext := sealed[:ns], sealed[ns:]+ return b.aead.Open(nil, nonce, ciphertext, nil)+}++// LoadKey reads a base64-encoded 32-byte key from the given env var.+// Returns ErrInvalidKey if the decoded length is not KeySize. Empty+// env values are treated as "not configured" and surface as a clear+// error rather than silently using a zero key.+func LoadKey(envVar string) ([]byte, error) {+ raw := os.Getenv(envVar)+ if raw == "" {+ return nil, fmt.Errorf("secretbox: %s is not set", envVar)+ }+ key, err := base64.StdEncoding.DecodeString(raw)+ if err != nil {+ return nil, fmt.Errorf("secretbox: %s is not valid base64: %w", envVar, err)+ }+ if len(key) != KeySize {+ return nil, fmt.Errorf("secretbox: %s decodes to %d bytes, expected %d", envVar, len(key), KeySize)+ }+ return key, nil+}diff --git a/server/internal/util/secretbox/secretbox_test.go b/server/internal/util/secretbox/secretbox_test.gonew file mode 100644index 0000000000..0cf2272693--- /dev/null+++ b/server/internal/util/secretbox/secretbox_test.go@@ -0,0 +1,108 @@+package secretbox++import (+ "bytes"+ "crypto/rand"+ "encoding/base64"+ "testing"+)++func mustNewBox(t *testing.T) *Box {+ t.Helper()+ key := make([]byte, KeySize)+ if _, err := rand.Read(key); err != nil {+ t.Fatalf("rand: %v", err)+ }+ box, err := New(key)+ if err != nil {+ t.Fatalf("New: %v", err)+ }+ return box+}++func TestRoundTrip(t *testing.T) {+ box := mustNewBox(t)+ plaintext := []byte("lark app_secret 12345")+ sealed, err := box.Seal(plaintext)+ if err != nil {+ t.Fatalf("Seal: %v", err)+ }+ opened, err := box.Open(sealed)+ if err != nil {+ t.Fatalf("Open: %v", err)+ }+ if !bytes.Equal(opened, plaintext) {+ t.Fatalf("round trip mismatch: got %q want %q", opened, plaintext)+ }+}++func TestSealIsNonDeterministic(t *testing.T) {+ // Same plaintext + same box → different ciphertext on each Seal,+ // because the nonce is random. This prevents content-fingerprinting+ // (e.g. confirming that two installations share the same secret).+ box := mustNewBox(t)+ plaintext := []byte("repeat")+ a, _ := box.Seal(plaintext)+ b, _ := box.Seal(plaintext)+ if bytes.Equal(a, b) {+ t.Fatalf("expected non-deterministic Seal, got identical ciphertexts")+ }+}++func TestOpenRejectsTampered(t *testing.T) {+ box := mustNewBox(t)+ sealed, _ := box.Seal([]byte("important"))+ // Flip a bit in the ciphertext portion (skip nonce).+ tampered := append([]byte(nil), sealed...)+ tampered[len(tampered)-1] ^= 0x01+ if _, err := box.Open(tampered); err == nil {+ t.Fatalf("expected auth failure on tampered ciphertext")+ }+}++func TestOpenRejectsShort(t *testing.T) {+ box := mustNewBox(t)+ if _, err := box.Open([]byte("short")); err != ErrCiphertextTooShort {+ t.Fatalf("expected ErrCiphertextTooShort, got %v", err)+ }+}++func TestNewRejectsBadKey(t *testing.T) {+ if _, err := New(make([]byte, 16)); err != ErrInvalidKey {+ t.Fatalf("expected ErrInvalidKey for 16-byte key, got %v", err)+ }+}++func TestLoadKey(t *testing.T) {+ const envVar = "TEST_SECRETBOX_KEY"+ t.Run("missing", func(t *testing.T) {+ t.Setenv(envVar, "")+ if _, err := LoadKey(envVar); err == nil {+ t.Fatal("expected error on missing env var")+ }+ })+ t.Run("bad base64", func(t *testing.T) {+ t.Setenv(envVar, "not!base64!")+ if _, err := LoadKey(envVar); err == nil {+ t.Fatal("expected error on invalid base64")+ }+ })+ t.Run("wrong length", func(t *testing.T) {+ t.Setenv(envVar, base64.StdEncoding.EncodeToString([]byte("too short")))+ if _, err := LoadKey(envVar); err == nil {+ t.Fatal("expected error on short key")+ }+ })+ t.Run("happy path", func(t *testing.T) {+ key := make([]byte, KeySize)+ _, _ = rand.Read(key)+ t.Setenv(envVar, base64.StdEncoding.EncodeToString(key))+ got, err := LoadKey(envVar)+ if err != nil {+ t.Fatalf("LoadKey: %v", err)+ }+ if !bytes.Equal(got, key) {+ t.Fatalf("LoadKey returned wrong bytes")+ }+ })+}diff --git a/server/migrations/109_lark_integration.down.sql b/server/migrations/109_lark_integration.down.sqlnew file mode 100644index 0000000000..84bcfb6947--- /dev/null+++ b/server/migrations/109_lark_integration.down.sql@@ -0,0 +1,7 @@+DROP TABLE IF EXISTS lark_binding_token;+DROP TABLE IF EXISTS lark_outbound_card_message;+DROP TABLE IF EXISTS lark_inbound_audit;+DROP TABLE IF EXISTS lark_inbound_message_dedup;+DROP TABLE IF EXISTS lark_chat_session_binding;+DROP TABLE IF EXISTS lark_user_binding;+DROP TABLE IF EXISTS lark_installation;diff --git a/server/migrations/109_lark_integration.up.sql b/server/migrations/109_lark_integration.up.sqlnew file mode 100644index 0000000000..571aa7d5f3--- /dev/null+++ b/server/migrations/109_lark_integration.up.sql@@ -0,0 +1,270 @@+-- Lark (飞书) Bot integration: per-agent PersonalAgent installations,+-- user/chat bindings, inbound dedup + drop audit, outbound card mapping,+-- and short-lived member binding tokens.+--+-- Scope notes (mirror description §4.8 boundaries):+-- * `chat_session` is reused as-is — Lark routes through a separate+-- `lark_chat_session_binding` rather than adding a `metadata` JSONB+-- column to chat_session.+-- * Outbound card-message mapping is *task/message* scoped, not session+-- scoped, so multiple runs on the same chat_session don't stomp each+-- other's cards.+-- * `app_secret` is stored encrypted; the application layer encrypts+-- before writing and decrypts on read (no DB-side decryption helper).+-- * `lark_inbound_audit` is the only writable surface for events that+-- fail identity check or group-mention filter — it stores routing /+-- identity / drop_reason / timestamp ONLY, never message body.++-- =====================+-- lark_installation+-- =====================+-- One row per (workspace, agent) — each Multica Agent owns at most one+-- Lark PersonalAgent Bot. `app_secret_encrypted` is the ciphertext+-- produced by the application-layer secretbox helper; never plaintext.+CREATE TABLE lark_installation (+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),+ workspace_id UUID NOT NULL REFERENCES workspace(id) ON DELETE CASCADE,+ agent_id UUID NOT NULL REFERENCES agent(id) ON DELETE CASCADE,+ app_id TEXT NOT NULL,+ -- Ciphertext of the Lark app secret. Application-layer secretbox.+ -- DB never sees plaintext; a dump leaks ciphertext only.+ app_secret_encrypted BYTEA NOT NULL,+ tenant_key TEXT,+ bot_open_id TEXT NOT NULL,+ installer_user_id UUID NOT NULL REFERENCES "user"(id) ON DELETE RESTRICT,+ status TEXT NOT NULL DEFAULT 'active'+ CHECK (status IN ('active', 'revoked')),+ -- WS ownership lease: only the server instance holding a non-expired+ -- lease may keep the WebSocket open for this installation. Used to+ -- prevent duplicate consumption when multiple replicas are deployed.+ ws_lease_token TEXT,+ ws_lease_expires_at TIMESTAMPTZ,+ installed_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ UNIQUE (workspace_id, agent_id),+ UNIQUE (app_id),+ -- Composite key target for the composite FK on lark_user_binding+ -- (installation_id, workspace_id) — guarantees a binding's workspace+ -- always matches the workspace of its installation.+ UNIQUE (id, workspace_id)+);++CREATE INDEX idx_lark_installation_workspace ON lark_installation(workspace_id);+CREATE INDEX idx_lark_installation_agent ON lark_installation(agent_id);+-- Used by the lease scanner to find leases due for renewal / takeover.+CREATE INDEX idx_lark_installation_lease ON lark_installation(ws_lease_expires_at)+ WHERE status = 'active';++-- =====================+-- lark_user_binding+-- =====================+-- Maps a Lark `open_id` to a Multica user, per-installation. open_id is+-- per-app, so the same Lark user has different open_ids across different+-- installations — the binding is therefore keyed on (installation, open_id),+-- not open_id alone. `union_id` is captured opportunistically for future+-- cross-installation identity merging (Phase 2) but is not authoritative+-- in MVP.+--+-- Two structural invariants protect §4.3's "unbound or non-workspace+-- members never leak content into chat_session" rule from drifting if+-- the application layer regresses:+--+-- 1. The composite FK on (installation_id, workspace_id) targets+-- lark_installation(id, workspace_id), so a binding row cannot+-- claim a workspace different from its installation's workspace.+--+-- 2. The composite FK on (workspace_id, multica_user_id) targets+-- member(workspace_id, user_id) with ON DELETE CASCADE, so when a+-- Multica user is removed from the workspace the stale Lark+-- binding is removed in the same transaction. There is no path+-- where lark_user_binding can outlive workspace membership.+CREATE TABLE lark_user_binding (+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),+ workspace_id UUID NOT NULL,+ multica_user_id UUID NOT NULL,+ installation_id UUID NOT NULL,+ lark_open_id TEXT NOT NULL,+ union_id TEXT,+ bound_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ UNIQUE (installation_id, lark_open_id),+ -- Installation ↔ workspace integrity. Composite FK guarantees the+ -- binding's workspace_id matches the installation's workspace_id.+ CONSTRAINT lark_user_binding_installation_fk+ FOREIGN KEY (installation_id, workspace_id)+ REFERENCES lark_installation(id, workspace_id)+ ON DELETE CASCADE,+ -- Workspace membership integrity. Composite FK guarantees the+ -- (workspace_id, multica_user_id) pair still exists in member; when+ -- the user is removed from the workspace, the binding cascades away.+ CONSTRAINT lark_user_binding_member_fk+ FOREIGN KEY (workspace_id, multica_user_id)+ REFERENCES member(workspace_id, user_id)+ ON DELETE CASCADE+);++CREATE INDEX idx_lark_user_binding_user+ ON lark_user_binding(multica_user_id, workspace_id);+CREATE INDEX idx_lark_user_binding_workspace_open+ ON lark_user_binding(workspace_id, lark_open_id);++-- =====================+-- lark_chat_session_binding+-- =====================+-- One Lark chat (`chat_id`) ↔ one Multica `chat_session`. The Lark side+-- doesn't distinguish p2p vs group at the routing layer, but we keep+-- `lark_chat_type` for product behavior (group sessions only ingest+-- @-Bot / reply-Bot messages; p2p ingests everything).+CREATE TABLE lark_chat_session_binding (+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),+ chat_session_id UUID NOT NULL REFERENCES chat_session(id) ON DELETE CASCADE,+ installation_id UUID NOT NULL REFERENCES lark_installation(id) ON DELETE CASCADE,+ lark_chat_id TEXT NOT NULL,+ lark_chat_type TEXT NOT NULL+ CHECK (lark_chat_type IN ('p2p', 'group')),+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ UNIQUE (installation_id, lark_chat_id),+ UNIQUE (chat_session_id)+);++CREATE INDEX idx_lark_chat_session_binding_session+ ON lark_chat_session_binding(chat_session_id);++-- =====================+-- lark_inbound_message_dedup+-- =====================+-- Idempotency for Lark inbound events. WebSocket reconnects can replay+-- recently-delivered events; we keep 24h of message_ids to short-circuit+-- replays before any business logic runs. A periodic vacuum job (separate+-- migration / cron) trims rows older than ~24h.+--+-- Two-phase semantics with owner fencing (see ClaimLarkInboundDedup /+-- MarkLarkInboundDedupProcessed / ReleaseLarkInboundDedup in+-- queries/lark.sql):+--+-- processed_at IS NULL → in-flight claim. The dispatcher holds a+-- row but has not yet reached a durable outcome (audit-drop row+-- persisted, OR chat_message + session touched). If the worker+-- crashes here the row is re-claimable after the staleness TTL,+-- so a replay does not get permanently swallowed.+--+-- processed_at IS NOT NULL → terminal. The message_id has reached a+-- durable outcome; future replays are dropped as duplicates+-- regardless of staleness.+--+-- claim_token → owner fence. Each Claim mints a fresh UUID; Mark and+-- Release only succeed when the supplied token matches the row's+-- current value. This closes two windows that staleness-TTL alone+-- leaves open:+--+-- (1) Stale-reclaim race. Worker A claims with token T_A; it+-- runs slowly past the 60s TTL but is still alive. Worker B+-- re-takes the claim with a new token T_B. A reaches the+-- chat_message+Mark transaction; the token-fenced Mark+-- returns zero rows because the live token is now T_B, so+-- A's tx ROLLS BACK and no second chat_message lands. B's+-- run is the sole writer.+--+-- (2) Mark window. The dispatcher Marks the dedup row INSIDE+-- the same tx as the chat_message + session touch, so the+-- durable write and the Mark commit (or roll back)+-- atomically. There is no "committed chat_message but not+-- yet Marked" window for a crash or retry to exploit.+--+-- Together: "first-attempt EnsureChatSession or AppendUserMessage+-- infra error → second attempt gets duplicate-dropped" is prevented by+-- Release (claim is dropped on rollback); "stale reclaim while+-- original worker is alive" and "process crash between durable commit+-- and Mark" are prevented by owner fencing + same-tx Mark.+CREATE TABLE lark_inbound_message_dedup (+ message_id TEXT PRIMARY KEY,+ received_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ processed_at TIMESTAMPTZ,+ claim_token UUID NOT NULL DEFAULT gen_random_uuid()+);++CREATE INDEX idx_lark_inbound_dedup_received+ ON lark_inbound_message_dedup(received_at);++-- =====================+-- lark_inbound_audit+-- =====================+-- Non-content audit log for events that DID arrive but were intentionally+-- dropped (group message without @, unbound user, non-workspace member,+-- duplicate, etc.). NEVER stores message body — only routing + identity+-- + drop_reason + timestamp. Used for ops debugging, abuse detection, and+-- proving the "non-bound users cannot leak content into chat_session"+-- invariant from §4.7 of the design.+CREATE TABLE lark_inbound_audit (+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),+ installation_id UUID REFERENCES lark_installation(id) ON DELETE SET NULL,+ lark_chat_id TEXT,+ event_type TEXT NOT NULL,+ lark_event_id TEXT,+ lark_message_id TEXT,+ -- Open-ended TEXT (not an enum) so new drop reasons can be added in+ -- application code without a schema migration. Convention: snake_case.+ -- Known values today: unbound_user, non_workspace_member,+ -- not_addressed_in_group, duplicate, revoked_installation, invalid_event.+ drop_reason TEXT NOT NULL,+ received_at TIMESTAMPTZ NOT NULL DEFAULT now()+);++CREATE INDEX idx_lark_inbound_audit_installation+ ON lark_inbound_audit(installation_id, received_at DESC);+CREATE INDEX idx_lark_inbound_audit_reason+ ON lark_inbound_audit(drop_reason, received_at DESC);++-- =====================+-- lark_outbound_card_message+-- =====================+-- Maps a Multica task (or session bootstrap "thinking…" card) to the+-- Lark interactive card message we're patching. Per-task, not per-session+-- — a chat_session can host many runs and a session-level field would+-- create card aliasing bugs. `task_id` may be NULL for the initial+-- bootstrap card before a task is created; the partial UNIQUE index+-- guarantees task↔card is 1:1 once a task exists.+CREATE TABLE lark_outbound_card_message (+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),+ chat_session_id UUID NOT NULL REFERENCES chat_session(id) ON DELETE CASCADE,+ task_id UUID REFERENCES agent_task_queue(id) ON DELETE SET NULL,+ lark_chat_id TEXT NOT NULL,+ lark_card_message_id TEXT NOT NULL,+ status TEXT NOT NULL DEFAULT 'pending'+ CHECK (status IN ('pending', 'streaming', 'final', 'error')),+ last_patched_at TIMESTAMPTZ,+ created_at TIMESTAMPTZ NOT NULL DEFAULT now()+);++CREATE UNIQUE INDEX idx_lark_outbound_card_task+ ON lark_outbound_card_message(task_id)+ WHERE task_id IS NOT NULL;+CREATE INDEX idx_lark_outbound_card_session+ ON lark_outbound_card_message(chat_session_id, created_at DESC);++-- =====================+-- lark_binding_token+-- =====================+-- Short-lived (≤ 15 min), single-use token for the "you're not bound yet,+-- click here" flow that links a Lark `open_id` to a Multica user. The+-- hash (not the raw token) is stored so a DB leak doesn't grant binding+-- capability. Replay is blocked by `consumed_at IS NOT NULL`.+CREATE TABLE lark_binding_token (+ token_hash TEXT PRIMARY KEY,+ workspace_id UUID NOT NULL REFERENCES workspace(id) ON DELETE CASCADE,+ installation_id UUID NOT NULL REFERENCES lark_installation(id) ON DELETE CASCADE,+ lark_open_id TEXT NOT NULL,+ expires_at TIMESTAMPTZ NOT NULL,+ consumed_at TIMESTAMPTZ,+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ -- Belt-and-braces with the application-layer cap (lark.BindingTokenTTL+ -- = 15 minutes). The CHECK refuses any row whose lifetime exceeds the+ -- product cap, so a misconfigured caller or a hand-inserted SQL row+ -- cannot quietly mint a longer-lived binding token. Keep this value+ -- in sync with lark.BindingTokenTTL.+ CONSTRAINT lark_binding_token_ttl_cap+ CHECK (expires_at <= created_at + INTERVAL '15 minutes')+);++CREATE INDEX idx_lark_binding_token_installation+ ON lark_binding_token(installation_id, expires_at);diff --git a/server/migrations/111_issue_origin_lark_chat.down.sql b/server/migrations/111_issue_origin_lark_chat.down.sqlnew file mode 100644index 0000000000..ef59cf7718--- /dev/null+++ b/server/migrations/111_issue_origin_lark_chat.down.sql@@ -0,0 +1,8 @@+-- Revert to the pre-Lark issue_origin_type_check list. Any existing rows+-- with origin_type='lark_chat' would violate the rolled-back constraint;+-- the down migration assumes the operator has already deleted or relabeled+-- those rows. We keep this strict (no DROP NOT VALID dance) to preserve+-- the schema invariant downstream code relies on.+ALTER TABLE issue DROP CONSTRAINT IF EXISTS issue_origin_type_check;+ALTER TABLE issue ADD CONSTRAINT issue_origin_type_check+ CHECK (origin_type IN ('autopilot', 'quick_create'));diff --git a/server/migrations/111_issue_origin_lark_chat.up.sql b/server/migrations/111_issue_origin_lark_chat.up.sqlnew file mode 100644index 0000000000..4d560ba7c0--- /dev/null+++ b/server/migrations/111_issue_origin_lark_chat.up.sql@@ -0,0 +1,10 @@+-- Extend issue.origin_type to allow the Lark `/issue` command path to stamp+-- issues with origin_type='lark_chat' + origin_id=<chat_session.id>. Without+-- this entry in the CHECK list, every /issue dispatch on Lark fails with+-- SQLSTATE 23514 and the connector exits with infra error — see Bohan's+-- live-env repro in MUL-2671 review where one /issue in a row tripped the+-- check three times, each crash dragging the WS connector down + Lark+-- retrying the same event into the next crash.+ALTER TABLE issue DROP CONSTRAINT IF EXISTS issue_origin_type_check;+ALTER TABLE issue ADD CONSTRAINT issue_origin_type_check+ CHECK (origin_type IN ('autopilot', 'quick_create', 'lark_chat'));diff --git a/server/migrations/112_lark_installation_bot_union_id.down.sql b/server/migrations/112_lark_installation_bot_union_id.down.sqlnew file mode 100644index 0000000000..a82c6b1002--- /dev/null+++ b/server/migrations/112_lark_installation_bot_union_id.down.sql@@ -0,0 +1,6 @@+-- Drop bot_union_id. Application code is expected to be rolled back to a+-- version that does not read this column before the down migration is+-- applied — there is no transitional period in which the runtime expects+-- the column and the schema lacks it.+ALTER TABLE lark_installation+ DROP COLUMN IF EXISTS bot_union_id;diff --git a/server/migrations/112_lark_installation_bot_union_id.up.sql b/server/migrations/112_lark_installation_bot_union_id.up.sqlnew file mode 100644index 0000000000..edff8f0ce4--- /dev/null+++ b/server/migrations/112_lark_installation_bot_union_id.up.sql@@ -0,0 +1,21 @@+-- Add bot_union_id to lark_installation so the WS inbound decoder can+-- match group-chat @-mentions against the bot's stable cross-app identity+-- (union_id) instead of the per-app open_id.+--+-- Why this column exists: Bohan's live-env triage on MUL-2671 showed that+-- in a group chat where two Multica-installed bots are bound, Lark's+-- `mentions[].id.open_id` field on `im.message.receive_v1` is structurally+-- inverse to /open-apis/bot/v3/info's `bot.open_id`. The bot whose WS+-- receives the event sees its OWN payload-form open_id when the OTHER+-- bot was @-mentioned, and a different open_id when itself was the+-- target. The only payload field consistent across both perspectives is+-- `union_id` — see the diag-log capture in MUL-2671 review.+--+-- Nullable on purpose: installations created before this migration won't+-- have a union_id until the registration service backfills them (next+-- run of GetBotInfo or a one-shot operator backfill). The decoder+-- short-circuits to its previous open_id-only match when bot_union_id IS+-- NULL, so pre-migration rows continue to work as they did before. New+-- installs populate it during finishSuccess.+ALTER TABLE lark_installation+ ADD COLUMN bot_union_id TEXT;diff --git a/server/migrations/113_lark_inbound_dedup_per_installation.down.sql b/server/migrations/113_lark_inbound_dedup_per_installation.down.sqlnew file mode 100644index 0000000000..1f996971b8--- /dev/null+++ b/server/migrations/113_lark_inbound_dedup_per_installation.down.sql@@ -0,0 +1,14 @@+-- Revert to message_id-only PK. The down migration drops the table and+-- recreates it without the installation_id column; transient cache rows+-- are dropped.+DROP TABLE IF EXISTS lark_inbound_message_dedup;++CREATE TABLE lark_inbound_message_dedup (+ message_id TEXT PRIMARY KEY,+ received_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ processed_at TIMESTAMPTZ,+ claim_token UUID NOT NULL DEFAULT gen_random_uuid()+);++CREATE INDEX idx_lark_inbound_dedup_received+ ON lark_inbound_message_dedup(received_at);diff --git a/server/migrations/113_lark_inbound_dedup_per_installation.up.sql b/server/migrations/113_lark_inbound_dedup_per_installation.up.sqlnew file mode 100644index 0000000000..26bf612fe3--- /dev/null+++ b/server/migrations/113_lark_inbound_dedup_per_installation.up.sql@@ -0,0 +1,28 @@+-- Re-scope lark_inbound_message_dedup to (installation_id, message_id).+--+-- The original schema keyed dedup on `message_id` alone. In a Lark group+-- chat where the same workspace has multiple Multica bots installed, each+-- bot's WS receives the SAME `message_id` from Lark — and both supervisors+-- legitimately need to claim, evaluate AddressedToBot from their own+-- bot's perspective, and either ingest (if @-ed) or drop as+-- not_addressed_in_group (if the OTHER bot was @-ed). With a single+-- shared dedup row, whichever WS claims first locks the row, and the+-- bot that was actually @-ed gets dropped as `duplicate` before it can+-- evaluate the mention. See MUL-2671 multi-bot routing triage.+--+-- The dedup table is short-lived (24h TTL via PurgeLarkInboundDedup);+-- existing rows can be dropped on the way through — there's no+-- meaningful product state in them, only transient idempotency cache.+DROP TABLE IF EXISTS lark_inbound_message_dedup;++CREATE TABLE lark_inbound_message_dedup (+ installation_id UUID NOT NULL REFERENCES lark_installation(id) ON DELETE CASCADE,+ message_id TEXT NOT NULL,+ received_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ processed_at TIMESTAMPTZ,+ claim_token UUID NOT NULL DEFAULT gen_random_uuid(),+ PRIMARY KEY (installation_id, message_id)+);++CREATE INDEX idx_lark_inbound_dedup_received+ ON lark_inbound_message_dedup(received_at);diff --git a/server/pkg/db/generated/chat.sql.go b/server/pkg/db/generated/chat.sql.goindex 38aa1f404b..aeee774d0d 100644--- a/server/pkg/db/generated/chat.sql.go+++ b/server/pkg/db/generated/chat.sql.go@@ -273,6 +273,34 @@ func (q *Queries) GetLastChatTaskSession(ctx context.Context, chatSessionID pgtyreturn i, err}+const getMostRecentUserChatMessage = `-- name: GetMostRecentUserChatMessage :one+SELECT id, chat_session_id, role, content, task_id, created_at, failure_reason, elapsed_ms FROM chat_message+WHERE chat_session_id = $1 AND role = 'user'+ORDER BY created_at DESC+LIMIT 1+`++// Returns the most recent role='user' message in a session. Used by the+// Lark `/issue` command parser: when the user types `/issue` with no+// title, the spec falls back to "use the previous user message as the+// title". Bot replies (role='assistant') are excluded — only human+// input qualifies as a fallback title source.+func (q *Queries) GetMostRecentUserChatMessage(ctx context.Context, chatSessionID pgtype.UUID) (ChatMessage, error) {+ row := q.db.QueryRow(ctx, getMostRecentUserChatMessage, chatSessionID)+ var i ChatMessage+ err := row.Scan(+ &i.ID,+ &i.ChatSessionID,+ &i.Role,+ &i.Content,+ &i.TaskID,+ &i.CreatedAt,+ &i.FailureReason,+ &i.ElapsedMs,+ )+ return i, err+}+const getPendingChatTask = `-- name: GetPendingChatTask :oneSELECT id, status, created_at FROM agent_task_queueWHERE chat_session_id = $1 AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory')diff --git a/server/pkg/db/generated/lark.sql.go b/server/pkg/db/generated/lark.sql.gonew file mode 100644index 0000000000..0581a634a5--- /dev/null+++ b/server/pkg/db/generated/lark.sql.go@@ -0,0 +1,1109 @@+// Code generated by sqlc. DO NOT EDIT.+// versions:+// sqlc v1.31.1+// source: lark.sql++package db++import (+ "context"++ "github.com/jackc/pgx/v5/pgtype"+)++const acquireLarkWSLease = `-- name: AcquireLarkWSLease :one+UPDATE lark_installation+SET ws_lease_token = $1,+ ws_lease_expires_at = $2,+ updated_at = now()+WHERE id = $3+ AND status = 'active'+ AND (+ ws_lease_token IS NULL+ OR ws_lease_expires_at < now()+ OR ws_lease_token = $1+ )+RETURNING id, workspace_id, agent_id, app_id, app_secret_encrypted, tenant_key, bot_open_id, bot_union_id, installer_user_id, status, ws_lease_token, ws_lease_expires_at, installed_at, created_at, updated_at+`++type AcquireLarkWSLeaseParams struct {+ NewToken pgtype.Text `json:"new_token"`+ NewExpiresAt pgtype.Timestamptz `json:"new_expires_at"`+ ID pgtype.UUID `json:"id"`+}++// Atomically claims the WebSocket lease for an installation. The CAS+// predicate accepts the lease when (a) no current holder exists, (b)+// the holder's lease has expired, or (c) the holder is us (renewal).+// Returns the row when the lease was successfully claimed; returns no+// rows when another live holder still owns it.+func (q *Queries) AcquireLarkWSLease(ctx context.Context, arg AcquireLarkWSLeaseParams) (LarkInstallation, error) {+ row := q.db.QueryRow(ctx, acquireLarkWSLease, arg.NewToken, arg.NewExpiresAt, arg.ID)+ var i LarkInstallation+ err := row.Scan(+ &i.ID,+ &i.WorkspaceID,+ &i.AgentID,+ &i.AppID,+ &i.AppSecretEncrypted,+ &i.TenantKey,+ &i.BotOpenID,+ &i.BotUnionID,+ &i.InstallerUserID,+ &i.Status,+ &i.WsLeaseToken,+ &i.WsLeaseExpiresAt,+ &i.InstalledAt,+ &i.CreatedAt,+ &i.UpdatedAt,+ )+ return i, err+}++const claimLarkInboundDedup = `-- name: ClaimLarkInboundDedup :one++INSERT INTO lark_inbound_message_dedup (installation_id, message_id, claim_token)+VALUES ($1, $2, gen_random_uuid())+ON CONFLICT (installation_id, message_id) DO UPDATE+ SET received_at = now(),+ claim_token = gen_random_uuid()+ WHERE lark_inbound_message_dedup.processed_at IS NULL+ AND lark_inbound_message_dedup.received_at < now() - INTERVAL '60 seconds'+RETURNING installation_id, message_id, received_at, processed_at, claim_token+`++type ClaimLarkInboundDedupParams struct {+ InstallationID pgtype.UUID `json:"installation_id"`+ MessageID string `json:"message_id"`+}++// =====================+// lark_inbound_message_dedup+// =====================+// The two-phase idempotency gate. The dispatcher uses this BEFORE+// group filter / identity check / chat-session lookup so a WebSocket+// reconnect that replays an event cannot re-trigger binding prompts,+// re-write drop audit rows, or re-touch chat_session.+//+// Returns the row when a claim is acquired:+// - newly inserted (first delivery of this message_id), OR+// - re-taken from a stale in-flight claim. A claim is stale when+// processed_at IS NULL AND received_at is older than 60 seconds —+// the previous worker crashed or lost its DB connection between+// claim and finalize, and a retry should be allowed to proceed.+//+// Returns NO rows (pgx.ErrNoRows) when the claim cannot be acquired:+// - the row exists with processed_at IS NOT NULL (terminal: prior+// attempt reached a durable outcome), OR+// - the row exists with processed_at IS NULL AND received_at within+// the last 60 seconds (another worker is actively processing).+//+// Owner fencing: every successful Claim mints a fresh UUID into+// `claim_token`. The Caller passes that token to MarkLarkInbound-+// DedupProcessed / ReleaseLarkInboundDedup; mismatched tokens are+// ignored. A stale-reclaim that re-takes the row ROTATES the token,+// so the previous (slow but still alive) worker can no longer Mark+// the row — its same-tx Mark returns zero rows and the chat_message+// write rolls back. See lark_inbound_message_dedup table comment.+//+// The dispatcher MUST follow up every successful claim with exactly one+// of MarkLarkInboundDedupProcessed (durable outcome) or+// ReleaseLarkInboundDedup (infra failure before durable outcome),+// supplying the returned claim_token. Otherwise the row sits as an+// in-flight claim and the next replay attempt must wait for the+// staleness TTL.+func (q *Queries) ClaimLarkInboundDedup(ctx context.Context, arg ClaimLarkInboundDedupParams) (LarkInboundMessageDedup, error) {+ row := q.db.QueryRow(ctx, claimLarkInboundDedup, arg.InstallationID, arg.MessageID)+ var i LarkInboundMessageDedup+ err := row.Scan(+ &i.InstallationID,+ &i.MessageID,+ &i.ReceivedAt,+ &i.ProcessedAt,+ &i.ClaimToken,+ )+ return i, err+}++const consumeLarkBindingToken = `-- name: ConsumeLarkBindingToken :one+UPDATE lark_binding_token+SET consumed_at = now()+WHERE token_hash = $1+ AND consumed_at IS NULL+ AND expires_at > now()+RETURNING token_hash, workspace_id, installation_id, lark_open_id, expires_at, consumed_at, created_at+`++// Atomic redemption. Returns the row only if (a) the hash exists, (b)+// it has not been consumed, and (c) it has not expired. The UPDATE ++// RETURNING pattern guarantees that two simultaneous redemptions of+// the same token cannot both succeed — exactly one row update wins,+// the other sees zero rows.+func (q *Queries) ConsumeLarkBindingToken(ctx context.Context, tokenHash string) (LarkBindingToken, error) {+ row := q.db.QueryRow(ctx, consumeLarkBindingToken, tokenHash)+ var i LarkBindingToken+ err := row.Scan(+ &i.TokenHash,+ &i.WorkspaceID,+ &i.InstallationID,+ &i.LarkOpenID,+ &i.ExpiresAt,+ &i.ConsumedAt,+ &i.CreatedAt,+ )+ return i, err+}++const createLarkBindingToken = `-- name: CreateLarkBindingToken :one++INSERT INTO lark_binding_token (+ token_hash, workspace_id, installation_id, lark_open_id, expires_at+) VALUES (+ $1, $2, $3, $4, $5+)+RETURNING token_hash, workspace_id, installation_id, lark_open_id, expires_at, consumed_at, created_at+`++type CreateLarkBindingTokenParams struct {+ TokenHash string `json:"token_hash"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ InstallationID pgtype.UUID `json:"installation_id"`+ LarkOpenID string `json:"lark_open_id"`+ ExpiresAt pgtype.Timestamptz `json:"expires_at"`+}++// =====================+// lark_binding_token+// =====================+// Mints a single-use binding token for an unbound Lark user. The TTL+// cap (`expires_at <= created_at + INTERVAL '15 minutes'`) is enforced+// by the DB CHECK on the table, in lockstep with lark.BindingTokenTTL.+// We store the HASH, not the raw token; the raw value is returned to+// the caller exactly once (in the URL it embeds in the Bot's reply+// card) and never persisted server-side.+func (q *Queries) CreateLarkBindingToken(ctx context.Context, arg CreateLarkBindingTokenParams) (LarkBindingToken, error) {+ row := q.db.QueryRow(ctx, createLarkBindingToken,+ arg.TokenHash,+ arg.WorkspaceID,+ arg.InstallationID,+ arg.LarkOpenID,+ arg.ExpiresAt,+ )+ var i LarkBindingToken+ err := row.Scan(+ &i.TokenHash,+ &i.WorkspaceID,+ &i.InstallationID,+ &i.LarkOpenID,+ &i.ExpiresAt,+ &i.ConsumedAt,+ &i.CreatedAt,+ )+ return i, err+}++const createLarkChatSessionBinding = `-- name: CreateLarkChatSessionBinding :one++INSERT INTO lark_chat_session_binding (+ chat_session_id, installation_id, lark_chat_id, lark_chat_type+) VALUES (+ $1, $2, $3, $4+)+RETURNING id, chat_session_id, installation_id, lark_chat_id, lark_chat_type, created_at+`++type CreateLarkChatSessionBindingParams struct {+ ChatSessionID pgtype.UUID `json:"chat_session_id"`+ InstallationID pgtype.UUID `json:"installation_id"`+ LarkChatID string `json:"lark_chat_id"`+ LarkChatType string `json:"lark_chat_type"`+}++// =====================+// lark_chat_session_binding+// =====================+func (q *Queries) CreateLarkChatSessionBinding(ctx context.Context, arg CreateLarkChatSessionBindingParams) (LarkChatSessionBinding, error) {+ row := q.db.QueryRow(ctx, createLarkChatSessionBinding,+ arg.ChatSessionID,+ arg.InstallationID,+ arg.LarkChatID,+ arg.LarkChatType,+ )+ var i LarkChatSessionBinding+ err := row.Scan(+ &i.ID,+ &i.ChatSessionID,+ &i.InstallationID,+ &i.LarkChatID,+ &i.LarkChatType,+ &i.CreatedAt,+ )+ return i, err+}++const createLarkInstallation = `-- name: CreateLarkInstallation :one+++INSERT INTO lark_installation (+ workspace_id, agent_id, app_id, app_secret_encrypted,+ tenant_key, bot_open_id, bot_union_id, installer_user_id+) VALUES (+ $1, $2, $3, $4, $7, $5, $8, $6+)+RETURNING id, workspace_id, agent_id, app_id, app_secret_encrypted, tenant_key, bot_open_id, bot_union_id, installer_user_id, status, ws_lease_token, ws_lease_expires_at, installed_at, created_at, updated_at+`++type CreateLarkInstallationParams struct {+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ AgentID pgtype.UUID `json:"agent_id"`+ AppID string `json:"app_id"`+ AppSecretEncrypted []byte `json:"app_secret_encrypted"`+ BotOpenID string `json:"bot_open_id"`+ InstallerUserID pgtype.UUID `json:"installer_user_id"`+ TenantKey pgtype.Text `json:"tenant_key"`+ BotUnionID pgtype.Text `json:"bot_union_id"`+}++// Lark (飞书) Bot integration queries. The migration that defines these+// tables lives at server/migrations/109_lark_integration.up.sql; the+// architectural boundaries the package enforces on top of them are+// documented in server/internal/integrations/lark/doc.go.+//+// Scoping convention: every public-facing read goes through a+// workspace-scoped variant where one exists. The lookups that take only+// a UUID PK (e.g. GetLarkInstallation) are reserved for internal trusted+// callers (the WS lease scanner, the inbound dispatcher after identity+// resolution); HTTP handlers should prefer the *InWorkspace forms.+// =====================+// lark_installation+// =====================+// Used by the OAuth callback. `app_secret_encrypted` is the ciphertext+// produced by internal/util/secretbox — never plaintext. The+// (workspace_id, agent_id) UNIQUE constraint enforces the spec rule+// "one Multica Agent ↔ one Lark Bot"; re-installing on the same agent+// goes through UpsertLarkInstallation instead.+func (q *Queries) CreateLarkInstallation(ctx context.Context, arg CreateLarkInstallationParams) (LarkInstallation, error) {+ row := q.db.QueryRow(ctx, createLarkInstallation,+ arg.WorkspaceID,+ arg.AgentID,+ arg.AppID,+ arg.AppSecretEncrypted,+ arg.BotOpenID,+ arg.InstallerUserID,+ arg.TenantKey,+ arg.BotUnionID,+ )+ var i LarkInstallation+ err := row.Scan(+ &i.ID,+ &i.WorkspaceID,+ &i.AgentID,+ &i.AppID,+ &i.AppSecretEncrypted,+ &i.TenantKey,+ &i.BotOpenID,+ &i.BotUnionID,+ &i.InstallerUserID,+ &i.Status,+ &i.WsLeaseToken,+ &i.WsLeaseExpiresAt,+ &i.InstalledAt,+ &i.CreatedAt,+ &i.UpdatedAt,+ )+ return i, err+}++const createLarkOutboundCardMessage = `-- name: CreateLarkOutboundCardMessage :one++INSERT INTO lark_outbound_card_message (+ chat_session_id, task_id, lark_chat_id, lark_card_message_id, status+) VALUES (+ $1, $5, $2, $3, $4+)+RETURNING id, chat_session_id, task_id, lark_chat_id, lark_card_message_id, status, last_patched_at, created_at+`++type CreateLarkOutboundCardMessageParams struct {+ ChatSessionID pgtype.UUID `json:"chat_session_id"`+ LarkChatID string `json:"lark_chat_id"`+ LarkCardMessageID string `json:"lark_card_message_id"`+ Status string `json:"status"`+ TaskID pgtype.UUID `json:"task_id"`+}++// =====================+// lark_outbound_card_message+// =====================+func (q *Queries) CreateLarkOutboundCardMessage(ctx context.Context, arg CreateLarkOutboundCardMessageParams) (LarkOutboundCardMessage, error) {+ row := q.db.QueryRow(ctx, createLarkOutboundCardMessage,+ arg.ChatSessionID,+ arg.LarkChatID,+ arg.LarkCardMessageID,+ arg.Status,+ arg.TaskID,+ )+ var i LarkOutboundCardMessage+ err := row.Scan(+ &i.ID,+ &i.ChatSessionID,+ &i.TaskID,+ &i.LarkChatID,+ &i.LarkCardMessageID,+ &i.Status,+ &i.LastPatchedAt,+ &i.CreatedAt,+ )+ return i, err+}++const createLarkUserBinding = `-- name: CreateLarkUserBinding :one++INSERT INTO lark_user_binding (+ workspace_id, multica_user_id, installation_id, lark_open_id, union_id+) VALUES (+ $1, $2, $3, $4, $5+)+ON CONFLICT (installation_id, lark_open_id) DO UPDATE SET+ union_id = COALESCE(EXCLUDED.union_id, lark_user_binding.union_id),+ bound_at = now()+WHERE lark_user_binding.multica_user_id = EXCLUDED.multica_user_id+RETURNING id, workspace_id, multica_user_id, installation_id, lark_open_id, union_id, bound_at+`++type CreateLarkUserBindingParams struct {+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ MulticaUserID pgtype.UUID `json:"multica_user_id"`+ InstallationID pgtype.UUID `json:"installation_id"`+ LarkOpenID string `json:"lark_open_id"`+ UnionID pgtype.Text `json:"union_id"`+}++// =====================+// lark_user_binding+// =====================+// Records that a Lark open_id (per-installation) maps to a Multica+// user.+//+// Two structural guarantees:+// 1. The composite FK to member(workspace_id, user_id) makes this+// statement fail when the redeemer is not (or no longer) a+// workspace member — that is §4.3 of the design.+// 2. ON CONFLICT DO UPDATE is gated on `multica_user_id` matching+// the existing binding, so a second redeemer holding their own+// valid binding token CANNOT silently steal an already-bound+// open_id. If the conflict row points at a different user, the+// UPDATE is skipped and the statement returns ZERO rows — the+// caller (lark.BindingTokenService.RedeemAndBind) translates+// that into ErrBindingAlreadyAssigned.+//+// The same-user case still updates metadata (union_id refresh,+// bound_at bump) so an idempotent re-bind by the original user+// continues to work; only a cross-user re-assignment is rejected.+// True account changes must go through an explicit unbind flow, not+// through a binding token.+func (q *Queries) CreateLarkUserBinding(ctx context.Context, arg CreateLarkUserBindingParams) (LarkUserBinding, error) {+ row := q.db.QueryRow(ctx, createLarkUserBinding,+ arg.WorkspaceID,+ arg.MulticaUserID,+ arg.InstallationID,+ arg.LarkOpenID,+ arg.UnionID,+ )+ var i LarkUserBinding+ err := row.Scan(+ &i.ID,+ &i.WorkspaceID,+ &i.MulticaUserID,+ &i.InstallationID,+ &i.LarkOpenID,+ &i.UnionID,+ &i.BoundAt,+ )+ return i, err+}++const deleteLarkUserBinding = `-- name: DeleteLarkUserBinding :exec+DELETE FROM lark_user_binding WHERE id = $1+`++func (q *Queries) DeleteLarkUserBinding(ctx context.Context, id pgtype.UUID) error {+ _, err := q.db.Exec(ctx, deleteLarkUserBinding, id)+ return err+}++const getLarkChatSessionBinding = `-- name: GetLarkChatSessionBinding :one+SELECT id, chat_session_id, installation_id, lark_chat_id, lark_chat_type, created_at FROM lark_chat_session_binding+WHERE installation_id = $1 AND lark_chat_id = $2+`++type GetLarkChatSessionBindingParams struct {+ InstallationID pgtype.UUID `json:"installation_id"`+ LarkChatID string `json:"lark_chat_id"`+}++// Lookup-by-Lark-chat path. Used by the inbound dispatcher to find the+// existing chat_session before deciding whether to create one. The+// UNIQUE (installation_id, lark_chat_id) constraint means at most one+// row matches.+func (q *Queries) GetLarkChatSessionBinding(ctx context.Context, arg GetLarkChatSessionBindingParams) (LarkChatSessionBinding, error) {+ row := q.db.QueryRow(ctx, getLarkChatSessionBinding, arg.InstallationID, arg.LarkChatID)+ var i LarkChatSessionBinding+ err := row.Scan(+ &i.ID,+ &i.ChatSessionID,+ &i.InstallationID,+ &i.LarkChatID,+ &i.LarkChatType,+ &i.CreatedAt,+ )+ return i, err+}++const getLarkChatSessionBindingBySession = `-- name: GetLarkChatSessionBindingBySession :one+SELECT id, chat_session_id, installation_id, lark_chat_id, lark_chat_type, created_at FROM lark_chat_session_binding+WHERE chat_session_id = $1+`++// Reverse lookup: given a chat_session_id, find its Lark binding. Used+// by the outbound card patcher to know which (installation, chat_id)+// to PATCH when an agent emits a stream event for this session.+func (q *Queries) GetLarkChatSessionBindingBySession(ctx context.Context, chatSessionID pgtype.UUID) (LarkChatSessionBinding, error) {+ row := q.db.QueryRow(ctx, getLarkChatSessionBindingBySession, chatSessionID)+ var i LarkChatSessionBinding+ err := row.Scan(+ &i.ID,+ &i.ChatSessionID,+ &i.InstallationID,+ &i.LarkChatID,+ &i.LarkChatType,+ &i.CreatedAt,+ )+ return i, err+}++const getLarkInstallation = `-- name: GetLarkInstallation :one+SELECT id, workspace_id, agent_id, app_id, app_secret_encrypted, tenant_key, bot_open_id, bot_union_id, installer_user_id, status, ws_lease_token, ws_lease_expires_at, installed_at, created_at, updated_at FROM lark_installation WHERE id = $1+`++func (q *Queries) GetLarkInstallation(ctx context.Context, id pgtype.UUID) (LarkInstallation, error) {+ row := q.db.QueryRow(ctx, getLarkInstallation, id)+ var i LarkInstallation+ err := row.Scan(+ &i.ID,+ &i.WorkspaceID,+ &i.AgentID,+ &i.AppID,+ &i.AppSecretEncrypted,+ &i.TenantKey,+ &i.BotOpenID,+ &i.BotUnionID,+ &i.InstallerUserID,+ &i.Status,+ &i.WsLeaseToken,+ &i.WsLeaseExpiresAt,+ &i.InstalledAt,+ &i.CreatedAt,+ &i.UpdatedAt,+ )+ return i, err+}++const getLarkInstallationByAgent = `-- name: GetLarkInstallationByAgent :one+SELECT id, workspace_id, agent_id, app_id, app_secret_encrypted, tenant_key, bot_open_id, bot_union_id, installer_user_id, status, ws_lease_token, ws_lease_expires_at, installed_at, created_at, updated_at FROM lark_installation+WHERE workspace_id = $1 AND agent_id = $2+`++type GetLarkInstallationByAgentParams struct {+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ AgentID pgtype.UUID `json:"agent_id"`+}++func (q *Queries) GetLarkInstallationByAgent(ctx context.Context, arg GetLarkInstallationByAgentParams) (LarkInstallation, error) {+ row := q.db.QueryRow(ctx, getLarkInstallationByAgent, arg.WorkspaceID, arg.AgentID)+ var i LarkInstallation+ err := row.Scan(+ &i.ID,+ &i.WorkspaceID,+ &i.AgentID,+ &i.AppID,+ &i.AppSecretEncrypted,+ &i.TenantKey,+ &i.BotOpenID,+ &i.BotUnionID,+ &i.InstallerUserID,+ &i.Status,+ &i.WsLeaseToken,+ &i.WsLeaseExpiresAt,+ &i.InstalledAt,+ &i.CreatedAt,+ &i.UpdatedAt,+ )+ return i, err+}++const getLarkInstallationByAppID = `-- name: GetLarkInstallationByAppID :one+SELECT id, workspace_id, agent_id, app_id, app_secret_encrypted, tenant_key, bot_open_id, bot_union_id, installer_user_id, status, ws_lease_token, ws_lease_expires_at, installed_at, created_at, updated_at FROM lark_installation WHERE app_id = $1+`++// Used by the OAuth callback to detect re-install vs first-install,+// and by the inbound dispatcher to route an event payload (which only+// carries app_id) to its installation row.+func (q *Queries) GetLarkInstallationByAppID(ctx context.Context, appID string) (LarkInstallation, error) {+ row := q.db.QueryRow(ctx, getLarkInstallationByAppID, appID)+ var i LarkInstallation+ err := row.Scan(+ &i.ID,+ &i.WorkspaceID,+ &i.AgentID,+ &i.AppID,+ &i.AppSecretEncrypted,+ &i.TenantKey,+ &i.BotOpenID,+ &i.BotUnionID,+ &i.InstallerUserID,+ &i.Status,+ &i.WsLeaseToken,+ &i.WsLeaseExpiresAt,+ &i.InstalledAt,+ &i.CreatedAt,+ &i.UpdatedAt,+ )+ return i, err+}++const getLarkInstallationInWorkspace = `-- name: GetLarkInstallationInWorkspace :one+SELECT id, workspace_id, agent_id, app_id, app_secret_encrypted, tenant_key, bot_open_id, bot_union_id, installer_user_id, status, ws_lease_token, ws_lease_expires_at, installed_at, created_at, updated_at FROM lark_installation+WHERE id = $1 AND workspace_id = $2+`++type GetLarkInstallationInWorkspaceParams struct {+ ID pgtype.UUID `json:"id"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+}++func (q *Queries) GetLarkInstallationInWorkspace(ctx context.Context, arg GetLarkInstallationInWorkspaceParams) (LarkInstallation, error) {+ row := q.db.QueryRow(ctx, getLarkInstallationInWorkspace, arg.ID, arg.WorkspaceID)+ var i LarkInstallation+ err := row.Scan(+ &i.ID,+ &i.WorkspaceID,+ &i.AgentID,+ &i.AppID,+ &i.AppSecretEncrypted,+ &i.TenantKey,+ &i.BotOpenID,+ &i.BotUnionID,+ &i.InstallerUserID,+ &i.Status,+ &i.WsLeaseToken,+ &i.WsLeaseExpiresAt,+ &i.InstalledAt,+ &i.CreatedAt,+ &i.UpdatedAt,+ )+ return i, err+}++const getLarkOutboundCardByTask = `-- name: GetLarkOutboundCardByTask :one+SELECT id, chat_session_id, task_id, lark_chat_id, lark_card_message_id, status, last_patched_at, created_at FROM lark_outbound_card_message+WHERE task_id = $1+`++// Most card patches arrive keyed by task_id (we're streaming an agent+// run's output). The partial unique index on (task_id) WHERE task_id IS+// NOT NULL guarantees this returns at most one row.+func (q *Queries) GetLarkOutboundCardByTask(ctx context.Context, taskID pgtype.UUID) (LarkOutboundCardMessage, error) {+ row := q.db.QueryRow(ctx, getLarkOutboundCardByTask, taskID)+ var i LarkOutboundCardMessage+ err := row.Scan(+ &i.ID,+ &i.ChatSessionID,+ &i.TaskID,+ &i.LarkChatID,+ &i.LarkCardMessageID,+ &i.Status,+ &i.LastPatchedAt,+ &i.CreatedAt,+ )+ return i, err+}++const getLarkUserBindingByOpenID = `-- name: GetLarkUserBindingByOpenID :one+SELECT id, workspace_id, multica_user_id, installation_id, lark_open_id, union_id, bound_at FROM lark_user_binding+WHERE installation_id = $1 AND lark_open_id = $2+`++type GetLarkUserBindingByOpenIDParams struct {+ InstallationID pgtype.UUID `json:"installation_id"`+ LarkOpenID string `json:"lark_open_id"`+}++// The inbound identity check. A row here means: this open_id maps to a+// Multica user who IS currently a workspace member (the composite FK+// cascades the binding away when membership is revoked, so a row's+// existence is itself the membership proof).+func (q *Queries) GetLarkUserBindingByOpenID(ctx context.Context, arg GetLarkUserBindingByOpenIDParams) (LarkUserBinding, error) {+ row := q.db.QueryRow(ctx, getLarkUserBindingByOpenID, arg.InstallationID, arg.LarkOpenID)+ var i LarkUserBinding+ err := row.Scan(+ &i.ID,+ &i.WorkspaceID,+ &i.MulticaUserID,+ &i.InstallationID,+ &i.LarkOpenID,+ &i.UnionID,+ &i.BoundAt,+ )+ return i, err+}++const listActiveLarkInstallations = `-- name: ListActiveLarkInstallations :many+SELECT id, workspace_id, agent_id, app_id, app_secret_encrypted, tenant_key, bot_open_id, bot_union_id, installer_user_id, status, ws_lease_token, ws_lease_expires_at, installed_at, created_at, updated_at FROM lark_installation+WHERE status = 'active'+ORDER BY created_at ASC+`++// Boot path for the WebSocket hub: enumerate every active installation+// so the hub can claim leases and open long connections. Excludes+// revoked rows — their WS should already be torn down.+func (q *Queries) ListActiveLarkInstallations(ctx context.Context) ([]LarkInstallation, error) {+ rows, err := q.db.Query(ctx, listActiveLarkInstallations)+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ items := []LarkInstallation{}+ for rows.Next() {+ var i LarkInstallation+ if err := rows.Scan(+ &i.ID,+ &i.WorkspaceID,+ &i.AgentID,+ &i.AppID,+ &i.AppSecretEncrypted,+ &i.TenantKey,+ &i.BotOpenID,+ &i.BotUnionID,+ &i.InstallerUserID,+ &i.Status,+ &i.WsLeaseToken,+ &i.WsLeaseExpiresAt,+ &i.InstalledAt,+ &i.CreatedAt,+ &i.UpdatedAt,+ ); err != nil {+ return nil, err+ }+ items = append(items, i)+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }+ return items, nil+}++const listLarkInboundAuditByInstallation = `-- name: ListLarkInboundAuditByInstallation :many+SELECT id, installation_id, lark_chat_id, event_type, lark_event_id, lark_message_id, drop_reason, received_at FROM lark_inbound_audit+WHERE installation_id = $1+ORDER BY received_at DESC+LIMIT $2 OFFSET $3+`++type ListLarkInboundAuditByInstallationParams struct {+ InstallationID pgtype.UUID `json:"installation_id"`+ Limit int32 `json:"limit"`+ Offset int32 `json:"offset"`+}++// Ops debugging view; paged via the (installation_id, received_at) idx.+func (q *Queries) ListLarkInboundAuditByInstallation(ctx context.Context, arg ListLarkInboundAuditByInstallationParams) ([]LarkInboundAudit, error) {+ rows, err := q.db.Query(ctx, listLarkInboundAuditByInstallation, arg.InstallationID, arg.Limit, arg.Offset)+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ items := []LarkInboundAudit{}+ for rows.Next() {+ var i LarkInboundAudit+ if err := rows.Scan(+ &i.ID,+ &i.InstallationID,+ &i.LarkChatID,+ &i.EventType,+ &i.LarkEventID,+ &i.LarkMessageID,+ &i.DropReason,+ &i.ReceivedAt,+ ); err != nil {+ return nil, err+ }+ items = append(items, i)+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }+ return items, nil+}++const listLarkInstallationsByWorkspace = `-- name: ListLarkInstallationsByWorkspace :many+SELECT id, workspace_id, agent_id, app_id, app_secret_encrypted, tenant_key, bot_open_id, bot_union_id, installer_user_id, status, ws_lease_token, ws_lease_expires_at, installed_at, created_at, updated_at FROM lark_installation+WHERE workspace_id = $1+ORDER BY created_at ASC+`++func (q *Queries) ListLarkInstallationsByWorkspace(ctx context.Context, workspaceID pgtype.UUID) ([]LarkInstallation, error) {+ rows, err := q.db.Query(ctx, listLarkInstallationsByWorkspace, workspaceID)+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ items := []LarkInstallation{}+ for rows.Next() {+ var i LarkInstallation+ if err := rows.Scan(+ &i.ID,+ &i.WorkspaceID,+ &i.AgentID,+ &i.AppID,+ &i.AppSecretEncrypted,+ &i.TenantKey,+ &i.BotOpenID,+ &i.BotUnionID,+ &i.InstallerUserID,+ &i.Status,+ &i.WsLeaseToken,+ &i.WsLeaseExpiresAt,+ &i.InstalledAt,+ &i.CreatedAt,+ &i.UpdatedAt,+ ); err != nil {+ return nil, err+ }+ items = append(items, i)+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }+ return items, nil+}++const listLarkUserBindingsByInstallation = `-- name: ListLarkUserBindingsByInstallation :many+SELECT id, workspace_id, multica_user_id, installation_id, lark_open_id, union_id, bound_at FROM lark_user_binding+WHERE installation_id = $1+ORDER BY bound_at DESC+`++func (q *Queries) ListLarkUserBindingsByInstallation(ctx context.Context, installationID pgtype.UUID) ([]LarkUserBinding, error) {+ rows, err := q.db.Query(ctx, listLarkUserBindingsByInstallation, installationID)+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ items := []LarkUserBinding{}+ for rows.Next() {+ var i LarkUserBinding+ if err := rows.Scan(+ &i.ID,+ &i.WorkspaceID,+ &i.MulticaUserID,+ &i.InstallationID,+ &i.LarkOpenID,+ &i.UnionID,+ &i.BoundAt,+ ); err != nil {+ return nil, err+ }+ items = append(items, i)+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }+ return items, nil+}++const markLarkInboundDedupProcessed = `-- name: MarkLarkInboundDedupProcessed :execrows+UPDATE lark_inbound_message_dedup+SET processed_at = now()+WHERE installation_id = $1+ AND message_id = $2+ AND claim_token = $3+ AND processed_at IS NULL+`++type MarkLarkInboundDedupProcessedParams struct {+ InstallationID pgtype.UUID `json:"installation_id"`+ MessageID string `json:"message_id"`+ ClaimToken pgtype.UUID `json:"claim_token"`+}++// Locks in a claim as permanently processed. Called by the dispatcher+// after a durable outcome has been reached:+// - a drop audit row was persisted (group filter / unbound user /+// revoked / invalid event), OR+// - chat_message + chat_session.updated_at were committed (ingest+// path, including ingest paths that subsequently fail at issue+// creation / task enqueue — the user-visible message is already in+// the session).+//+// For the chat_message ingest path the dispatcher invokes this query+// INSIDE the chat_message+session transaction (via qtx), so the+// durable write and the Mark commit atomically. A token mismatch+// (another worker has re-claimed the row in the meantime) returns+// zero rows; the caller treats that as a lost claim and rolls back the+// in-tx invocation, so no second chat_message is written.+//+// Guarded by processed_at IS NULL so a successful Mark is itself+// idempotent: replaying it cannot resurrect a row that was already+// terminal.+func (q *Queries) MarkLarkInboundDedupProcessed(ctx context.Context, arg MarkLarkInboundDedupProcessedParams) (int64, error) {+ result, err := q.db.Exec(ctx, markLarkInboundDedupProcessed, arg.InstallationID, arg.MessageID, arg.ClaimToken)+ if err != nil {+ return 0, err+ }+ return result.RowsAffected(), nil+}++const purgeExpiredLarkBindingTokens = `-- name: PurgeExpiredLarkBindingTokens :exec+DELETE FROM lark_binding_token+WHERE expires_at < $1+`++// Tokens are tiny but unbounded over time. The same vacuum cron that+// handles dedup can sweep these too.+func (q *Queries) PurgeExpiredLarkBindingTokens(ctx context.Context, expiresAt pgtype.Timestamptz) error {+ _, err := q.db.Exec(ctx, purgeExpiredLarkBindingTokens, expiresAt)+ return err+}++const purgeLarkInboundDedup = `-- name: PurgeLarkInboundDedup :exec+DELETE FROM lark_inbound_message_dedup+WHERE received_at < $1+`++// Removes dedup rows older than the supplied cutoff. The vacuum job+// (separate cron) calls this with cutoff = now() - INTERVAL '24h'.+// Sweeps both processed and (very old) abandoned in-flight rows.+func (q *Queries) PurgeLarkInboundDedup(ctx context.Context, receivedAt pgtype.Timestamptz) error {+ _, err := q.db.Exec(ctx, purgeLarkInboundDedup, receivedAt)+ return err+}++const recordLarkInboundDrop = `-- name: RecordLarkInboundDrop :exec++INSERT INTO lark_inbound_audit (+ installation_id, lark_chat_id, event_type,+ lark_event_id, lark_message_id, drop_reason+) VALUES (+ $3,+ $4,+ $1,+ $5,+ $6,+ $2+)+`++type RecordLarkInboundDropParams struct {+ EventType string `json:"event_type"`+ DropReason string `json:"drop_reason"`+ InstallationID pgtype.UUID `json:"installation_id"`+ LarkChatID pgtype.Text `json:"lark_chat_id"`+ LarkEventID pgtype.Text `json:"lark_event_id"`+ LarkMessageID pgtype.Text `json:"lark_message_id"`+}++// =====================+// lark_inbound_audit+// =====================+// The ONLY write path for events that fail identity check or the+// group-mention filter. Deliberately accepts no body column — the+// AuditLogger interface in internal/integrations/lark mirrors that+// shape so a caller cannot accidentally hand a body to this row.+func (q *Queries) RecordLarkInboundDrop(ctx context.Context, arg RecordLarkInboundDropParams) error {+ _, err := q.db.Exec(ctx, recordLarkInboundDrop,+ arg.EventType,+ arg.DropReason,+ arg.InstallationID,+ arg.LarkChatID,+ arg.LarkEventID,+ arg.LarkMessageID,+ )+ return err+}++const releaseLarkInboundDedup = `-- name: ReleaseLarkInboundDedup :execrows+DELETE FROM lark_inbound_message_dedup+WHERE installation_id = $1+ AND message_id = $2+ AND claim_token = $3+ AND processed_at IS NULL+`++type ReleaseLarkInboundDedupParams struct {+ InstallationID pgtype.UUID `json:"installation_id"`+ MessageID string `json:"message_id"`+ ClaimToken pgtype.UUID `json:"claim_token"`+}++// Releases an in-flight claim. Called by the dispatcher when an infra+// error occurred BEFORE any durable side effect (e.g. EnsureChatSession+// or AppendUserMessage returned an error and its transaction rolled+// back). Deleting the row lets the WS adapter's retry re-acquire the+// claim immediately, instead of waiting for the 60-second staleness+// TTL. Guarded by processed_at IS NULL so an out-of-order Release+// cannot undo a Mark; guarded by claim_token so a slow-but-alive worker+// whose claim was reclaimed cannot delete the new holder's row.+func (q *Queries) ReleaseLarkInboundDedup(ctx context.Context, arg ReleaseLarkInboundDedupParams) (int64, error) {+ result, err := q.db.Exec(ctx, releaseLarkInboundDedup, arg.InstallationID, arg.MessageID, arg.ClaimToken)+ if err != nil {+ return 0, err+ }+ return result.RowsAffected(), nil+}++const releaseLarkWSLease = `-- name: ReleaseLarkWSLease :exec+UPDATE lark_installation+SET ws_lease_token = NULL,+ ws_lease_expires_at = NULL,+ updated_at = now()+WHERE id = $1+ AND ws_lease_token = $2+`++type ReleaseLarkWSLeaseParams struct {+ ID pgtype.UUID `json:"id"`+ CurrentToken pgtype.Text `json:"current_token"`+}++// Drops the lease iff we're still the holder. A racing acquirer that+// already took over will not have its lease cleared.+func (q *Queries) ReleaseLarkWSLease(ctx context.Context, arg ReleaseLarkWSLeaseParams) error {+ _, err := q.db.Exec(ctx, releaseLarkWSLease, arg.ID, arg.CurrentToken)+ return err+}++const setLarkInstallationStatus = `-- name: SetLarkInstallationStatus :exec+UPDATE lark_installation+SET status = $2, updated_at = now()+WHERE id = $1+`++type SetLarkInstallationStatusParams struct {+ ID pgtype.UUID `json:"id"`+ Status string `json:"status"`+}++func (q *Queries) SetLarkInstallationStatus(ctx context.Context, arg SetLarkInstallationStatusParams) error {+ _, err := q.db.Exec(ctx, setLarkInstallationStatus, arg.ID, arg.Status)+ return err+}++const setLarkInstallationBotUnionID = `-- name: SetLarkInstallationBotUnionID :exec+UPDATE lark_installation+SET bot_union_id = $2,+ updated_at = now()+WHERE id = $1+`++type SetLarkInstallationBotUnionIDParams struct {+ ID pgtype.UUID `json:"id"`+ BotUnionID pgtype.Text `json:"bot_union_id"`+}++// Operator-only backfill for installations created before the+// bot_union_id column existed (migration 112). Production reads do+// NOT use this — finishSuccess writes union_id during install, and+// the upsert path writes it on re-install. Kept as a focused single-+// column UPDATE so the backfill cannot accidentally overwrite app+// credentials, status, or lease state.+func (q *Queries) SetLarkInstallationBotUnionID(ctx context.Context, arg SetLarkInstallationBotUnionIDParams) error {+ _, err := q.db.Exec(ctx, setLarkInstallationBotUnionID, arg.ID, arg.BotUnionID)+ return err+}++const updateLarkOutboundCardStatus = `-- name: UpdateLarkOutboundCardStatus :exec+UPDATE lark_outbound_card_message+SET status = $2,+ last_patched_at = now()+WHERE id = $1+`++type UpdateLarkOutboundCardStatusParams struct {+ ID pgtype.UUID `json:"id"`+ Status string `json:"status"`+}++func (q *Queries) UpdateLarkOutboundCardStatus(ctx context.Context, arg UpdateLarkOutboundCardStatusParams) error {+ _, err := q.db.Exec(ctx, updateLarkOutboundCardStatus, arg.ID, arg.Status)+ return err+}++const upsertLarkInstallation = `-- name: UpsertLarkInstallation :one+INSERT INTO lark_installation (+ workspace_id, agent_id, app_id, app_secret_encrypted,+ tenant_key, bot_open_id, bot_union_id, installer_user_id+) VALUES (+ $1, $2, $3, $4, $7, $5, $8, $6+)+ON CONFLICT (workspace_id, agent_id) DO UPDATE SET+ app_id = EXCLUDED.app_id,+ app_secret_encrypted = EXCLUDED.app_secret_encrypted,+ tenant_key = EXCLUDED.tenant_key,+ bot_open_id = EXCLUDED.bot_open_id,+ bot_union_id = EXCLUDED.bot_union_id,+ installer_user_id = EXCLUDED.installer_user_id,+ status = 'active',+ installed_at = now(),+ updated_at = now()+RETURNING id, workspace_id, agent_id, app_id, app_secret_encrypted, tenant_key, bot_open_id, bot_union_id, installer_user_id, status, ws_lease_token, ws_lease_expires_at, installed_at, created_at, updated_at+`++type UpsertLarkInstallationParams struct {+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ AgentID pgtype.UUID `json:"agent_id"`+ AppID string `json:"app_id"`+ AppSecretEncrypted []byte `json:"app_secret_encrypted"`+ BotOpenID string `json:"bot_open_id"`+ InstallerUserID pgtype.UUID `json:"installer_user_id"`+ TenantKey pgtype.Text `json:"tenant_key"`+ BotUnionID pgtype.Text `json:"bot_union_id"`+}++// Re-install path: a user who already bound this agent to Lark scans+// the QR again (e.g. they rotated their Lark app secret, or revoked ++// reinstalled). We refresh the app credentials, bot identity, and+// installer attribution, and force status back to 'active'. The WS+// lease is intentionally NOT reset here — the inbound hub owns lease+// lifecycle.+func (q *Queries) UpsertLarkInstallation(ctx context.Context, arg UpsertLarkInstallationParams) (LarkInstallation, error) {+ row := q.db.QueryRow(ctx, upsertLarkInstallation,+ arg.WorkspaceID,+ arg.AgentID,+ arg.AppID,+ arg.AppSecretEncrypted,+ arg.BotOpenID,+ arg.InstallerUserID,+ arg.TenantKey,+ arg.BotUnionID,+ )+ var i LarkInstallation+ err := row.Scan(+ &i.ID,+ &i.WorkspaceID,+ &i.AgentID,+ &i.AppID,+ &i.AppSecretEncrypted,+ &i.TenantKey,+ &i.BotOpenID,+ &i.BotUnionID,+ &i.InstallerUserID,+ &i.Status,+ &i.WsLeaseToken,+ &i.WsLeaseExpiresAt,+ &i.InstalledAt,+ &i.CreatedAt,+ &i.UpdatedAt,+ )+ return i, err+}diff --git a/server/pkg/db/generated/models.go b/server/pkg/db/generated/models.goindex 05ba1727db..d213c531fa 100644--- a/server/pkg/db/generated/models.go+++ b/server/pkg/db/generated/models.go@@ -407,6 +407,83 @@ type IssueToLabel struct {LabelID pgtype.UUID `json:"label_id"`}+type LarkBindingToken struct {+ TokenHash string `json:"token_hash"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ InstallationID pgtype.UUID `json:"installation_id"`+ LarkOpenID string `json:"lark_open_id"`+ ExpiresAt pgtype.Timestamptz `json:"expires_at"`+ ConsumedAt pgtype.Timestamptz `json:"consumed_at"`+ CreatedAt pgtype.Timestamptz `json:"created_at"`+}++type LarkChatSessionBinding struct {+ ID pgtype.UUID `json:"id"`+ ChatSessionID pgtype.UUID `json:"chat_session_id"`+ InstallationID pgtype.UUID `json:"installation_id"`+ LarkChatID string `json:"lark_chat_id"`+ LarkChatType string `json:"lark_chat_type"`+ CreatedAt pgtype.Timestamptz `json:"created_at"`+}++type LarkInboundAudit struct {+ ID pgtype.UUID `json:"id"`+ InstallationID pgtype.UUID `json:"installation_id"`+ LarkChatID pgtype.Text `json:"lark_chat_id"`+ EventType string `json:"event_type"`+ LarkEventID pgtype.Text `json:"lark_event_id"`+ LarkMessageID pgtype.Text `json:"lark_message_id"`+ DropReason string `json:"drop_reason"`+ ReceivedAt pgtype.Timestamptz `json:"received_at"`+}++type LarkInboundMessageDedup struct {+ InstallationID pgtype.UUID `json:"installation_id"`+ MessageID string `json:"message_id"`+ ReceivedAt pgtype.Timestamptz `json:"received_at"`+ ProcessedAt pgtype.Timestamptz `json:"processed_at"`+ ClaimToken pgtype.UUID `json:"claim_token"`+}++type LarkInstallation struct {+ ID pgtype.UUID `json:"id"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ AgentID pgtype.UUID `json:"agent_id"`+ AppID string `json:"app_id"`+ AppSecretEncrypted []byte `json:"app_secret_encrypted"`+ TenantKey pgtype.Text `json:"tenant_key"`+ BotOpenID string `json:"bot_open_id"`+ BotUnionID pgtype.Text `json:"bot_union_id"`+ InstallerUserID pgtype.UUID `json:"installer_user_id"`+ Status string `json:"status"`+ WsLeaseToken pgtype.Text `json:"ws_lease_token"`+ WsLeaseExpiresAt pgtype.Timestamptz `json:"ws_lease_expires_at"`+ InstalledAt pgtype.Timestamptz `json:"installed_at"`+ CreatedAt pgtype.Timestamptz `json:"created_at"`+ UpdatedAt pgtype.Timestamptz `json:"updated_at"`+}++type LarkOutboundCardMessage struct {+ ID pgtype.UUID `json:"id"`+ ChatSessionID pgtype.UUID `json:"chat_session_id"`+ TaskID pgtype.UUID `json:"task_id"`+ LarkChatID string `json:"lark_chat_id"`+ LarkCardMessageID string `json:"lark_card_message_id"`+ Status string `json:"status"`+ LastPatchedAt pgtype.Timestamptz `json:"last_patched_at"`+ CreatedAt pgtype.Timestamptz `json:"created_at"`+}++type LarkUserBinding struct {+ ID pgtype.UUID `json:"id"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ MulticaUserID pgtype.UUID `json:"multica_user_id"`+ InstallationID pgtype.UUID `json:"installation_id"`+ LarkOpenID string `json:"lark_open_id"`+ UnionID pgtype.Text `json:"union_id"`+ BoundAt pgtype.Timestamptz `json:"bound_at"`+}+type Member struct {ID pgtype.UUID `json:"id"`WorkspaceID pgtype.UUID `json:"workspace_id"`diff --git a/server/pkg/db/queries/chat.sql b/server/pkg/db/queries/chat.sqlindex 75dcf82193..4df44f30ef 100644--- a/server/pkg/db/queries/chat.sql+++ b/server/pkg/db/queries/chat.sql@@ -158,3 +158,14 @@ WHERE id = $1;-- unread boundary stable across multiple incoming replies.UPDATE chat_session SET unread_since = now()WHERE id = $1 AND unread_since IS NULL;++-- name: GetMostRecentUserChatMessage :one+-- Returns the most recent role='user' message in a session. Used by the+-- Lark `/issue` command parser: when the user types `/issue` with no+-- title, the spec falls back to "use the previous user message as the+-- title". Bot replies (role='assistant') are excluded — only human+-- input qualifies as a fallback title source.+SELECT * FROM chat_message+WHERE chat_session_id = $1 AND role = 'user'+ORDER BY created_at DESC+LIMIT 1;diff --git a/server/pkg/db/queries/lark.sql b/server/pkg/db/queries/lark.sqlnew file mode 100644index 0000000000..144871ccc5--- /dev/null+++ b/server/pkg/db/queries/lark.sql@@ -0,0 +1,392 @@+-- Lark (飞书) Bot integration queries. The migration that defines these+-- tables lives at server/migrations/109_lark_integration.up.sql; the+-- architectural boundaries the package enforces on top of them are+-- documented in server/internal/integrations/lark/doc.go.+--+-- Scoping convention: every public-facing read goes through a+-- workspace-scoped variant where one exists. The lookups that take only+-- a UUID PK (e.g. GetLarkInstallation) are reserved for internal trusted+-- callers (the WS lease scanner, the inbound dispatcher after identity+-- resolution); HTTP handlers should prefer the *InWorkspace forms.++-- =====================+-- lark_installation+-- =====================++-- name: CreateLarkInstallation :one+-- Used by the OAuth callback. `app_secret_encrypted` is the ciphertext+-- produced by internal/util/secretbox — never plaintext. The+-- (workspace_id, agent_id) UNIQUE constraint enforces the spec rule+-- "one Multica Agent ↔ one Lark Bot"; re-installing on the same agent+-- goes through UpsertLarkInstallation instead.+INSERT INTO lark_installation (+ workspace_id, agent_id, app_id, app_secret_encrypted,+ tenant_key, bot_open_id, bot_union_id, installer_user_id+) VALUES (+ $1, $2, $3, $4, sqlc.narg('tenant_key'), $5, sqlc.narg('bot_union_id'), $6+)+RETURNING *;++-- name: UpsertLarkInstallation :one+-- Re-install path: a user who already bound this agent to Lark scans+-- the QR again (e.g. they rotated their Lark app secret, or revoked ++-- reinstalled). We refresh the app credentials, bot identity, and+-- installer attribution, and force status back to 'active'. The WS+-- lease is intentionally NOT reset here — the inbound hub owns lease+-- lifecycle.+INSERT INTO lark_installation (+ workspace_id, agent_id, app_id, app_secret_encrypted,+ tenant_key, bot_open_id, bot_union_id, installer_user_id+) VALUES (+ $1, $2, $3, $4, sqlc.narg('tenant_key'), $5, sqlc.narg('bot_union_id'), $6+)+ON CONFLICT (workspace_id, agent_id) DO UPDATE SET+ app_id = EXCLUDED.app_id,+ app_secret_encrypted = EXCLUDED.app_secret_encrypted,+ tenant_key = EXCLUDED.tenant_key,+ bot_open_id = EXCLUDED.bot_open_id,+ bot_union_id = EXCLUDED.bot_union_id,+ installer_user_id = EXCLUDED.installer_user_id,+ status = 'active',+ installed_at = now(),+ updated_at = now()+RETURNING *;++-- name: SetLarkInstallationBotUnionID :exec+-- Operator-only backfill for installations created before the+-- bot_union_id column existed (migration 112). Production reads do+-- NOT use this — finishSuccess writes union_id during install, and+-- the upsert path writes it on re-install. Kept as a focused single-+-- column UPDATE so the backfill cannot accidentally overwrite app+-- credentials, status, or lease state.+UPDATE lark_installation+SET bot_union_id = $2,+ updated_at = now()+WHERE id = $1;++-- name: GetLarkInstallation :one+SELECT * FROM lark_installation WHERE id = $1;++-- name: GetLarkInstallationInWorkspace :one+SELECT * FROM lark_installation+WHERE id = $1 AND workspace_id = $2;++-- name: GetLarkInstallationByAgent :one+SELECT * FROM lark_installation+WHERE workspace_id = $1 AND agent_id = $2;++-- name: GetLarkInstallationByAppID :one+-- Used by the OAuth callback to detect re-install vs first-install,+-- and by the inbound dispatcher to route an event payload (which only+-- carries app_id) to its installation row.+SELECT * FROM lark_installation WHERE app_id = $1;++-- name: ListLarkInstallationsByWorkspace :many+SELECT * FROM lark_installation+WHERE workspace_id = $1+ORDER BY created_at ASC;++-- name: ListActiveLarkInstallations :many+-- Boot path for the WebSocket hub: enumerate every active installation+-- so the hub can claim leases and open long connections. Excludes+-- revoked rows — their WS should already be torn down.+SELECT * FROM lark_installation+WHERE status = 'active'+ORDER BY created_at ASC;++-- name: SetLarkInstallationStatus :exec+UPDATE lark_installation+SET status = $2, updated_at = now()+WHERE id = $1;++-- name: AcquireLarkWSLease :one+-- Atomically claims the WebSocket lease for an installation. The CAS+-- predicate accepts the lease when (a) no current holder exists, (b)+-- the holder's lease has expired, or (c) the holder is us (renewal).+-- Returns the row when the lease was successfully claimed; returns no+-- rows when another live holder still owns it.+UPDATE lark_installation+SET ws_lease_token = sqlc.arg('new_token'),+ ws_lease_expires_at = sqlc.arg('new_expires_at'),+ updated_at = now()+WHERE id = sqlc.arg('id')+ AND status = 'active'+ AND (+ ws_lease_token IS NULL+ OR ws_lease_expires_at < now()+ OR ws_lease_token = sqlc.arg('new_token')+ )+RETURNING *;++-- name: ReleaseLarkWSLease :exec+-- Drops the lease iff we're still the holder. A racing acquirer that+-- already took over will not have its lease cleared.+UPDATE lark_installation+SET ws_lease_token = NULL,+ ws_lease_expires_at = NULL,+ updated_at = now()+WHERE id = $1+ AND ws_lease_token = sqlc.arg('current_token');++-- =====================+-- lark_user_binding+-- =====================++-- name: CreateLarkUserBinding :one+-- Records that a Lark open_id (per-installation) maps to a Multica+-- user.+--+-- Two structural guarantees:+-- 1. The composite FK to member(workspace_id, user_id) makes this+-- statement fail when the redeemer is not (or no longer) a+-- workspace member — that is §4.3 of the design.+-- 2. ON CONFLICT DO UPDATE is gated on `multica_user_id` matching+-- the existing binding, so a second redeemer holding their own+-- valid binding token CANNOT silently steal an already-bound+-- open_id. If the conflict row points at a different user, the+-- UPDATE is skipped and the statement returns ZERO rows — the+-- caller (lark.BindingTokenService.RedeemAndBind) translates+-- that into ErrBindingAlreadyAssigned.+--+-- The same-user case still updates metadata (union_id refresh,+-- bound_at bump) so an idempotent re-bind by the original user+-- continues to work; only a cross-user re-assignment is rejected.+-- True account changes must go through an explicit unbind flow, not+-- through a binding token.+INSERT INTO lark_user_binding (+ workspace_id, multica_user_id, installation_id, lark_open_id, union_id+) VALUES (+ $1, $2, $3, $4, sqlc.narg('union_id')+)+ON CONFLICT (installation_id, lark_open_id) DO UPDATE SET+ union_id = COALESCE(EXCLUDED.union_id, lark_user_binding.union_id),+ bound_at = now()+WHERE lark_user_binding.multica_user_id = EXCLUDED.multica_user_id+RETURNING *;++-- name: GetLarkUserBindingByOpenID :one+-- The inbound identity check. A row here means: this open_id maps to a+-- Multica user who IS currently a workspace member (the composite FK+-- cascades the binding away when membership is revoked, so a row's+-- existence is itself the membership proof).+SELECT * FROM lark_user_binding+WHERE installation_id = $1 AND lark_open_id = $2;++-- name: ListLarkUserBindingsByInstallation :many+SELECT * FROM lark_user_binding+WHERE installation_id = $1+ORDER BY bound_at DESC;++-- name: DeleteLarkUserBinding :exec+DELETE FROM lark_user_binding WHERE id = $1;++-- =====================+-- lark_chat_session_binding+-- =====================++-- name: CreateLarkChatSessionBinding :one+INSERT INTO lark_chat_session_binding (+ chat_session_id, installation_id, lark_chat_id, lark_chat_type+) VALUES (+ $1, $2, $3, $4+)+RETURNING *;++-- name: GetLarkChatSessionBinding :one+-- Lookup-by-Lark-chat path. Used by the inbound dispatcher to find the+-- existing chat_session before deciding whether to create one. The+-- UNIQUE (installation_id, lark_chat_id) constraint means at most one+-- row matches.+SELECT * FROM lark_chat_session_binding+WHERE installation_id = $1 AND lark_chat_id = $2;++-- name: GetLarkChatSessionBindingBySession :one+-- Reverse lookup: given a chat_session_id, find its Lark binding. Used+-- by the outbound card patcher to know which (installation, chat_id)+-- to PATCH when an agent emits a stream event for this session.+SELECT * FROM lark_chat_session_binding+WHERE chat_session_id = $1;++-- =====================+-- lark_inbound_message_dedup+-- =====================++-- name: ClaimLarkInboundDedup :one+-- The two-phase idempotency gate. The dispatcher uses this BEFORE+-- group filter / identity check / chat-session lookup so a WebSocket+-- reconnect that replays an event cannot re-trigger binding prompts,+-- re-write drop audit rows, or re-touch chat_session.+--+-- Returns the row when a claim is acquired:+-- - newly inserted (first delivery of this message_id), OR+-- - re-taken from a stale in-flight claim. A claim is stale when+-- processed_at IS NULL AND received_at is older than 60 seconds —+-- the previous worker crashed or lost its DB connection between+-- claim and finalize, and a retry should be allowed to proceed.+--+-- Returns NO rows (pgx.ErrNoRows) when the claim cannot be acquired:+-- - the row exists with processed_at IS NOT NULL (terminal: prior+-- attempt reached a durable outcome), OR+-- - the row exists with processed_at IS NULL AND received_at within+-- the last 60 seconds (another worker is actively processing).+--+-- Owner fencing: every successful Claim mints a fresh UUID into+-- `claim_token`. The Caller passes that token to MarkLarkInbound-+-- DedupProcessed / ReleaseLarkInboundDedup; mismatched tokens are+-- ignored. A stale-reclaim that re-takes the row ROTATES the token,+-- so the previous (slow but still alive) worker can no longer Mark+-- the row — its same-tx Mark returns zero rows and the chat_message+-- write rolls back. See lark_inbound_message_dedup table comment.+--+-- The dispatcher MUST follow up every successful claim with exactly one+-- of MarkLarkInboundDedupProcessed (durable outcome) or+-- ReleaseLarkInboundDedup (infra failure before durable outcome),+-- supplying the returned claim_token. Otherwise the row sits as an+-- in-flight claim and the next replay attempt must wait for the+-- staleness TTL.+INSERT INTO lark_inbound_message_dedup (installation_id, message_id, claim_token)+VALUES ($1, $2, gen_random_uuid())+ON CONFLICT (installation_id, message_id) DO UPDATE+ SET received_at = now(),+ claim_token = gen_random_uuid()+ WHERE lark_inbound_message_dedup.processed_at IS NULL+ AND lark_inbound_message_dedup.received_at < now() - INTERVAL '60 seconds'+RETURNING installation_id, message_id, received_at, processed_at, claim_token;++-- name: MarkLarkInboundDedupProcessed :execrows+-- Locks in a claim as permanently processed. Called by the dispatcher+-- after a durable outcome has been reached:+-- - a drop audit row was persisted (group filter / unbound user /+-- revoked / invalid event), OR+-- - chat_message + chat_session.updated_at were committed (ingest+-- path, including ingest paths that subsequently fail at issue+-- creation / task enqueue — the user-visible message is already in+-- the session).+-- For the chat_message ingest path the dispatcher invokes this query+-- INSIDE the chat_message+session transaction (via qtx), so the+-- durable write and the Mark commit atomically. A token mismatch+-- (another worker has re-claimed the row in the meantime) returns+-- zero rows; the caller treats that as a lost claim and rolls back the+-- in-tx invocation, so no second chat_message is written.+--+-- Guarded by processed_at IS NULL so a successful Mark is itself+-- idempotent: replaying it cannot resurrect a row that was already+-- terminal.+UPDATE lark_inbound_message_dedup+SET processed_at = now()+WHERE installation_id = $1+ AND message_id = $2+ AND claim_token = $3+ AND processed_at IS NULL;++-- name: ReleaseLarkInboundDedup :execrows+-- Releases an in-flight claim. Called by the dispatcher when an infra+-- error occurred BEFORE any durable side effect (e.g. EnsureChatSession+-- or AppendUserMessage returned an error and its transaction rolled+-- back). Deleting the row lets the WS adapter's retry re-acquire the+-- claim immediately, instead of waiting for the 60-second staleness+-- TTL. Guarded by processed_at IS NULL so an out-of-order Release+-- cannot undo a Mark; guarded by claim_token so a slow-but-alive worker+-- whose claim was reclaimed cannot delete the new holder's row.+DELETE FROM lark_inbound_message_dedup+WHERE installation_id = $1+ AND message_id = $2+ AND claim_token = $3+ AND processed_at IS NULL;++-- name: PurgeLarkInboundDedup :exec+-- Removes dedup rows older than the supplied cutoff. The vacuum job+-- (separate cron) calls this with cutoff = now() - INTERVAL '24h'.+-- Sweeps both processed and (very old) abandoned in-flight rows.+DELETE FROM lark_inbound_message_dedup+WHERE received_at < $1;++-- =====================+-- lark_inbound_audit+-- =====================++-- name: RecordLarkInboundDrop :exec+-- The ONLY write path for events that fail identity check or the+-- group-mention filter. Deliberately accepts no body column — the+-- AuditLogger interface in internal/integrations/lark mirrors that+-- shape so a caller cannot accidentally hand a body to this row.+INSERT INTO lark_inbound_audit (+ installation_id, lark_chat_id, event_type,+ lark_event_id, lark_message_id, drop_reason+) VALUES (+ sqlc.narg('installation_id'),+ sqlc.narg('lark_chat_id'),+ $1,+ sqlc.narg('lark_event_id'),+ sqlc.narg('lark_message_id'),+ $2+);++-- name: ListLarkInboundAuditByInstallation :many+-- Ops debugging view; paged via the (installation_id, received_at) idx.+SELECT * FROM lark_inbound_audit+WHERE installation_id = $1+ORDER BY received_at DESC+LIMIT $2 OFFSET $3;++-- =====================+-- lark_outbound_card_message+-- =====================++-- name: CreateLarkOutboundCardMessage :one+INSERT INTO lark_outbound_card_message (+ chat_session_id, task_id, lark_chat_id, lark_card_message_id, status+) VALUES (+ $1, sqlc.narg('task_id'), $2, $3, $4+)+RETURNING *;++-- name: GetLarkOutboundCardByTask :one+-- Most card patches arrive keyed by task_id (we're streaming an agent+-- run's output). The partial unique index on (task_id) WHERE task_id IS+-- NOT NULL guarantees this returns at most one row.+SELECT * FROM lark_outbound_card_message+WHERE task_id = $1;++-- name: UpdateLarkOutboundCardStatus :exec+UPDATE lark_outbound_card_message+SET status = $2,+ last_patched_at = now()+WHERE id = $1;++-- =====================+-- lark_binding_token+-- =====================++-- name: CreateLarkBindingToken :one+-- Mints a single-use binding token for an unbound Lark user. The TTL+-- cap (`expires_at <= created_at + INTERVAL '15 minutes'`) is enforced+-- by the DB CHECK on the table, in lockstep with lark.BindingTokenTTL.+-- We store the HASH, not the raw token; the raw value is returned to+-- the caller exactly once (in the URL it embeds in the Bot's reply+-- card) and never persisted server-side.+INSERT INTO lark_binding_token (+ token_hash, workspace_id, installation_id, lark_open_id, expires_at+) VALUES (+ $1, $2, $3, $4, $5+)+RETURNING *;++-- name: ConsumeLarkBindingToken :one+-- Atomic redemption. Returns the row only if (a) the hash exists, (b)+-- it has not been consumed, and (c) it has not expired. The UPDATE ++-- RETURNING pattern guarantees that two simultaneous redemptions of+-- the same token cannot both succeed — exactly one row update wins,+-- the other sees zero rows.+UPDATE lark_binding_token+SET consumed_at = now()+WHERE token_hash = $1+ AND consumed_at IS NULL+ AND expires_at > now()+RETURNING *;++-- name: PurgeExpiredLarkBindingTokens :exec+-- Tokens are tiny but unbounded over time. The same vacuum cron that+-- handles dedup can sweep these too.+DELETE FROM lark_binding_token+WHERE expires_at < $1;diff --git a/server/pkg/protocol/events.go b/server/pkg/protocol/events.goindex 63c64e2278..dd2cecd67b 100644--- a/server/pkg/protocol/events.go+++ b/server/pkg/protocol/events.go@@ -124,4 +124,13 @@ const (EventPullRequestLinked = "pull_request:linked"EventPullRequestUpdated = "pull_request:updated"EventPullRequestUnlinked = "pull_request:unlinked"++ // Lark integration events. `created` covers both first-install+ // (UNIQUE on (workspace_id, agent_id) means at most one row per+ // agent) and re-install via UpsertLarkInstallation — front-ends+ // treat both as a single "installation appeared / refreshed"+ // notification. `revoked` flips status to 'revoked' without+ // deleting the row; the audit trail is preserved.+ EventLarkInstallationCreated = "lark_installation:created"+ EventLarkInstallationRevoked = "lark_installation:revoked")