Skip to content

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

Go

MUL-4753 Fix Lark recent context fetch degradation (#5401)

LiaoyuanNing@TTC51e4afc4800e
diff --git a/server/internal/integrations/lark/inbound_enricher.go b/server/internal/integrations/lark/inbound_enricher.go
index 9c573a779b..d6ed11ee37 100644
--- a/server/internal/integrations/lark/inbound_enricher.go
+++ b/server/internal/integrations/lark/inbound_enricher.go
@@ -2,8 +2,10 @@ package lark
import (
"context"
+ "errors"
"fmt"
"log/slog"
+ "net"
"sort"
"strconv"
"strings"
@@ -32,6 +34,22 @@ const defaultMaxForwardChildren = 100
// ACK budget (one list call, page_size 10).
const DefaultRecentContextSize = 10
+const (
+ recentContextEndpoint = "im/v1/messages.list"
+ recentContextMaxFetchAttempts = 2
+
+ recentContextFailureUnknown = "unknown"
+ recentContextFailureChannelUnbound = "channel_unbound"
+ recentContextFailureTimeout = "timeout"
+ recentContextFailurePermissionDenied = "permission_denied"
+ recentContextFailureMessageDeleted = "message_deleted"
+ recentContextFailureRateLimited = "rate_limited"
+ recentContextFailureTokenExpired = "token_expired"
+ recentContextFailureTemporary = "temporary"
+)
+
+var errRecentContextChannelUnbound = errors.New("lark enricher: missing chat_id for recent context")
+
// Enricher expands an inbound message's body with context the user
// EXPLICITLY attached — a quoted reply or a merged-and-forwarded bundle
// — by calling back into Lark's IM API. It runs after the (fast,
@@ -40,9 +58,9 @@ const DefaultRecentContextSize = 10
// conversation inline.
//
// It is best-effort by contract: every fetch failure degrades to a
-// visible placeholder block and Enrich NEVER returns an error or blocks
-// ingestion. A message with nothing to expand (no parent_id, not a
-// merge_forward) is returned untouched without any network call.
+// readable note or placeholder and Enrich NEVER returns an error or
+// blocks ingestion. A message with nothing to expand (no parent_id, not
+// a merge_forward) is returned untouched without any network call.
type Enricher interface {
Enrich(ctx context.Context, msg InboundMessage, creds InstallationCredentials) InboundMessage
}
@@ -190,7 +208,7 @@ func (e *inboundEnricher) Enrich(ctx context.Context, msg InboundMessage, creds
var b strings.Builder
if wantRecent {
if recentErr != nil {
- b.WriteString(recentContextErrorBlock())
+ b.WriteString(recentContextUnavailableLine(classifyRecentContextFetchError(recentErr).category))
} else if len(recentItems) > 0 {
b.WriteString(e.renderRecentContextBlock(recentItems, names))
}
@@ -275,21 +293,60 @@ func (e *inboundEnricher) resolveNames(ctx context.Context, creds InstallationCr
// oldest-first. The window is anchored to the trigger message's time so
// it captures the conversation up to the @-mention rather than whatever
// is newest by the time this fetch runs. A fetch failure is returned to
-// the caller (which renders the documented placeholder); it never blocks
-// ingestion.
+// the caller (which renders a safe, readable degradation note); it never
+// blocks ingestion.
func (e *inboundEnricher) fetchRecentItems(ctx context.Context, creds InstallationCredentials, msg InboundMessage) ([]LarkMessage, error) {
- items, err := e.client.ListChatMessages(ctx, creds, ListMessagesParams{
+ if msg.ChatID == "" {
+ classified := classifyRecentContextFetchError(errRecentContextChannelUnbound)
+ e.logRecentContextFetchFailure(msg, errRecentContextChannelUnbound, classified, 0)
+ return nil, errRecentContextChannelUnbound
+ }
+
+ params := ListMessagesParams{
ChatID: msg.ChatID,
PageSize: e.recentContextSize,
// Lark sends create_time as epoch millis; end_time wants seconds. A
// missing/unparseable time yields 0, which the client treats as
// "no end_time" (newest N).
EndTime: parseLarkMillis(msg.CreateTime) / 1000,
- })
- if err != nil {
- e.logger.Warn("lark enricher: recent context fetch failed",
- "chat_id", string(msg.ChatID), "err", err)
- return nil, err
+ }
+ var items []LarkMessage
+ var err error
+ for attempt := 1; attempt <= recentContextMaxFetchAttempts; attempt++ {
+ items, err = e.client.ListChatMessages(ctx, creds, params)
+ if err == nil {
+ if attempt > 1 {
+ e.logger.Info("lark enricher: recent context fetch recovered after retry",
+ "layer", "lark_inbound_enricher",
+ "endpoint", recentContextEndpoint,
+ "status", "recovered",
+ "attempts", attempt,
+ "chat_id", string(msg.ChatID),
+ "message_id", msg.MessageID)
+ }
+ break
+ }
+ classified := classifyRecentContextFetchError(err)
+ // A retry only helps while the shared enrichment budget still has
+ // time left. Both attempts reuse one ctx (ws_connector caps the
+ // whole Enrich at EnrichTimeout, ~2s), so once ctx is done a second
+ // call fails immediately — degrade now instead of burning a doomed
+ // request. This is why a first-attempt deadline never "recovers".
+ if !classified.retryable || attempt == recentContextMaxFetchAttempts || ctx.Err() != nil {
+ e.logRecentContextFetchFailure(msg, err, classified, attempt)
+ return nil, err
+ }
+ e.logger.Warn("lark enricher: recent context fetch failed; retrying",
+ "layer", "lark_inbound_enricher",
+ "endpoint", recentContextEndpoint,
+ "status", "retrying",
+ "category", classified.category,
+ "retryable", classified.retryable,
+ "attempt", attempt,
+ "next_attempt", attempt+1,
+ "chat_id", string(msg.ChatID),
+ "message_id", msg.MessageID,
+ "err", err)
}
exclude := map[string]bool{msg.MessageID: true}
@@ -312,6 +369,19 @@ func (e *inboundEnricher) fetchRecentItems(ctx context.Context, creds Installati
return kept, nil
}
+func (e *inboundEnricher) logRecentContextFetchFailure(msg InboundMessage, err error, classified recentContextFetchClassification, attempts int) {
+ e.logger.Warn("lark enricher: recent context fetch failed",
+ "layer", "lark_inbound_enricher",
+ "endpoint", recentContextEndpoint,
+ "status", "failed",
+ "category", classified.category,
+ "retryable", classified.retryable,
+ "attempts", attempts,
+ "chat_id", string(msg.ChatID),
+ "message_id", msg.MessageID,
+ "err", err)
+}
+
// renderRecentContextBlock renders the surrounding conversation as a
// <recent_context> block: one "[<speaker>]: <text>" line per message,
// oldest-first, speakers labeled with real names from `names` (falling
@@ -337,8 +407,90 @@ func (e *inboundEnricher) renderRecentContextBlock(kept []LarkMessage, names map
len(kept), strings.Join(lines, "\n"))
}
-func recentContextErrorBlock() string {
- return "<recent_context type=\"error\">[unable to fetch recent context]</recent_context>"
+type recentContextFetchClassification struct {
+ category string
+ retryable bool
+}
+
+func classifyRecentContextFetchError(err error) recentContextFetchClassification {
+ if err == nil {
+ return recentContextFetchClassification{category: recentContextFailureUnknown}
+ }
+ if errors.Is(err, errRecentContextChannelUnbound) {
+ return recentContextFetchClassification{category: recentContextFailureChannelUnbound}
+ }
+ var apiErr *APIError
+ if errors.As(err, &apiErr) {
+ return classifyRecentContextAPIError(apiErr.Code, apiErr.Msg)
+ }
+ var netErr net.Error
+ if errors.Is(err, context.DeadlineExceeded) ||
+ (errors.As(err, &netErr) && netErr.Timeout()) {
+ return recentContextFetchClassification{category: recentContextFailureTimeout, retryable: true}
+ }
+
+ msg := strings.ToLower(err.Error())
+ switch {
+ case strings.Contains(msg, "missing chat_id") || strings.Contains(msg, "missing chat id"):
+ return recentContextFetchClassification{category: recentContextFailureChannelUnbound}
+ case containsAny(msg, "code=99991002", "code=230001", "no permission", "permission denied", "insufficient permissions", "forbidden", "http 403"):
+ return recentContextFetchClassification{category: recentContextFailurePermissionDenied}
+ case containsAny(msg, "code=230110", "code=230011", "code=230050", "deleted", "recalled", "not visible", "invisible"):
+ return recentContextFetchClassification{category: recentContextFailureMessageDeleted}
+ case containsAny(msg, "code=99991663", "code=99991664"):
+ return recentContextFetchClassification{category: recentContextFailureTokenExpired, retryable: true}
+ case containsAny(msg, "code=230020", "rate limit", "rate_limit", "http 429"):
+ // Not retryable: the client drops Retry-After, and an immediate
+ // second call within the same budget almost always re-hits the
+ // limit while doubling list load on an already-throttled tenant.
+ return recentContextFetchClassification{category: recentContextFailureRateLimited}
+ case containsAny(msg, "deadline exceeded", "timeout", "timed out"):
+ return recentContextFetchClassification{category: recentContextFailureTimeout, retryable: true}
+ case containsAny(msg, "http 500", "http 502", "http 503", "http 504", "connection reset", "connection refused", "temporary"):
+ return recentContextFetchClassification{category: recentContextFailureTemporary, retryable: true}
+ default:
+ return recentContextFetchClassification{category: recentContextFailureUnknown}
+ }
+}
+
+func classifyRecentContextAPIError(code int, msg string) recentContextFetchClassification {
+ switch {
+ case code == 99991002 || code == 230001:
+ return recentContextFetchClassification{category: recentContextFailurePermissionDenied}
+ case code == 230110 || code == 230011 || code == 230050:
+ return recentContextFetchClassification{category: recentContextFailureMessageDeleted}
+ case isTokenError(code):
+ return recentContextFetchClassification{category: recentContextFailureTokenExpired, retryable: true}
+ case code == 230020:
+ // See classifyRecentContextFetchError: rate limits degrade rather
+ // than retry, since the client drops Retry-After.
+ return recentContextFetchClassification{category: recentContextFailureRateLimited}
+ }
+ return classifyRecentContextFetchError(errors.New(msg))
+}
+
+func containsAny(s string, needles ...string) bool {
+ for _, needle := range needles {
+ if strings.Contains(s, needle) {
+ return true
+ }
+ }
+ return false
+}
+
+func recentContextUnavailableLine(category string) string {
+ switch category {
+ case recentContextFailureChannelUnbound:
+ return "[Recent Lark context unavailable: chat binding is missing. Continuing with the latest message.]"
+ case recentContextFailurePermissionDenied:
+ return "[Recent Lark context unavailable: the bot cannot read this chat history. Continuing with the latest message.]"
+ case recentContextFailureMessageDeleted:
+ return "[Recent Lark context unavailable: the referenced chat history is deleted or no longer visible. Continuing with the latest message.]"
+ case recentContextFailureTimeout, recentContextFailureRateLimited, recentContextFailureTokenExpired, recentContextFailureTemporary:
+ return "[Recent Lark context temporarily unavailable; continuing with the latest message.]"
+ default:
+ return "[Recent Lark context unavailable; continuing with the latest message.]"
+ }
}
// renderQuotedBlock renders a <quoted_message> block from the already-
diff --git a/server/internal/integrations/lark/inbound_enricher_recent_test.go b/server/internal/integrations/lark/inbound_enricher_recent_test.go
index 25b9be79e3..42c2c20528 100644
--- a/server/internal/integrations/lark/inbound_enricher_recent_test.go
+++ b/server/internal/integrations/lark/inbound_enricher_recent_test.go
@@ -1,7 +1,9 @@
package lark
import (
+ "context"
"errors"
+ "strings"
"testing"
)
@@ -23,6 +25,14 @@ func groupCfg() InboundEnricherConfig {
return InboundEnricherConfig{RecentContextSize: DefaultRecentContextSize}
}
+func assertNoRecentContextFetchPlaceholder(t *testing.T, body string) {
+ t.Helper()
+ if strings.Contains(body, `<recent_context type="error">`) ||
+ strings.Contains(body, "[unable to fetch recent context]") {
+ t.Fatalf("recent context fetch placeholder leaked into body: %q", body)
+ }
+}
+
// TestEnrichRecentContextGroupMention is the MUL-3084 core: a bare @-bot
// mention in a group (no quote, no forward) gets the surrounding
// conversation inlined as a <recent_context> block ahead of the user's
@@ -77,6 +87,37 @@ func TestEnrichRecentContextGroupMention(t *testing.T) {
}
}
+// TestEnrichRecentContextRendersDeletedItems keeps deleted messages
+// user-readable when Lark returns them inside the recent window.
+func TestEnrichRecentContextRendersDeletedItems(t *testing.T) {
+ t.Parallel()
+ fake := newEnricherFake()
+ fake.byChat["oc_g"] = []LarkMessage{
+ textMsg("om_trigger", "ou_user", "总结一下", "3000"),
+ {MessageID: "om_deleted", MessageType: "text", Deleted: true, SenderID: "ou_alice", SenderType: "user", CreateTime: "1000"},
+ }
+ in := InboundMessage{
+ MessageType: "text",
+ MessageID: "om_trigger",
+ ChatID: "oc_g",
+ ChatType: ChatTypeGroup,
+ AddressedToBot: true,
+ Body: "总结一下",
+ CreateTime: "3000",
+ }
+
+ out := enrich(t, fake, in, groupCfg())
+
+ want := `<recent_context count="1">
+[User 1]: [deleted message]
+</recent_context>
+
+总结一下`
+ if out.Body != want {
+ t.Errorf("body\n got = %q\nwant = %q", out.Body, want)
+ }
+}
+
// TestEnrichRecentContextResolvesNames covers the MUL-3084 follow-up:
// speakers in <recent_context> show real display names (not User 1/2),
// and the user's own @-message is labeled with the sender's name so the
@@ -271,8 +312,9 @@ func TestEnrichForwardedResolvesNames(t *testing.T) {
}
}
-// TestEnrichRecentContextFetchError degrades to a visible placeholder on
-// a list failure, without blocking ingestion or dropping the user's body.
+// TestEnrichRecentContextFetchError degrades to a plain, user-readable
+// note on a list failure without leaking the old internal XML placeholder
+// or dropping the user's body.
func TestEnrichRecentContextFetchError(t *testing.T) {
t.Parallel()
fake := newEnricherFake()
@@ -288,12 +330,266 @@ func TestEnrichRecentContextFetchError(t *testing.T) {
out := enrich(t, fake, in, groupCfg())
- want := `<recent_context type="error">[unable to fetch recent context]</recent_context>
+ want := `[Recent Lark context unavailable; continuing with the latest message.]
+
+在干嘛`
+ if out.Body != want {
+ t.Errorf("body\n got = %q\nwant = %q", out.Body, want)
+ }
+ assertNoRecentContextFetchPlaceholder(t, out.Body)
+ if len(fake.listCalls) != 1 {
+ t.Errorf("unknown error should not be retried; got calls %v", fake.listCalls)
+ }
+}
+
+// TestEnrichRecentContextRetriesTransientNetworkError pins the bounded
+// retry on a transient failure that leaves the shared enrichment budget
+// intact: one retry, and a successful retry renders the real
+// recent_context block instead of degrading. It deliberately does NOT use
+// context.DeadlineExceeded — that error means the shared ctx is already
+// spent, so a second attempt could never recover in production (see
+// TestEnrichRecentContextDoneContextDoesNotRetry).
+func TestEnrichRecentContextRetriesTransientNetworkError(t *testing.T) {
+ t.Parallel()
+ fake := newEnricherFake()
+ fake.errSeqChat["oc_g"] = []error{errors.New("connection reset by peer"), nil}
+ fake.byChat["oc_g"] = []LarkMessage{
+ textMsg("om_trigger", "ou_user", "总结一下", "3000"),
+ textMsg("om_a", "ou_alice", "我改完了登录页", "1000"),
+ }
+ in := InboundMessage{
+ MessageType: "text",
+ MessageID: "om_trigger",
+ ChatID: "oc_g",
+ ChatType: ChatTypeGroup,
+ AddressedToBot: true,
+ Body: "总结一下",
+ CreateTime: "3000",
+ }
+
+ out := enrich(t, fake, in, groupCfg())
+
+ want := `<recent_context count="1">
+[User 1]: 我改完了登录页
+</recent_context>
+
+总结一下`
+ if out.Body != want {
+ t.Errorf("body\n got = %q\nwant = %q", out.Body, want)
+ }
+ if len(fake.listCalls) != 2 {
+ t.Errorf("transient network error should retry once; got calls %v", fake.listCalls)
+ }
+}
+
+// TestEnrichRecentContextDoneContextDoesNotRetry locks Must-fix #1: when
+// the shared enrichment budget is already spent, a retryable first failure
+// must degrade after ONE attempt rather than fire a second call that can
+// only fail again. A pre-cancelled context stands in for that exhausted
+// budget (the production entry point wraps Enrich in a ~2s deadline).
+func TestEnrichRecentContextDoneContextDoesNotRetry(t *testing.T) {
+ t.Parallel()
+ fake := newEnricherFake()
+ // Would normally be retried (transient), but the context is done.
+ fake.errByChat["oc_g"] = errors.New("connection reset by peer")
+ in := InboundMessage{
+ MessageType: "text",
+ MessageID: "om_trigger",
+ ChatID: "oc_g",
+ ChatType: ChatTypeGroup,
+ AddressedToBot: true,
+ Body: "在干嘛",
+ }
+
+ ctx, cancel := context.WithCancel(context.Background())
+ cancel()
+ e := NewInboundEnricher(fake, groupCfg())
+ out := e.Enrich(ctx, in, InstallationCredentials{AppID: "a", AppSecret: "s"})
+
+ want := `[Recent Lark context temporarily unavailable; continuing with the latest message.]
在干嘛`
if out.Body != want {
t.Errorf("body\n got = %q\nwant = %q", out.Body, want)
}
+ assertNoRecentContextFetchPlaceholder(t, out.Body)
+ if len(fake.listCalls) != 1 {
+ t.Errorf("a done context must not retry; got calls %v", fake.listCalls)
+ }
+}
+
+// TestEnrichRecentContextRateLimitedDoesNotRetry locks Must-fix #2: a rate
+// limit degrades immediately instead of retrying. It uses the PRODUCTION
+// error shape — ListChatMessages returns a plain wrapped error string, not
+// an *APIError — so the string classifier path (the one prod actually
+// hits) is what gets pinned.
+func TestEnrichRecentContextRateLimitedDoesNotRetry(t *testing.T) {
+ t.Parallel()
+ fake := newEnricherFake()
+ fake.errByChat["oc_g"] = errors.New(`lark http client: list chat messages: code=230020 msg="rate limit exceeded"`)
+ in := InboundMessage{
+ MessageType: "text",
+ MessageID: "om_trigger",
+ ChatID: "oc_g",
+ ChatType: ChatTypeGroup,
+ AddressedToBot: true,
+ Body: "在干嘛",
+ }
+
+ out := enrich(t, fake, in, groupCfg())
+
+ want := `[Recent Lark context temporarily unavailable; continuing with the latest message.]
+
+在干嘛`
+ if out.Body != want {
+ t.Errorf("body\n got = %q\nwant = %q", out.Body, want)
+ }
+ assertNoRecentContextFetchPlaceholder(t, out.Body)
+ if len(fake.listCalls) != 1 {
+ t.Errorf("rate limit should not retry; got calls %v", fake.listCalls)
+ }
+}
+
+// TestEnrichRecentContextProductionErrorShapes covers the classifier on
+// the real error shape ListChatMessages returns: a plain wrapped error
+// string ("...: code=%d msg=%q"), NOT an *APIError. The typed-APIError
+// tests above exercise classifyRecentContextAPIError, but production
+// traffic only ever reaches the string path, so pin that too — including
+// that token errors DO retry (client refreshes the token) while permission
+// and deleted errors do not.
+func TestEnrichRecentContextProductionErrorShapes(t *testing.T) {
+ t.Parallel()
+ cases := []struct {
+ name string
+ err error
+ wantLine string
+ wantCalls int
+ }{
+ {
+ name: "permission_denied",
+ err: errors.New(`lark http client: list chat messages: code=99991002 msg="no permission"`),
+ wantLine: "[Recent Lark context unavailable: the bot cannot read this chat history. Continuing with the latest message.]",
+ wantCalls: 1,
+ },
+ {
+ name: "message_deleted",
+ err: errors.New(`lark http client: list chat messages: code=230110 msg="message has been deleted"`),
+ wantLine: "[Recent Lark context unavailable: the referenced chat history is deleted or no longer visible. Continuing with the latest message.]",
+ wantCalls: 1,
+ },
+ {
+ name: "token_expired_retries_then_degrades",
+ err: errors.New(`lark http client: list chat messages: code=99991663 msg="access token expired"`),
+ wantLine: "[Recent Lark context temporarily unavailable; continuing with the latest message.]",
+ wantCalls: 2,
+ },
+ }
+ for _, tc := range cases {
+ tc := tc
+ t.Run(tc.name, func(t *testing.T) {
+ t.Parallel()
+ fake := newEnricherFake()
+ fake.errByChat["oc_g"] = tc.err
+ in := InboundMessage{
+ MessageType: "text",
+ MessageID: "om_trigger",
+ ChatID: "oc_g",
+ ChatType: ChatTypeGroup,
+ AddressedToBot: true,
+ Body: "在干嘛",
+ }
+
+ out := enrich(t, fake, in, groupCfg())
+
+ want := tc.wantLine + "\n\n在干嘛"
+ if out.Body != want {
+ t.Errorf("body\n got = %q\nwant = %q", out.Body, want)
+ }
+ assertNoRecentContextFetchPlaceholder(t, out.Body)
+ if len(fake.listCalls) != tc.wantCalls {
+ t.Errorf("%s: got calls %v want %d", tc.name, fake.listCalls, tc.wantCalls)
+ }
+ })
+ }
+}
+
+func TestEnrichRecentContextPermissionDeniedDoesNotRetry(t *testing.T) {
+ t.Parallel()
+ fake := newEnricherFake()
+ fake.errByChat["oc_g"] = &APIError{Op: "list chat messages", Code: 99991002, Msg: "no permission"}
+ in := InboundMessage{
+ MessageType: "text",
+ MessageID: "om_trigger",
+ ChatID: "oc_g",
+ ChatType: ChatTypeGroup,
+ AddressedToBot: true,
+ Body: "查一下上下文",
+ }
+
+ out := enrich(t, fake, in, groupCfg())
+
+ want := `[Recent Lark context unavailable: the bot cannot read this chat history. Continuing with the latest message.]
+
+查一下上下文`
+ if out.Body != want {
+ t.Errorf("body\n got = %q\nwant = %q", out.Body, want)
+ }
+ assertNoRecentContextFetchPlaceholder(t, out.Body)
+ if len(fake.listCalls) != 1 {
+ t.Errorf("permission denial should not retry; got calls %v", fake.listCalls)
+ }
+}
+
+func TestEnrichRecentContextDeletedOrInvisibleError(t *testing.T) {
+ t.Parallel()
+ fake := newEnricherFake()
+ fake.errByChat["oc_g"] = &APIError{Op: "list chat messages", Code: 230110, Msg: "message has been deleted"}
+ in := InboundMessage{
+ MessageType: "text",
+ MessageID: "om_trigger",
+ ChatID: "oc_g",
+ ChatType: ChatTypeGroup,
+ AddressedToBot: true,
+ Body: "接着处理",
+ }
+
+ out := enrich(t, fake, in, groupCfg())
+
+ want := `[Recent Lark context unavailable: the referenced chat history is deleted or no longer visible. Continuing with the latest message.]
+
+接着处理`
+ if out.Body != want {
+ t.Errorf("body\n got = %q\nwant = %q", out.Body, want)
+ }
+ assertNoRecentContextFetchPlaceholder(t, out.Body)
+ if len(fake.listCalls) != 1 {
+ t.Errorf("deleted/invisible error should not retry; got calls %v", fake.listCalls)
+ }
+}
+
+func TestEnrichRecentContextMissingChatBinding(t *testing.T) {
+ t.Parallel()
+ fake := newEnricherFake()
+ in := InboundMessage{
+ MessageType: "text",
+ MessageID: "om_trigger",
+ ChatType: ChatTypeGroup,
+ AddressedToBot: true,
+ Body: "查一下上下文",
+ }
+
+ out := enrich(t, fake, in, groupCfg())
+
+ want := `[Recent Lark context unavailable: chat binding is missing. Continuing with the latest message.]
+
+查一下上下文`
+ if out.Body != want {
+ t.Errorf("body\n got = %q\nwant = %q", out.Body, want)
+ }
+ assertNoRecentContextFetchPlaceholder(t, out.Body)
+ if len(fake.listCalls) != 0 {
+ t.Errorf("missing chat binding should not call ListChatMessages; got %v", fake.listCalls)
+ }
}
// TestEnrichRecentContextEmptyWindow emits NO block (not an empty one)
diff --git a/server/internal/integrations/lark/inbound_enricher_test.go b/server/internal/integrations/lark/inbound_enricher_test.go
index fa0966791d..6031ba18c7 100644
--- a/server/internal/integrations/lark/inbound_enricher_test.go
+++ b/server/internal/integrations/lark/inbound_enricher_test.go
@@ -22,6 +22,7 @@ type enricherFakeClient struct {
// ListChatMessages canned results + recorder, keyed by chat id.
byChat map[ChatID][]LarkMessage
errByChat map[ChatID]error
+ errSeqChat map[ChatID][]error
listCalls []ChatID
listParams []ListMessagesParams
@@ -39,6 +40,7 @@ func newEnricherFake() *enricherFakeClient {
errByID: map[string]error{},
byChat: map[ChatID][]LarkMessage{},
errByChat: map[ChatID]error{},
+ errSeqChat: map[ChatID][]error{},
}
}
@@ -53,6 +55,13 @@ func (f *enricherFakeClient) GetMessage(ctx context.Context, creds InstallationC
func (f *enricherFakeClient) ListChatMessages(ctx context.Context, creds InstallationCredentials, p ListMessagesParams) ([]LarkMessage, error) {
f.listCalls = append(f.listCalls, p.ChatID)
f.listParams = append(f.listParams, p)
+ if seq := f.errSeqChat[p.ChatID]; len(seq) > 0 {
+ err := seq[0]
+ f.errSeqChat[p.ChatID] = seq[1:]
+ if err != nil {
+ return nil, err
+ }
+ }
if e, ok := f.errByChat[p.ChatID]; ok {
return nil, e
}