Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-3378 feat(lark): reply inside the originating thread (话题) instead of the group (#4262)
lethean-kun0aa3b53c255a
diff --git a/server/internal/integrations/lark/chat.go b/server/internal/integrations/lark/chat.goindex 85fe403d84..a693521a4b 100644--- a/server/internal/integrations/lark/chat.go+++ b/server/internal/integrations/lark/chat.go@@ -83,7 +83,12 @@ type AppendUserMessageParams struct {CommandBody stringInstallationID pgtype.UUIDLarkMessageID string- ClaimToken pgtype.UUID+ // LarkThreadID is the Lark topic (话题) id of the trigger message, or+ // empty for a normal chat message. AppendUserMessage records it (with+ // LarkMessageID) on the chat binding so the outbound patcher can+ // thread its reply back into the originating topic.+ LarkThreadID string+ ClaimToken pgtype.UUID}// AppendResult reports what AppendUserMessage decided.diff --git a/server/internal/integrations/lark/chat_service.go b/server/internal/integrations/lark/chat_service.goindex 4524b2e179..f8b0c5c741 100644--- a/server/internal/integrations/lark/chat_service.go+++ b/server/internal/integrations/lark/chat_service.go@@ -235,6 +235,25 @@ func (s *chatSessionService) AppendUserMessage(ctx context.Context, p AppendUserreturn AppendResult{}, fmt.Errorf("touch chat session: %w", err)}+ // Record this message as the chat binding's most-recent reply+ // target. The outbound patcher is event-driven and disconnected from+ // the inbound message, so it cannot otherwise know which message /+ // thread to reply into. We persist the latest trigger here (in the+ // same tx as the chat_message write) so EventChatDone can thread the+ // reply back into the originating Lark topic. last_lark_thread_id is+ // NULL for non-thread messages, which keeps the outbound on the+ // chat-level send path. Skipped when there is no Lark message_id+ // (defensive: every real inbound carries one).+ if p.LarkMessageID != "" {+ if err := qtx.UpdateLarkChatSessionBindingReplyTarget(ctx, db.UpdateLarkChatSessionBindingReplyTargetParams{+ ChatSessionID: p.ChatSessionID,+ LastLarkMessageID: textOrNull(p.LarkMessageID),+ LastLarkThreadID: textOrNull(p.LarkThreadID),+ }); err != nil {+ return AppendResult{}, fmt.Errorf("update reply target: %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 ordiff --git a/server/internal/integrations/lark/client.go b/server/internal/integrations/lark/client.goindex 890d0bb756..a51ca6c75f 100644--- a/server/internal/integrations/lark/client.go+++ b/server/internal/integrations/lark/client.go@@ -198,8 +198,30 @@ type SendCardParams struct {// through opaque so the card-template package can evolve without// dragging this transport interface along.CardJSON string+ // ReplyTarget, when set, routes the send through Lark's reply+ // endpoint (POST /im/v1/messages/{id}/reply) instead of the+ // chat-level send endpoint, so the card lands inside the originating+ // 话题 (thread). Empty ReplyTarget keeps the legacy chat-level send.+ ReplyTarget ReplyTarget}+// ReplyTarget describes how an outbound message should be threaded back+// to an inbound message. When MessageID is non-empty the transport uses+// Lark's reply endpoint targeting that message; InThread maps to the+// reply_in_thread flag so the reply stays inside the message's topic.+// The zero value (empty MessageID) means "send at the chat level" — the+// historical behavior — so callers that don't care about threading just+// leave it unset.+type ReplyTarget struct {+ MessageID string+ InThread bool+}++// IsSet reports whether this target should route through the reply+// endpoint. A reply needs a parent message_id; without one there is+// nothing to reply to and the caller falls back to a chat-level send.+func (r ReplyTarget) IsSet() bool { return r.MessageID != "" }+// PatchCardParams is the input shape for updating an existing card.type PatchCardParams struct {InstallationID InstallationCredentials@@ -214,6 +236,9 @@ type SendTextParams struct {InstallationID InstallationCredentialsChatID ChatIDText string+ // ReplyTarget threads the text reply back into a Lark topic; see+ // ReplyTarget. Empty keeps the chat-level send.+ ReplyTarget ReplyTarget}// SendMarkdownCardParams is the input shape for posting an agent@@ -231,6 +256,9 @@ type SendMarkdownCardParams struct {// Lark shows in the chat list / desktop notification. Empty falls// back to whatever Lark derives from the body.Summary string+ // ReplyTarget threads the card reply back into a Lark topic; see+ // ReplyTarget. Empty keeps the chat-level send.+ ReplyTarget ReplyTarget}// BindingPromptParams carries the data needed to render and send thediff --git a/server/internal/integrations/lark/dispatcher.go b/server/internal/integrations/lark/dispatcher.goindex 3deeaa55fd..bd59c03b9e 100644--- a/server/internal/integrations/lark/dispatcher.go+++ b/server/internal/integrations/lark/dispatcher.go@@ -57,6 +57,15 @@ type InboundMessage struct {ParentID stringRootID string+ // ThreadID is the Lark topic (话题) id this message belongs to,+ // taken verbatim from the receive event's `thread_id`. Lark only+ // populates it for messages posted inside a thread, so a non-empty+ // value is the signal that the @-mention happened in a thread. The+ // dispatcher persists it on the chat binding so the (decoupled)+ // outbound patcher can reply back into the same thread instead of+ // posting at the chat level.+ ThreadID string+// CommandBody is the user's OWN typed text (the decoded Body before// the enricher prepends any <quoted_message> / <forwarded_messages>// context). The `/issue` command is parsed from THIS, not from the@@ -484,6 +493,7 @@ func (d *Dispatcher) processClaimed(ctx context.Context, msg InboundMessage, insCommandBody: msg.CommandBody,InstallationID: inst.ID,LarkMessageID: msg.MessageID,+ LarkThreadID: msg.ThreadID,ClaimToken: claimToken,})if err != nil {diff --git a/server/internal/integrations/lark/dispatcher_test.go b/server/internal/integrations/lark/dispatcher_test.goindex f8fb9dc9ba..97e5d10062 100644--- a/server/internal/integrations/lark/dispatcher_test.go+++ b/server/internal/integrations/lark/dispatcher_test.go@@ -476,6 +476,48 @@ func TestDispatcher_PlainMessageEnqueuesTask(t *testing.T) {}}+// TestDispatcher_ForwardsThreadIDToAppend verifies the dispatcher+// threads the inbound message's thread_id into AppendUserMessage, which+// is what lets the chat binding remember the topic so the outbound+// patcher can reply back into it.+func TestDispatcher_ForwardsThreadIDToAppend(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)}},+ }++ _, err := d.Handle(context.Background(), InboundMessage{+ AppID: "ok",+ ChatType: ChatTypeGroup,+ AddressedToBot: true,+ SenderOpenID: "ou_user_a",+ Body: "hey in a topic",+ MessageID: "om_in_thread",+ ThreadID: "omt_topic_42",+ })+ if err != nil {+ t.Fatalf("unexpected error: %v", err)+ }+ if chat.lastAppendParams.LarkThreadID != "omt_topic_42" {+ t.Errorf("LarkThreadID forwarded to AppendUserMessage: got %q want omt_topic_42",+ chat.lastAppendParams.LarkThreadID)+ }+ if chat.lastAppendParams.LarkMessageID != "om_in_thread" {+ t.Errorf("LarkMessageID forwarded to AppendUserMessage: got %q want om_in_thread",+ chat.lastAppendParams.LarkMessageID)+ }+}+func TestDispatcher_GroupMessageUsesInstallerAsCreator(t *testing.T) {inst := activeInstallation()sessionID := validUUID(0x66)diff --git a/server/internal/integrations/lark/http_client.go b/server/internal/integrations/lark/http_client.goindex ca2a982ce7..fc1fefc794 100644--- a/server/internal/integrations/lark/http_client.go+++ b/server/internal/integrations/lark/http_client.go@@ -228,6 +228,32 @@ func (c *httpAPIClient) invalidateToken(appID string) {c.mu.Unlock()}+// outboundMessageRequest builds the (path, body) the three send methods+// share. When target.IsSet() the message is routed through Lark's reply+// endpoint (POST /im/v1/messages/{message_id}/reply) so it threads back+// into the originating 话题 — reply_in_thread carries the target's+// InThread flag (Lark also keeps the reply in-thread automatically when+// the parent message already belongs to a thread). Otherwise the message+// goes to the chat-level send endpoint keyed by receive_id=chat_id, the+// historical behavior. Body is map[string]any (not map[string]string)+// because reply_in_thread is a bool.+func outboundMessageRequest(chatID ChatID, msgType, content string, target ReplyTarget) (string, map[string]any) {+ if target.IsSet() {+ return "/open-apis/im/v1/messages/" + url.PathEscape(target.MessageID) + "/reply", map[string]any{+ "msg_type": msgType,+ "content": content,+ "reply_in_thread": target.InThread,+ }+ }+ q := url.Values{}+ q.Set("receive_id_type", "chat_id")+ return "/open-apis/im/v1/messages?" + q.Encode(), map[string]any{+ "receive_id": string(chatID),+ "msg_type": msgType,+ "content": content,+ }+}+// 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.@@ -242,13 +268,7 @@ func (c *httpAPIClient) SendInteractiveCard(ctx context.Context, p SendCardParamif 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,- }+ path, body := outboundMessageRequest(p.ChatID, "interactive", p.CardJSON, p.ReplyTarget)var resp struct {Code int `json:"code"`Msg string `json:"msg"`@@ -256,7 +276,6 @@ func (c *httpAPIClient) SendInteractiveCard(ctx context.Context, p SendCardParamMessageID string `json:"message_id"`} `json:"data"`}- path := "/open-apis/im/v1/messages?" + q.Encode()if err := c.doJSON(ctx, c.resolveBaseURL(p.InstallationID), http.MethodPost, path, token, body, &resp); err != nil {return "", fmt.Errorf("lark http client: send interactive card: %w", err)}@@ -264,7 +283,7 @@ func (c *httpAPIClient) SendInteractiveCard(ctx context.Context, p SendCardParamif 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 "", &APIError{Op: "send interactive card", Code: resp.Code, Msg: resp.Msg}}return resp.Data.MessageID, nil}@@ -293,13 +312,7 @@ func (c *httpAPIClient) SendTextMessage(ctx context.Context, p SendTextParams) (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),- }+ path, body := outboundMessageRequest(p.ChatID, "text", string(contentBytes), p.ReplyTarget)var resp struct {Code int `json:"code"`Msg string `json:"msg"`@@ -307,7 +320,6 @@ func (c *httpAPIClient) SendTextMessage(ctx context.Context, p SendTextParams) (MessageID string `json:"message_id"`} `json:"data"`}- path := "/open-apis/im/v1/messages?" + q.Encode()if err := c.doJSON(ctx, c.resolveBaseURL(p.InstallationID), http.MethodPost, path, token, body, &resp); err != nil {return "", fmt.Errorf("lark http client: send text message: %w", err)}@@ -315,7 +327,7 @@ func (c *httpAPIClient) SendTextMessage(ctx context.Context, p SendTextParams) (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 "", &APIError{Op: "send text message", Code: resp.Code, Msg: resp.Msg}}return resp.Data.MessageID, nil}@@ -363,13 +375,7 @@ func (c *httpAPIClient) SendMarkdownCard(ctx context.Context, p SendMarkdownCardif 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),- }+ path, body := outboundMessageRequest(p.ChatID, "interactive", string(cardBytes), p.ReplyTarget)var resp struct {Code int `json:"code"`Msg string `json:"msg"`@@ -377,7 +383,6 @@ func (c *httpAPIClient) SendMarkdownCard(ctx context.Context, p SendMarkdownCardMessageID string `json:"message_id"`} `json:"data"`}- path := "/open-apis/im/v1/messages?" + q.Encode()if err := c.doJSON(ctx, c.resolveBaseURL(p.InstallationID), http.MethodPost, path, token, body, &resp); err != nil {return "", fmt.Errorf("lark http client: send markdown card: %w", err)}@@ -385,7 +390,7 @@ func (c *httpAPIClient) SendMarkdownCard(ctx context.Context, p SendMarkdownCardif 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 "", &APIError{Op: "send markdown card", Code: resp.Code, Msg: resp.Msg}}return resp.Data.MessageID, nil}@@ -914,6 +919,57 @@ func isTokenError(code int) bool {return code == codeTokenExpired || code == codeTokenInvalid}+// APIError is a structured Lark business error: the request reached+// Lark, returned HTTP 200, but Lark rejected it with a non-zero+// `code`. This is distinct from the transport-level errors doJSON+// surfaces (network failure, 5xx, timeout), which are returned as+// plain wrapped errors. The distinction matters for the threaded-reply+// fallback: a business code is definitive ("nothing was sent, and here+// is exactly why"), whereas a transport error is ambiguous ("the+// message may or may not have been delivered") and must NOT trigger a+// chat-level retry that could duplicate or leak the reply.+type APIError struct {+ Op string+ Code int+ Msg string+}++func (e *APIError) Error() string {+ return fmt.Sprintf("lark http client: %s: code=%d msg=%q", e.Op, e.Code, e.Msg)+}++// threadReplyUnsupportedCodes are the reply-endpoint business codes+// that definitively mean "this specific trigger message / topic cannot+// receive a threaded reply" AND nothing was sent, while a plain+// chat-level send to the same chat is unaffected. Only these justify+// the chat-level fallback. Rate limits (230020), "message is being+// sent" (230049, ambiguous), permission/content errors (which would+// also fail at chat level), and all transport/5xx/timeout failures are+// deliberately excluded: those stay failures so we never duplicate a+// reply or leak a thread-only reply into the main group chat.+// Codes are from the IM reply-message endpoint error table.+var threadReplyUnsupportedCodes = map[int]struct{}{+ 230011: {}, // the trigger message has been recalled+ 230019: {}, // the topic does not exist+ 230050: {}, // the trigger message is invisible to the operator+ 230071: {}, // the group does not support reply in thread+ 230072: {}, // aggregated messages do not support reply in thread+ 230111: {}, // cannot reply to a self-destructing message+}++// isThreadReplyUnsupported reports whether err is a Lark APIError whose+// code means the threaded reply cannot land on this target. Only such+// errors are safe to retry at the chat level. Transport errors and+// other business codes return false.+func isThreadReplyUnsupported(err error) bool {+ var apiErr *APIError+ if errors.As(err, &apiErr) {+ _, ok := threadReplyUnsupportedCodes[apiErr.Code]+ return ok+ }+ return false+}+func truncate(s string, n int) string {if len(s) <= n {return sdiff --git a/server/internal/integrations/lark/http_client_test.go b/server/internal/integrations/lark/http_client_test.goindex b79033982d..db2fad94f9 100644--- a/server/internal/integrations/lark/http_client_test.go+++ b/server/internal/integrations/lark/http_client_test.go@@ -3,6 +3,7 @@ package larkimport ("context""encoding/json"+ "errors""io""net/http""net/http/httptest"@@ -106,6 +107,34 @@ func (f *larkFakeServer) stubSend(resp map[string]any, verify func(r *http.Reque})}+// stubReply installs the IM-reply endpoint+// (POST /open-apis/im/v1/messages/<id>/reply), used by the thread-reply+// path. Body is decoded as map[string]any because reply_in_thread is a+// bool. Register stubToken + stubReply (and not stubSend / stubPatch) in+// a reply test, since they share the /messages/ prefix.+func (f *larkFakeServer) stubReply(resp map[string]any, verify func(r *http.Request, id string, body map[string]any)) {+ const prefix = "/open-apis/im/v1/messages/"+ f.mux.HandleFunc(prefix, func(w http.ResponseWriter, r *http.Request) {+ if r.Method != http.MethodPost || !strings.HasSuffix(r.URL.Path, "/reply") {+ f.t.Errorf("reply: want POST .../reply, got %s %s", r.Method, r.URL.Path)+ return+ }+ f.sendN.Add(1)+ id := strings.TrimSuffix(strings.TrimPrefix(r.URL.Path, prefix), "/reply")+ if id == "" {+ f.t.Errorf("reply: missing message id")+ }+ var body map[string]any+ if err := json.NewDecoder(r.Body).Decode(&body); err != nil {+ f.t.Errorf("reply: decode body: %v", err)+ }+ if verify != nil {+ verify(r, id, 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@@ -410,6 +439,62 @@ func TestHTTPClient_SendTextMessage_HappyPath(t *testing.T) {}}+// TestHTTPClient_SendTextMessage_ReplyInThread pins the wire shape of a+// threaded reply: when ReplyTarget is set the client must POST to the+// reply endpoint (/messages/<id>/reply), carry reply_in_thread=true, and+// NOT include a chat-level receive_id — that's what lands the agent's+// reply inside the originating 话题 (thread) instead of the group.+func TestHTTPClient_SendTextMessage_ReplyInThread(t *testing.T) {+ fake := newLarkFake(t)+ fake.stubToken("tok_reply", 7200)+ fake.stubReply(+ map[string]any{+ "code": 0,+ "msg": "ok",+ "data": map[string]string{"message_id": "om_reply_1"},+ },+ func(r *http.Request, id string, body map[string]any) {+ if id != "om_trigger" {+ t.Errorf("reply target id: got %q want om_trigger", id)+ }+ if body["msg_type"] != "text" {+ t.Errorf("msg_type: got %v want text", body["msg_type"])+ }+ if v, _ := body["reply_in_thread"].(bool); !v {+ t.Errorf("reply_in_thread: got %v want true", body["reply_in_thread"])+ }+ if _, hasRecv := body["receive_id"]; hasRecv {+ t.Errorf("reply endpoint body must NOT carry receive_id; got %v", body)+ }+ content, ok := body["content"].(string)+ if !ok {+ t.Fatalf("content missing or not a string: %v", body["content"])+ }+ var inner map[string]string+ if err := json.Unmarshal([]byte(content), &inner); err != nil {+ t.Fatalf("content inner JSON: %v (raw=%q)", err, content)+ }+ if inner["text"] != "threaded hi" {+ t.Errorf("inner content.text: got %q want threaded hi", inner["text"])+ }+ },+ )++ c := newTestClient(fake, time.Now)+ msgID, err := c.SendTextMessage(context.Background(), SendTextParams{+ InstallationID: testCreds(),+ ChatID: ChatID("oc_chat_42"),+ Text: "threaded hi",+ ReplyTarget: ReplyTarget{MessageID: "om_trigger", InThread: true},+ })+ if err != nil {+ t.Fatalf("send: %v", err)+ }+ if msgID != "om_reply_1" {+ t.Errorf("message id: got %q want om_reply_1", msgID)+ }+}+// 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@@ -639,6 +724,70 @@ func TestHTTPClient_SendInteractiveCard_LarkErrorCode(t *testing.T) {}}+// TestHTTPClient_SendMethods_ReturnTypedAPIError pins that the three+// send methods used for threaded replies surface a non-zero Lark code+// as a structured *APIError, so the outbound fallback can classify+// "topic cannot receive this reply" codes without string matching.+func TestHTTPClient_SendMethods_ReturnTypedAPIError(t *testing.T) {+ cases := []struct {+ name string+ call func(c *httpAPIClient) error+ }{+ {"interactive", func(c *httpAPIClient) error {+ _, err := c.SendInteractiveCard(context.Background(), SendCardParams{InstallationID: testCreds(), ChatID: "oc", CardJSON: `{}`})+ return err+ }},+ {"text", func(c *httpAPIClient) error {+ _, err := c.SendTextMessage(context.Background(), SendTextParams{InstallationID: testCreds(), ChatID: "oc", Text: "hi"})+ return err+ }},+ {"markdown", func(c *httpAPIClient) error {+ _, err := c.SendMarkdownCard(context.Background(), SendMarkdownCardParams{InstallationID: testCreds(), ChatID: "oc", Markdown: "**hi**"})+ return err+ }},+ }+ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ fake := newLarkFake(t)+ fake.stubToken("tok_e", 7200)+ fake.stubSend(map[string]any{"code": 230071, "msg": "group does not support reply in thread"}, nil)+ c := newTestClient(fake, time.Now)+ err := tc.call(c)+ var apiErr *APIError+ if !errors.As(err, &apiErr) {+ t.Fatalf("want *APIError, got %T (%v)", err, err)+ }+ if apiErr.Code != 230071 {+ t.Errorf("APIError.Code = %d; want 230071", apiErr.Code)+ }+ if !isThreadReplyUnsupported(err) {+ t.Errorf("230071 should classify as thread-reply-unsupported")+ }+ if !strings.Contains(err.Error(), "code=230071") {+ t.Errorf("error string should preserve code=230071: %v", err)+ }+ })+ }+}++// TestIsThreadReplyUnsupported_ExcludesAmbiguous guards that ambiguous+// and rate-limit failures are NOT treated as classified thread errors,+// so they never trigger a chat-level fallback.+func TestIsThreadReplyUnsupported_ExcludesAmbiguous(t *testing.T) {+ if isThreadReplyUnsupported(errors.New("transport failure")) {+ t.Error("plain transport error must not classify as thread-reply-unsupported")+ }+ if isThreadReplyUnsupported(&APIError{Code: 230020, Msg: "rate limit"}) {+ t.Error("rate limit (230020) must not classify as thread-reply-unsupported")+ }+ if isThreadReplyUnsupported(&APIError{Code: 230049, Msg: "message is being sent"}) {+ t.Error("ambiguous 'being sent' (230049) must not classify as thread-reply-unsupported")+ }+ if !isThreadReplyUnsupported(&APIError{Code: 230072, Msg: "aggregated"}) {+ t.Error("aggregated message (230072) should classify as thread-reply-unsupported")+ }+}+func TestHTTPClient_SendInteractiveCard_TokenExpired_InvalidatesCache(t *testing.T) {fake := newLarkFake(t)fake.stubToken("tok_first", 7200)diff --git a/server/internal/integrations/lark/outbound.go b/server/internal/integrations/lark/outbound.goindex 737a9d2743..081e75c80f 100644--- a/server/internal/integrations/lark/outbound.go+++ b/server/internal/integrations/lark/outbound.go@@ -359,24 +359,77 @@ func (p *Patcher) sendChatReply(ctx context.Context, creds InstallationCredentiaif content == "" {return nil}+ target := threadReplyTarget(binding)if containsMarkdown(content) {- if _, err := p.client.SendMarkdownCard(ctx, SendMarkdownCardParams{+ return sendWithThreadFallback(p.cfg.Logger, "send markdown card", target, func(t ReplyTarget) error {+ _, err := p.client.SendMarkdownCard(ctx, SendMarkdownCardParams{+ InstallationID: creds,+ ChatID: ChatID(binding.LarkChatID),+ Markdown: content,+ ReplyTarget: t,+ })+ return err+ })+ }+ return sendWithThreadFallback(p.cfg.Logger, "send text message", target, func(t ReplyTarget) error {+ _, err := p.client.SendTextMessage(ctx, SendTextParams{InstallationID: creds,ChatID: ChatID(binding.LarkChatID),- Markdown: content,- }); err != nil {- return fmt.Errorf("send markdown card: %w", err)+ Text: content,+ ReplyTarget: t,+ })+ return err+ })+}++// threadReplyTarget derives the outbound reply target from the chat+// binding's most-recent inbound trigger. We thread the reply ONLY when+// that trigger was itself inside a Lark topic (last_lark_thread_id+// present): normal group / p2p chats keep the unchanged chat-level send+// path, and only an @-mention that happened inside a thread gets a+// threaded reply (replying to last_lark_message_id with reply_in_thread).+// The zero ReplyTarget means "send at the chat level".+func threadReplyTarget(binding db.LarkChatSessionBinding) ReplyTarget {+ if binding.LastLarkThreadID.Valid && binding.LastLarkThreadID.String != "" &&+ binding.LastLarkMessageID.Valid && binding.LastLarkMessageID.String != "" {+ return ReplyTarget{MessageID: binding.LastLarkMessageID.String, InThread: true}+ }+ return ReplyTarget{}+}++// sendWithThreadFallback runs send with the thread reply target and,+// ONLY when the threaded attempt fails with a Lark error that means the+// topic reply legitimately cannot land (trigger message recalled, topic+// gone, topics disabled, aggregated message — see+// threadReplyUnsupportedCodes), retries once at the chat level so the+// reply is not silently lost. Any other failure — transport error,+// 5xx, timeout, rate limit, or an ambiguous "the server may have+// received it" error — is logged and returned as a failure rather than+// retried: a blind chat-level retry could duplicate the reply or leak a+// thread-only reply into the main group chat. When target is already+// chat-level there is nothing to fall back to and the error is returned.+//+// It is a package-level function (rather than a Patcher method) so the+// event-driven Patcher and the immediate OutcomeReplier share one+// classified fallback path.+func sendWithThreadFallback(log *slog.Logger, op string, target ReplyTarget, send func(ReplyTarget) error) error {+ err := send(target)+ if err == nil {+ return nil+ }+ if target.IsSet() && isThreadReplyUnsupported(err) {+ log.Warn("lark: thread reply unsupported for target, retrying at chat level",+ "op", op, "reply_message_id", target.MessageID, "error", err)+ if fallbackErr := send(ReplyTarget{}); fallbackErr != nil {+ return fmt.Errorf("%s (chat-level fallback after thread-unsupported reply: %v): %w", op, err, fallbackErr)}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)+ if target.IsSet() {+ log.Warn("lark: thread reply failed; not falling back (non-classified error)",+ "op", op, "reply_message_id", target.MessageID, "error", err)}- return nil+ return fmt.Errorf("%s: %w", op, err)}func (p *Patcher) installationCredentials(inst db.LarkInstallation) (InstallationCredentials, error) {@@ -417,14 +470,15 @@ func (p *Patcher) fail(ctx context.Context, creds InstallationCredentials, bindiif 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+ return sendWithThreadFallback(p.cfg.Logger, "send error card", threadReplyTarget(binding), func(t ReplyTarget) error {+ _, err := p.client.SendInteractiveCard(ctx, SendCardParams{+ InstallationID: creds,+ ChatID: ChatID(binding.LarkChatID),+ CardJSON: render.JSON,+ ReplyTarget: t,+ })+ return err+ })}// taskAndSessionFromEvent parses the typed-ish payload broadcastTaskEventdiff --git a/server/internal/integrations/lark/outbound_test.go b/server/internal/integrations/lark/outbound_test.goindex ec239f0b65..aa1f2aba18 100644--- a/server/internal/integrations/lark/outbound_test.go+++ b/server/internal/integrations/lark/outbound_test.go@@ -82,14 +82,32 @@ type fakeAPIClient struct {mdCardErr errormdCardReturn stringbindingSent []BindingPromptParams+ // threadReplyErr, when non-nil, is returned by the three send+ // methods whenever the call carries a thread ReplyTarget, while the+ // attempt is still recorded. Tests inject either a classified+ // *APIError (to exercise the chat-level fallback) or an ambiguous+ // transport error (to assert no fallback happens).+ threadReplyErr error}+// errThreadReplyClassified is a Lark business error the fallback path+// recognizes (230071 = group does not support reply in thread), so a+// thread send that returns it triggers the chat-level retry.+var errThreadReplyClassified = &APIError{Op: "send text message", Code: 230071, Msg: "group does not support reply in thread"}++// errThreadReplyTransport is an ambiguous, non-classified failure: the+// fallback path must NOT retry it at chat level.+var errThreadReplyTransport = errors.New("fake: transport failure")+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)+ if f.threadReplyErr != nil && p.ReplyTarget.IsSet() {+ return "", f.threadReplyErr+ }return f.sendReturn, f.sendErr}func (f *fakeAPIClient) PatchInteractiveCard(ctx context.Context, p PatchCardParams) error {@@ -102,12 +120,18 @@ func (f *fakeAPIClient) SendTextMessage(ctx context.Context, p SendTextParams) (f.mu.Lock()defer f.mu.Unlock()f.textSent = append(f.textSent, p)+ if f.threadReplyErr != nil && p.ReplyTarget.IsSet() {+ return "", f.threadReplyErr+ }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)+ if f.threadReplyErr != nil && p.ReplyTarget.IsSet() {+ return "", f.threadReplyErr+ }return f.mdCardReturn, f.mdCardErr}func (f *fakeAPIClient) SendBindingPromptCard(ctx context.Context, p BindingPromptParams) error {@@ -463,3 +487,147 @@ func TestDefaultRendererConfigCarriesUpdateMulti(t *testing.T) {})}}++// TestPatcherRepliesInThreadWhenTriggerWasInThread pins the core+// behavior of this feature: when the chat binding's most-recent trigger+// lived inside a Lark topic (last_lark_thread_id set), the agent reply+// is routed through the reply endpoint targeting that message with+// reply_in_thread=true, so it lands inside the 话题 instead of the group.+func TestPatcherRepliesInThreadWhenTriggerWasInThread(t *testing.T) {+ p, q, api := newTestPatcher(t)+ q.binding.LastLarkMessageID = pgtype.Text{String: "om_trigger", Valid: true}+ q.binding.LastLarkThreadID = pgtype.Text{String: "omt_topic", Valid: true}+ taskID := uuidFromString(t, "ee666666-ee66-ee66-ee66-eeeeeeeeeeee")++ p.handleEvent(events.Event{+ Type: protocol.EventChatDone,+ TaskID: uuidString(taskID),+ ChatSessionID: uuidString(q.binding.ChatSessionID),+ Payload: protocol.ChatDonePayload{Content: "in-thread reply"},+ })++ api.mu.Lock()+ defer api.mu.Unlock()+ if len(api.textSent) != 1 {+ t.Fatalf("expected one text send; got %d", len(api.textSent))+ }+ got := api.textSent[0].ReplyTarget+ if got.MessageID != "om_trigger" || !got.InThread {+ t.Errorf("expected thread reply target {om_trigger, InThread:true}; got %+v", got)+ }+}++// TestPatcherSendsToChatWhenNoThread verifies that a non-thread trigger+// (no last_lark_thread_id on the binding) keeps the historical+// chat-level send: ReplyTarget stays empty so SendTextMessage targets+// the chat by chat_id. This is the no-behavior-change guarantee for+// normal group / p2p chats.+func TestPatcherSendsToChatWhenNoThread(t *testing.T) {+ p, q, api := newTestPatcher(t)+ // binding has a message id but NO thread id → must not thread.+ q.binding.LastLarkMessageID = pgtype.Text{String: "om_trigger", Valid: true}+ 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{Content: "plain reply"},+ })++ api.mu.Lock()+ defer api.mu.Unlock()+ if len(api.textSent) != 1 {+ t.Fatalf("expected one text send; got %d", len(api.textSent))+ }+ if api.textSent[0].ReplyTarget.IsSet() {+ t.Errorf("non-thread trigger must NOT route through the reply endpoint; got %+v",+ api.textSent[0].ReplyTarget)+ }+}++// TestPatcherThreadReplyMarkdownRoutesToThread verifies the markdown+// card path also threads when the trigger was in a topic.+func TestPatcherThreadReplyMarkdownRoutesToThread(t *testing.T) {+ p, q, api := newTestPatcher(t)+ q.binding.LastLarkMessageID = pgtype.Text{String: "om_trigger", Valid: true}+ q.binding.LastLarkThreadID = pgtype.Text{String: "omt_topic", Valid: true}+ taskID := uuidFromString(t, "ee888888-ee88-ee88-ee88-eeeeeeeeeeee")++ p.handleEvent(events.Event{+ Type: protocol.EventChatDone,+ TaskID: uuidString(taskID),+ ChatSessionID: uuidString(q.binding.ChatSessionID),+ Payload: protocol.ChatDonePayload{Content: "# heading\n- bullet"},+ })++ api.mu.Lock()+ defer api.mu.Unlock()+ if len(api.mdCardSent) != 1 {+ t.Fatalf("expected one markdown card send; got %d", len(api.mdCardSent))+ }+ got := api.mdCardSent[0].ReplyTarget+ if got.MessageID != "om_trigger" || !got.InThread {+ t.Errorf("expected markdown thread reply target {om_trigger, InThread:true}; got %+v", got)+ }+}++// TestPatcherThreadReplyFallsBackToChatLevel verifies that when a+// threaded send fails with a classified "topic cannot receive this+// reply" Lark error (e.g. the trigger message was recalled or the topic+// was aggregated), the patcher retries once at the chat level so the+// agent's reply is never silently lost.+func TestPatcherThreadReplyFallsBackToChatLevel(t *testing.T) {+ p, q, api := newTestPatcher(t)+ api.threadReplyErr = errThreadReplyClassified+ q.binding.LastLarkMessageID = pgtype.Text{String: "om_trigger", Valid: true}+ q.binding.LastLarkThreadID = pgtype.Text{String: "omt_topic", Valid: true}+ taskID := uuidFromString(t, "ee999999-ee99-ee99-ee99-eeeeeeeeeeee")++ p.handleEvent(events.Event{+ Type: protocol.EventChatDone,+ TaskID: uuidString(taskID),+ ChatSessionID: uuidString(q.binding.ChatSessionID),+ Payload: protocol.ChatDonePayload{Content: "reply that must survive"},+ })++ api.mu.Lock()+ defer api.mu.Unlock()+ if len(api.textSent) != 2 {+ t.Fatalf("expected two text sends (thread attempt + chat-level fallback); got %d", len(api.textSent))+ }+ if !api.textSent[0].ReplyTarget.IsSet() {+ t.Errorf("first attempt should be the thread reply; got %+v", api.textSent[0].ReplyTarget)+ }+ if api.textSent[1].ReplyTarget.IsSet() {+ t.Errorf("fallback attempt must be chat-level (empty ReplyTarget); got %+v", api.textSent[1].ReplyTarget)+ }+}++// TestPatcherThreadReplyDoesNotFallBackOnAmbiguousError verifies that a+// non-classified failure (transport error, 5xx, timeout, rate limit)+// from the threaded send is NOT retried at chat level: a blind retry+// could duplicate the reply or leak a thread-only reply into the group.+func TestPatcherThreadReplyDoesNotFallBackOnAmbiguousError(t *testing.T) {+ p, q, api := newTestPatcher(t)+ api.threadReplyErr = errThreadReplyTransport+ q.binding.LastLarkMessageID = pgtype.Text{String: "om_trigger", Valid: true}+ q.binding.LastLarkThreadID = pgtype.Text{String: "omt_topic", Valid: true}+ taskID := uuidFromString(t, "ee888888-ee88-ee88-ee88-eeeeeeeeeeee")++ p.handleEvent(events.Event{+ Type: protocol.EventChatDone,+ TaskID: uuidString(taskID),+ ChatSessionID: uuidString(q.binding.ChatSessionID),+ Payload: protocol.ChatDonePayload{Content: "reply that must not duplicate"},+ })++ api.mu.Lock()+ defer api.mu.Unlock()+ if len(api.textSent) != 1 {+ t.Fatalf("expected a single thread attempt with no chat-level fallback; got %d sends", len(api.textSent))+ }+ if !api.textSent[0].ReplyTarget.IsSet() {+ t.Errorf("the single attempt should be the thread reply; got %+v", api.textSent[0].ReplyTarget)+ }+}diff --git a/server/internal/integrations/lark/outcome_replier.go b/server/internal/integrations/lark/outcome_replier.goindex 21eec0e1e2..731f611893 100644--- a/server/internal/integrations/lark/outcome_replier.go+++ b/server/internal/integrations/lark/outcome_replier.go@@ -235,14 +235,33 @@ func (r *LarkOutcomeReplier) sendIssueCreated(ctx context.Context, inst db.LarkIreturn 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)+ // Share the Patcher's classified fallback: a thread reply that+ // fails because the topic cannot receive it (recalled trigger,+ // topics disabled, aggregated message) falls back to a chat-level+ // send so the confirmation is not lost; transport/5xx/rate-limit+ // failures stay failures rather than leaking into the group chat.+ return sendWithThreadFallback(r.log, "send issue-created text", inboundReplyTarget(msg), func(t ReplyTarget) error {+ _, err := r.client.SendTextMessage(ctx, SendTextParams{+ InstallationID: creds,+ ChatID: msg.ChatID,+ Text: text,+ ReplyTarget: t,+ })+ return err+ })+}++// inboundReplyTarget threads an outbound reply off the inbound trigger+// message when that message lived inside a Lark topic (话题). It mirrors+// threadReplyTarget (used by the event-driven Patcher) but reads the+// live InboundMessage the replier already holds, so it needs no DB+// round-trip. An empty thread_id yields the zero ReplyTarget — a+// chat-level send, i.e. the unchanged behavior for non-thread messages.+func inboundReplyTarget(msg InboundMessage) ReplyTarget {+ if msg.ThreadID != "" && msg.MessageID != "" {+ return ReplyTarget{MessageID: msg.MessageID, InThread: true}}- return nil+ return ReplyTarget{}}// issueCreatedText composes the user-facing confirmation. Identifier@@ -285,14 +304,18 @@ func (r *LarkOutcomeReplier) sendChatNotice(ctx context.Context, inst db.LarkInsif 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+ // Same classified fallback as sendIssueCreated: only thread-reply+ // failures that mean the topic cannot receive the message fall back+ // to a chat-level send; ambiguous/transport failures stay failures.+ return sendWithThreadFallback(r.log, "send notice card", inboundReplyTarget(msg), func(t ReplyTarget) error {+ _, err := r.client.SendInteractiveCard(ctx, SendCardParams{+ InstallationID: creds,+ ChatID: msg.ChatID,+ CardJSON: cardJSON,+ ReplyTarget: t,+ })+ return err+ })}func (r *LarkOutcomeReplier) installationCredentials(inst db.LarkInstallation) (InstallationCredentials, error) {diff --git a/server/internal/integrations/lark/outcome_replier_test.go b/server/internal/integrations/lark/outcome_replier_test.goindex cb3581a0bc..491edc3c14 100644--- a/server/internal/integrations/lark/outcome_replier_test.go+++ b/server/internal/integrations/lark/outcome_replier_test.go@@ -26,6 +26,12 @@ type stubAPIClientWithRecorder struct {sendErr errortextErr errorbindingErr error+ // threadSendErr, when non-nil, is returned by SendInteractiveCard /+ // SendTextMessage only when the call carries a thread ReplyTarget.+ // Used to exercise the shared classified fallback on the immediate+ // replies. The attempt is still recorded so tests can count the+ // thread attempt plus any chat-level fallback.+ threadSendErr error}func (s *stubAPIClientWithRecorder) IsConfigured() bool { return s.configured }@@ -33,10 +39,13 @@ 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()+ s.interactiveOut = append(s.interactiveOut, p)+ if s.threadSendErr != nil && p.ReplyTarget.IsSet() {+ return "", s.threadSendErr+ }if s.sendErr != nil {return "", s.sendErr}- s.interactiveOut = append(s.interactiveOut, p)return "lark-msg-id", nil}@@ -47,10 +56,13 @@ func (s *stubAPIClientWithRecorder) PatchInteractiveCard(ctx context.Context, pfunc (s *stubAPIClientWithRecorder) SendTextMessage(ctx context.Context, p SendTextParams) (string, error) {s.mu.Lock()defer s.mu.Unlock()+ s.textOut = append(s.textOut, p)+ if s.threadSendErr != nil && p.ReplyTarget.IsSet() {+ return "", s.threadSendErr+ }if s.textErr != nil {return "", s.textErr}- s.textOut = append(s.textOut, p)return "lark-text-msg-id", nil}@@ -375,6 +387,140 @@ func TestLarkOutcomeReplierOutcomeIngestedSilentWithoutIssue(t *testing.T) {}}+// threadedInboundMsg builds an inbound message that originated inside a+// Lark topic, so the replier targets the thread (and can fall back).+func threadedInboundMsg(chatID ChatID) InboundMessage {+ return InboundMessage{ChatID: chatID, MessageID: "om_trigger", ThreadID: "omt_topic", SenderOpenID: "ou_user"}+}++// TestLarkOutcomeReplierIssueCreatedThreadFallback verifies the /issue+// confirmation reuses the Patcher's classified fallback: a thread reply+// rejected with a "topic cannot receive this" Lark error retries once at+// the chat level so the confirmation is not lost.+func TestLarkOutcomeReplierIssueCreatedThreadFallback(t *testing.T) {+ t.Parallel()+ log := slog.New(slog.NewTextHandler(io.Discard, nil))+ stub := &stubAPIClientWithRecorder{configured: true, threadSendErr: errThreadReplyClassified}+ 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{AppID: "cli_x"}, threadedInboundMsg("oc_chat_42"), 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) != 2 {+ t.Fatalf("expected thread attempt + chat-level fallback (2 sends); got %d", len(stub.textOut))+ }+ if !stub.textOut[0].ReplyTarget.IsSet() {+ t.Errorf("first attempt should be the thread reply; got %+v", stub.textOut[0].ReplyTarget)+ }+ if stub.textOut[1].ReplyTarget.IsSet() {+ t.Errorf("fallback attempt must be chat-level; got %+v", stub.textOut[1].ReplyTarget)+ }+}++// TestLarkOutcomeReplierIssueCreatedNoFallbackOnAmbiguous verifies the+// /issue confirmation does NOT retry at chat level on an ambiguous+// transport failure, so the confirmation cannot be duplicated.+func TestLarkOutcomeReplierIssueCreatedNoFallbackOnAmbiguous(t *testing.T) {+ t.Parallel()+ log := slog.New(slog.NewTextHandler(io.Discard, nil))+ stub := &stubAPIClientWithRecorder{configured: true, threadSendErr: errThreadReplyTransport}+ 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{AppID: "cli_x"}, threadedInboundMsg("oc_chat_42"), DispatchResult{+ Outcome: OutcomeIngested,+ IssueID: mustUUID("22222222-2222-2222-2222-222222222222"),+ IssueNumber: 42,+ IssueIdentifier: "MUL-42",+ })++ stub.mu.Lock()+ defer stub.mu.Unlock()+ if len(stub.textOut) != 1 {+ t.Fatalf("expected a single thread attempt with no fallback; got %d sends", len(stub.textOut))+ }+ if !stub.textOut[0].ReplyTarget.IsSet() {+ t.Errorf("the single attempt should be the thread reply; got %+v", stub.textOut[0].ReplyTarget)+ }+}++// TestLarkOutcomeReplierNoticeThreadFallback verifies the offline /+// archived notice card shares the same classified fallback.+func TestLarkOutcomeReplierNoticeThreadFallback(t *testing.T) {+ t.Parallel()+ log := slog.New(slog.NewTextHandler(io.Discard, nil))+ stub := &stubAPIClientWithRecorder{configured: true, threadSendErr: errThreadReplyClassified}+ rep := NewLarkOutcomeReplier(OutcomeReplierConfig{+ APIClient: stub,+ BindingSvc: &BindingTokenService{},+ Credentials: stubCredentialsResolver{secret: "s"},+ Queries: stubReplierQueries{agent: db.Agent{Name: "Trump"}},+ PublicURL: "https://multica.test",+ Logger: log,+ })++ rep.Reply(context.Background(), db.LarkInstallation{AppID: "cli_x"}, threadedInboundMsg("oc_chat_1"), DispatchResult{Outcome: OutcomeAgentOffline})++ stub.mu.Lock()+ defer stub.mu.Unlock()+ if len(stub.interactiveOut) != 2 {+ t.Fatalf("expected thread attempt + chat-level fallback (2 cards); got %d", len(stub.interactiveOut))+ }+ if !stub.interactiveOut[0].ReplyTarget.IsSet() {+ t.Errorf("first attempt should be the thread reply; got %+v", stub.interactiveOut[0].ReplyTarget)+ }+ if stub.interactiveOut[1].ReplyTarget.IsSet() {+ t.Errorf("fallback attempt must be chat-level; got %+v", stub.interactiveOut[1].ReplyTarget)+ }+}++// TestLarkOutcomeReplierNoticeNoFallbackOnAmbiguous verifies the notice+// card is not retried at chat level on an ambiguous transport failure.+func TestLarkOutcomeReplierNoticeNoFallbackOnAmbiguous(t *testing.T) {+ t.Parallel()+ log := slog.New(slog.NewTextHandler(io.Discard, nil))+ stub := &stubAPIClientWithRecorder{configured: true, threadSendErr: errThreadReplyTransport}+ 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{}, threadedInboundMsg("oc_chat_arch"), DispatchResult{Outcome: OutcomeAgentArchived})++ stub.mu.Lock()+ defer stub.mu.Unlock()+ if len(stub.interactiveOut) != 1 {+ t.Fatalf("expected a single thread attempt with no fallback; got %d cards", len(stub.interactiveOut))+ }+ if !stub.interactiveOut[0].ReplyTarget.IsSet() {+ t.Errorf("the single attempt should be the thread reply; got %+v", stub.interactiveOut[0].ReplyTarget)+ }+}+func mustUUID(s string) pgtype.UUID {var u pgtype.UUIDif err := u.Scan(s); err != nil {diff --git a/server/internal/integrations/lark/ws_frame_decoder.go b/server/internal/integrations/lark/ws_frame_decoder.goindex 7cf41483db..991b89bb43 100644--- a/server/internal/integrations/lark/ws_frame_decoder.go+++ b/server/internal/integrations/lark/ws_frame_decoder.go@@ -82,6 +82,10 @@ func (d *LarkJSONFrameDecoder) Decode(payload []byte, inst db.LarkInstallation)// completeness / future thread handling.ParentID: evt.Message.ParentID,RootID: evt.Message.RootID,+ // thread_id is present only when the message lives inside a Lark+ // topic (话题). The outbound patcher uses it to decide whether to+ // reply back into that thread; empty means a normal chat message.+ ThreadID: evt.Message.ThreadID,}botUnionID := ""@@ -155,6 +159,10 @@ type larkMessageReceiveEvent struct {// RootID is the root of the reply tree.ParentID string `json:"parent_id"`RootID string `json:"root_id"`+ // ThreadID is present only for messages inside a Lark topic+ // (话题). Lark omits it for plain chat messages, so its presence+ // is the signal that an @-mention happened inside a thread.+ ThreadID string `json:"thread_id"`} `json:"message"`}diff --git a/server/internal/integrations/lark/ws_frame_decoder_test.go b/server/internal/integrations/lark/ws_frame_decoder_test.goindex 16388fa972..31caac823e 100644--- a/server/internal/integrations/lark/ws_frame_decoder_test.go+++ b/server/internal/integrations/lark/ws_frame_decoder_test.go@@ -560,3 +560,54 @@ func TestLarkJSONFrameDecoderCapturesReplyLinkage(t *testing.T) {t.Errorf("CommandBody = %q want 去实现", msg.CommandBody)}}++// TestLarkJSONFrameDecoderCapturesThreadID verifies thread_id from a+// topic (话题) message lands on the InboundMessage so the outbound+// patcher can reply back into the thread.+func TestLarkJSONFrameDecoderCapturesThreadID(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":"om_in_thread","chat_id":"c","chat_type":"group","message_type":"text",+ "content":"{\"text\":\"@bot help\"}",+ "thread_id":"omt_topic_123"+ }+ }+ }`)+ msg, ok, err := NewLarkJSONFrameDecoder().Decode(raw, db.LarkInstallation{BotOpenID: "ou_bot"})+ if err != nil || !ok {+ t.Fatalf("Decode ok=%v err=%v", ok, err)+ }+ if msg.ThreadID != "omt_topic_123" {+ t.Errorf("ThreadID = %q want omt_topic_123", msg.ThreadID)+ }+}++// TestLarkJSONFrameDecoderNonThreadHasEmptyThreadID verifies a normal+// chat message (no thread_id in the event) leaves ThreadID empty, which+// keeps the outbound on the unchanged chat-level send path.+func TestLarkJSONFrameDecoderNonThreadHasEmptyThreadID(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":"om_plain","chat_id":"c","chat_type":"group","message_type":"text",+ "content":"{\"text\":\"hi\"}"+ }+ }+ }`)+ msg, ok, err := NewLarkJSONFrameDecoder().Decode(raw, db.LarkInstallation{BotOpenID: "ou_bot"})+ if err != nil || !ok {+ t.Fatalf("Decode ok=%v err=%v", ok, err)+ }+ if msg.ThreadID != "" {+ t.Errorf("ThreadID = %q want empty for non-thread message", msg.ThreadID)+ }+}diff --git a/server/migrations/122_lark_chat_session_binding_thread_reply.down.sql b/server/migrations/122_lark_chat_session_binding_thread_reply.down.sqlnew file mode 100644index 0000000000..fd2aef5c90--- /dev/null+++ b/server/migrations/122_lark_chat_session_binding_thread_reply.down.sql@@ -0,0 +1,3 @@+ALTER TABLE lark_chat_session_binding+ DROP COLUMN IF EXISTS last_lark_message_id,+ DROP COLUMN IF EXISTS last_lark_thread_id;diff --git a/server/migrations/122_lark_chat_session_binding_thread_reply.up.sql b/server/migrations/122_lark_chat_session_binding_thread_reply.up.sqlnew file mode 100644index 0000000000..17f4b67e93--- /dev/null+++ b/server/migrations/122_lark_chat_session_binding_thread_reply.up.sql@@ -0,0 +1,23 @@+-- Thread-aware outbound: remember the most recent inbound trigger+-- message (and the Lark topic / thread it belongs to, if any) per chat+-- binding so the decoupled outbound patcher can thread its reply back+-- into the originating 话题 (thread) instead of always posting a fresh+-- message at the chat level.+--+-- The outbound side is event-driven and disconnected from the inbound+-- message: it only knows the chat_session → lark_chat_session_binding+-- (i.e. the lark_chat_id). Persisting the latest trigger here is what+-- lets EventChatDone resolve a reply target without plumbing the+-- message id through the whole task lifecycle.+--+-- Both columns are nullable:+-- * last_lark_message_id is the message_id the reply quotes / replies+-- to (Lark's reply endpoint keys off it).+-- * last_lark_thread_id is the message's thread_id; Lark only sends a+-- thread_id for messages that are part of a topic, so a NULL/empty+-- value means "the last trigger was a normal chat message" and the+-- outbound keeps the existing chat-level send behavior. Only when a+-- thread_id is present does the patcher switch to a thread reply.+ALTER TABLE lark_chat_session_binding+ ADD COLUMN last_lark_message_id TEXT,+ ADD COLUMN last_lark_thread_id TEXT;diff --git a/server/pkg/db/generated/lark.sql.go b/server/pkg/db/generated/lark.sql.goindex de0c86f6c8..d84f9b0a5e 100644--- a/server/pkg/db/generated/lark.sql.go+++ b/server/pkg/db/generated/lark.sql.go@@ -233,7 +233,7 @@ INSERT INTO lark_chat_session_binding () VALUES ($1, $2, $3, $4)-RETURNING id, chat_session_id, installation_id, lark_chat_id, lark_chat_type, created_at+RETURNING id, chat_session_id, installation_id, lark_chat_id, lark_chat_type, created_at, last_lark_message_id, last_lark_thread_id`type CreateLarkChatSessionBindingParams struct {@@ -261,6 +261,8 @@ func (q *Queries) CreateLarkChatSessionBinding(ctx context.Context, arg CreateLa&i.LarkChatID,&i.LarkChatType,&i.CreatedAt,+ &i.LastLarkMessageID,+ &i.LastLarkThreadID,)return i, err}@@ -458,7 +460,7 @@ func (q *Queries) DeleteLarkUserBinding(ctx context.Context, id pgtype.UUID) 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+SELECT id, chat_session_id, installation_id, lark_chat_id, lark_chat_type, created_at, last_lark_message_id, last_lark_thread_id FROM lark_chat_session_bindingWHERE installation_id = $1 AND lark_chat_id = $2`@@ -481,12 +483,14 @@ func (q *Queries) GetLarkChatSessionBinding(ctx context.Context, arg GetLarkChat&i.LarkChatID,&i.LarkChatType,&i.CreatedAt,+ &i.LastLarkMessageID,+ &i.LastLarkThreadID,)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+SELECT id, chat_session_id, installation_id, lark_chat_id, lark_chat_type, created_at, last_lark_message_id, last_lark_thread_id FROM lark_chat_session_bindingWHERE chat_session_id = $1`@@ -503,6 +507,8 @@ func (q *Queries) GetLarkChatSessionBindingBySession(ctx context.Context, chatSe&i.LarkChatID,&i.LarkChatType,&i.CreatedAt,+ &i.LastLarkMessageID,+ &i.LastLarkThreadID,)return i, err}@@ -1053,6 +1059,31 @@ func (q *Queries) SetLarkInstallationStatus(ctx context.Context, arg SetLarkInstreturn err}+const updateLarkChatSessionBindingReplyTarget = `-- name: UpdateLarkChatSessionBindingReplyTarget :exec+UPDATE lark_chat_session_binding+SET last_lark_message_id = $2,+ last_lark_thread_id = $3+WHERE chat_session_id = $1+`++type UpdateLarkChatSessionBindingReplyTargetParams struct {+ ChatSessionID pgtype.UUID `json:"chat_session_id"`+ LastLarkMessageID pgtype.Text `json:"last_lark_message_id"`+ LastLarkThreadID pgtype.Text `json:"last_lark_thread_id"`+}++// Records the most recent inbound trigger message + the Lark topic+// (thread) it belongs to, so the decoupled outbound patcher can thread+// its reply back into the originating 话题. Called on every ingested+// message (in the same tx as the chat_message write). last_lark_thread_id+// is NULL for non-thread messages, which keeps the outbound on the+// existing chat-level send path; a non-NULL value flips the next reply+// into a thread reply targeting last_lark_message_id.+func (q *Queries) UpdateLarkChatSessionBindingReplyTarget(ctx context.Context, arg UpdateLarkChatSessionBindingReplyTargetParams) error {+ _, err := q.db.Exec(ctx, updateLarkChatSessionBindingReplyTarget, arg.ChatSessionID, arg.LastLarkMessageID, arg.LastLarkThreadID)+ return err+}+const updateLarkOutboundCardStatus = `-- name: UpdateLarkOutboundCardStatus :execUPDATE lark_outbound_card_messageSET status = $2,diff --git a/server/pkg/db/generated/models.go b/server/pkg/db/generated/models.goindex e0ce7fc9d9..7fdbab1419 100644--- a/server/pkg/db/generated/models.go+++ b/server/pkg/db/generated/models.go@@ -452,12 +452,14 @@ type LarkBindingToken struct {}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"`+ 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"`+ LastLarkMessageID pgtype.Text `json:"last_lark_message_id"`+ LastLarkThreadID pgtype.Text `json:"last_lark_thread_id"`}type LarkInboundAudit struct {diff --git a/server/pkg/db/queries/lark.sql b/server/pkg/db/queries/lark.sqlindex 8183870107..a9c418d01b 100644--- a/server/pkg/db/queries/lark.sql+++ b/server/pkg/db/queries/lark.sql@@ -222,6 +222,19 @@ WHERE installation_id = $1 AND lark_chat_id = $2;SELECT * FROM lark_chat_session_bindingWHERE chat_session_id = $1;+-- name: UpdateLarkChatSessionBindingReplyTarget :exec+-- Records the most recent inbound trigger message + the Lark topic+-- (thread) it belongs to, so the decoupled outbound patcher can thread+-- its reply back into the originating 话题. Called on every ingested+-- message (in the same tx as the chat_message write). last_lark_thread_id+-- is NULL for non-thread messages, which keeps the outbound on the+-- existing chat-level send path; a non-NULL value flips the next reply+-- into a thread reply targeting last_lark_message_id.+UPDATE lark_chat_session_binding+SET last_lark_message_id = sqlc.narg('last_lark_message_id'),+ last_lark_thread_id = sqlc.narg('last_lark_thread_id')+WHERE chat_session_id = $1;+-- =====================-- lark_inbound_message_dedup-- =====================