Skip to content

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

Go

MUL-7076 fix(lark): fallback to group notice when binding card unavailable (#8064)

m2keloopa124a5b80418
diff --git a/server/internal/integrations/lark/http_client.go b/server/internal/integrations/lark/http_client.go
index 80a1e6246f..12df677269 100644
--- a/server/internal/integrations/lark/http_client.go
+++ b/server/internal/integrations/lark/http_client.go
@@ -89,6 +89,11 @@ const (
// replay, while leaving it out would cost another wedged cache.
codeTenantTokenInvalid = 99991663
codeAppTokenInvalid = 99991664
+
+ // codeNoAvailability means the bot cannot send a private message to the
+ // user because they are outside the bot's visible scope. Keep the
+ // group-level reply path visible so users still get guidance.
+ codeNoAvailability = 230013
)
// HTTPClientConfig configures the production Lark HTTP APIClient.
@@ -531,7 +536,7 @@ func (c *httpAPIClient) SendBindingPromptCard(ctx context.Context, p BindingProm
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 &APIError{Op: "send binding prompt", Code: resp.Code, Msg: resp.Msg}
}
return nil
}
diff --git a/server/internal/integrations/lark/http_client_test.go b/server/internal/integrations/lark/http_client_test.go
index b6ee769492..e94335f8d0 100644
--- a/server/internal/integrations/lark/http_client_test.go
+++ b/server/internal/integrations/lark/http_client_test.go
@@ -234,6 +234,13 @@ 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")
+ }
+}
+
func TestHTTPClient_DownloadMessageResource(t *testing.T) {
fake := newLarkFake(t)
fake.stubToken("tok_resource", 7200)
@@ -429,6 +436,16 @@ func TestHTTPClient_DownloadMessageResourceBusinessError(t *testing.T) {
}
}
+// 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
@@ -1090,6 +1107,36 @@ func TestHTTPClient_SendBindingPromptCard_HappyPath(t *testing.T) {
}
}
+func TestHTTPClient_SendBindingPromptCard_NoAvailabilityReturnsAPIError(t *testing.T) {
+ fake := newLarkFake(t)
+ fake.stubToken("tok_bind_no_avail", 7200)
+
+ fake.mux.HandleFunc("/open-apis/im/v1/messages", func(w http.ResponseWriter, r *http.Request) {
+ fake.bindN.Add(1)
+ writeJSON(w, map[string]any{"code": 230013, "msg": "Bot has NO availability to this user.", "data": map[string]any{}})
+ })
+
+ c := newTestClient(fake, time.Now)
+ err := c.SendBindingPromptCard(context.Background(), BindingPromptParams{
+ InstallationID: testCreds(),
+ OpenID: OpenID("ou_user_1"),
+ BindURL: "https://multica.test/lark/bind?token=abc",
+ })
+ if err == nil {
+ t.Fatal("expected SendBindingPromptCard to fail")
+ }
+ apiErr, ok := err.(*APIError)
+ if !ok {
+ t.Fatalf("expected APIError, got %T", err)
+ }
+ if apiErr.Code != 230013 {
+ t.Fatalf("expected code=230013, got %d", apiErr.Code)
+ }
+ if apiErr.Msg != "Bot has NO availability to this user." {
+ t.Fatalf("unexpected msg: %q", apiErr.Msg)
+ }
+}
+
func TestHTTPClient_TokenEndpointError(t *testing.T) {
fake := newLarkFake(t)
fake.stubTokenError(10003, "invalid app_id or app_secret")
diff --git a/server/internal/integrations/lark/outcome_replier.go b/server/internal/integrations/lark/outcome_replier.go
index 4ba0035755..32d26bfc27 100644
--- a/server/internal/integrations/lark/outcome_replier.go
+++ b/server/internal/integrations/lark/outcome_replier.go
@@ -156,7 +156,7 @@ func NewLarkOutcomeReplier(cfg OutcomeReplierConfig) OutcomeReplier {
func (r *LarkOutcomeReplier) Reply(ctx context.Context, inst Installation, msg InboundMessage, res DispatchResult) {
switch res.Outcome {
case OutcomeNeedsBinding:
- if err := r.sendBindingPrompt(ctx, inst, res); err != nil {
+ if err := r.sendBindingPrompt(ctx, inst, msg, res); err != nil {
r.log.Warn("lark outcome replier: binding prompt failed",
"installation_id", uuidString(inst.ID),
"open_id", string(res.SenderOpenID),
@@ -223,7 +223,7 @@ func (r *LarkOutcomeReplier) Reply(ctx context.Context, inst Installation, msg I
}
}
-func (r *LarkOutcomeReplier) sendBindingPrompt(ctx context.Context, inst Installation, res DispatchResult) error {
+func (r *LarkOutcomeReplier) sendBindingPrompt(ctx context.Context, inst Installation, msg InboundMessage, res DispatchResult) error {
if res.SenderOpenID == "" {
return errors.New("missing sender open_id")
}
@@ -239,11 +239,24 @@ func (r *LarkOutcomeReplier) sendBindingPrompt(ctx context.Context, inst Install
if err != nil {
return err
}
- return r.client.SendBindingPromptCard(ctx, BindingPromptParams{
+ if err := r.client.SendBindingPromptCard(ctx, BindingPromptParams{
InstallationID: creds,
OpenID: res.SenderOpenID,
BindURL: bindURL,
- })
+ }); err != nil {
+ if msg.ChatType == ChatTypeGroup && isBindingPromptUnavailable(err) {
+ if fallbackErr := r.sendChatNotice(ctx, inst, msg, bindingPromptUnavailableCopy); fallbackErr != nil {
+ return fmt.Errorf("send binding prompt fallback failed after private prompt unavailable: %v: %w", err, fallbackErr)
+ }
+ return nil
+ }
+ return err
+ }
+ return nil
+}
+
+func isBindingPromptUnavailable(err error) bool {
+ return larkErrorCode(err) == codeNoAvailability
}
// sendIssueOutcome posts either the created confirmation or active-duplicate
@@ -411,10 +424,11 @@ func renderNoticeCard(header, body string) (string, error) {
// 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 已被归档,无法继续处理消息。请联系工作区管理员恢复或重新绑定。"
- freshPendingCopy = "✅ 已准备从空上下文运行。你的下一条聊天消息仍会进入当前对话,但不会带上之前的上下文。"
- chatStartedCopy = "✅ 已新建 Multica 对话。你的下一条消息会进入该对话。"
- issueUsageCopy = "请填写任务标题,格式如下:\n\n`/issue <标题>`\n`[描述]`(可选)"
- issueUsageWithMediaCopy = "请添加标题,并与图片或视频一起重新发送(*图片或视频可以位于命令之前或之后*):\n\n`/issue <标题>`\n`[描述]`(可选)"
+ agentOfflineCopy = "Agent 当前离线,消息已记录。下次 daemon 上线后会自动继续处理。"
+ agentArchivedCopy = "这个 Agent 已被归档,无法继续处理消息。请联系工作区管理员恢复或重新绑定。"
+ freshPendingCopy = "✅ 已准备从空上下文运行。你的下一条聊天消息仍会进入当前对话,但不会带上之前的上下文。"
+ chatStartedCopy = "✅ 已新建 Multica 对话。你的下一条消息会进入该对话。"
+ issueUsageCopy = "请填写任务标题,格式如下:\n\n`/issue <标题>`\n`[描述]`(可选)"
+ issueUsageWithMediaCopy = "请添加标题,并与图片或视频一起重新发送(*图片或视频可以位于命令之前或之后*):\n\n`/issue <标题>`\n`[描述]`(可选)"
+ bindingPromptUnavailableCopy = "你还未绑定 Multica 账户,绑定卡片未能发送到你的私聊。\n请先打开机器人对话并发送一条消息,再回到群里重试;仍失败请联系管理员检查应用可用范围。"
)
diff --git a/server/internal/integrations/lark/outcome_replier_test.go b/server/internal/integrations/lark/outcome_replier_test.go
index fc544a197a..8c293e4014 100644
--- a/server/internal/integrations/lark/outcome_replier_test.go
+++ b/server/internal/integrations/lark/outcome_replier_test.go
@@ -73,10 +73,10 @@ func (s *stubAPIClientWithRecorder) SendMarkdownCard(ctx context.Context, p Send
func (s *stubAPIClientWithRecorder) SendBindingPromptCard(ctx context.Context, p BindingPromptParams) error {
s.mu.Lock()
defer s.mu.Unlock()
+ s.bindingCalls = append(s.bindingCalls, p)
if s.bindingErr != nil {
return s.bindingErr
}
- s.bindingCalls = append(s.bindingCalls, p)
return nil
}
@@ -360,6 +360,227 @@ func TestLarkOutcomeReplierUsesAppURLForWebLinks(t *testing.T) {
}
}
+func TestLarkOutcomeReplierNeedsBindingFallsBackToGroupNoticeWhenPrivateUnavailable(t *testing.T) {
+ t.Parallel()
+ log := slog.New(slog.NewTextHandler(io.Discard, nil))
+ stub := &stubAPIClientWithRecorder{
+ configured: true,
+ bindingErr: &APIError{
+ Op: "send binding prompt",
+ Code: codeNoAvailability,
+ Msg: "Bot has NO availability to this user.",
+ },
+ }
+ rep := NewLarkOutcomeReplier(OutcomeReplierConfig{
+ APIClient: stub,
+ BindingSvc: fakeBindingMinter{raw: "token"},
+ Credentials: stubCredentialsResolver{secret: "s"},
+ Queries: stubReplierQueries{},
+ AppURL: "https://multica.test",
+ Logger: log,
+ })
+
+ inst := Installation{AppID: "cli_x"}
+ inst.ID = mustUUID("11111111-1111-1111-1111-111111111111")
+ inst.WorkspaceID = mustUUID("33333333-3333-3333-3333-333333333333")
+ rep.Reply(context.Background(), inst, InboundMessage{ChatID: "oc_chat", ChatType: ChatTypeGroup, SenderOpenID: "ou_user"},
+ DispatchResult{Outcome: OutcomeNeedsBinding, SenderOpenID: "ou_user"})
+
+ stub.mu.Lock()
+ defer stub.mu.Unlock()
+ if len(stub.bindingCalls) != 1 {
+ t.Fatalf("expected one binding prompt attempt, got %d", len(stub.bindingCalls))
+ }
+ if got := stub.bindingCalls[0].OpenID; got != "ou_user" {
+ t.Fatalf("binding prompt should target sender open_id; got %q", got)
+ }
+ if len(stub.interactiveOut) != 1 {
+ t.Fatalf("expected one fallback card, got %d", len(stub.interactiveOut))
+ }
+ if !strings.Contains(stub.interactiveOut[0].CardJSON, "请先打开机器人对话并发送一条消息,再回到群里重试") {
+ t.Fatalf("fallback card should contain private-send-unavailable guidance: %q", stub.interactiveOut[0].CardJSON)
+ }
+}
+
+func TestLarkOutcomeReplierNeedsBindingFallsBackForStatusErrorNoAvailabilityCode(t *testing.T) {
+ t.Parallel()
+ log := slog.New(slog.NewTextHandler(io.Discard, nil))
+ stub := &stubAPIClientWithRecorder{
+ configured: true,
+ bindingErr: &larkAPIStatusError{
+ StatusCode: 400,
+ Code: codeNoAvailability,
+ Msg: "localized or otherwise arbitrary copy",
+ Raw: `{"code":230013,"msg":"localized or otherwise arbitrary copy"}`,
+ },
+ }
+ inst := Installation{AppID: "cli_x"}
+ inst.ID = mustUUID("11111111-1111-1111-1111-111111111111")
+ inst.WorkspaceID = mustUUID("33333333-3333-3333-3333-333333333333")
+ rep := NewLarkOutcomeReplier(OutcomeReplierConfig{
+ APIClient: stub,
+ BindingSvc: fakeBindingMinter{raw: "token"},
+ Credentials: stubCredentialsResolver{secret: "s"},
+ Queries: stubReplierQueries{},
+ AppURL: "https://multica.test",
+ Logger: log,
+ })
+
+ rep.Reply(context.Background(), inst, InboundMessage{ChatID: "oc_chat", ChatType: ChatTypeGroup, SenderOpenID: "ou_user"},
+ DispatchResult{Outcome: OutcomeNeedsBinding, SenderOpenID: "ou_user"})
+
+ stub.mu.Lock()
+ defer stub.mu.Unlock()
+ if len(stub.bindingCalls) != 1 {
+ t.Fatalf("expected one binding prompt attempt, got %d", len(stub.bindingCalls))
+ }
+ if len(stub.interactiveOut) != 1 {
+ t.Fatalf("expected one fallback card, got %d", len(stub.interactiveOut))
+ }
+}
+
+func TestLarkOutcomeReplierNeedsBindingDoesNotFallbackForUnstructuredNoAvailabilityText(t *testing.T) {
+ t.Parallel()
+ log := slog.New(slog.NewTextHandler(io.Discard, nil))
+ stub := &stubAPIClientWithRecorder{
+ configured: true,
+ bindingErr: errors.New("proxy reported no availability while retrying"),
+ }
+ rep := NewLarkOutcomeReplier(OutcomeReplierConfig{
+ APIClient: stub,
+ BindingSvc: fakeBindingMinter{raw: "token"},
+ Credentials: stubCredentialsResolver{secret: "s"},
+ Queries: stubReplierQueries{},
+ AppURL: "https://multica.test",
+ Logger: log,
+ })
+
+ rep.Reply(context.Background(), Installation{}, InboundMessage{ChatID: "oc_chat", ChatType: ChatTypeGroup, SenderOpenID: "ou_user"},
+ DispatchResult{Outcome: OutcomeNeedsBinding, SenderOpenID: "ou_user"})
+
+ stub.mu.Lock()
+ defer stub.mu.Unlock()
+ if len(stub.bindingCalls) != 1 {
+ t.Fatalf("expected one binding prompt attempt, got %d", len(stub.bindingCalls))
+ }
+ if len(stub.interactiveOut) != 0 {
+ t.Fatalf("did not expect fallback card on unstructured error text, got %d", len(stub.interactiveOut))
+ }
+}
+
+func TestLarkOutcomeReplierNeedsBindingSuppressesFallbackOutsideGroupChats(t *testing.T) {
+ t.Parallel()
+
+ for _, tc := range []struct {
+ name string
+ chatType ChatType
+ }{
+ {name: "p2p", chatType: ChatTypeP2P},
+ {name: "unspecified", chatType: ""},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ t.Parallel()
+ log := slog.New(slog.NewTextHandler(io.Discard, nil))
+ stub := &stubAPIClientWithRecorder{
+ configured: true,
+ bindingErr: &APIError{
+ Op: "send binding prompt",
+ Code: codeNoAvailability,
+ Msg: "Bot has no availability to this user.",
+ },
+ }
+ rep := NewLarkOutcomeReplier(OutcomeReplierConfig{
+ APIClient: stub,
+ BindingSvc: fakeBindingMinter{raw: "token"},
+ Credentials: stubCredentialsResolver{secret: "s"},
+ Queries: stubReplierQueries{},
+ AppURL: "https://multica.test",
+ Logger: log,
+ })
+
+ rep.Reply(context.Background(), Installation{}, InboundMessage{ChatID: "oc_chat", ChatType: tc.chatType, SenderOpenID: "ou_user"},
+ DispatchResult{Outcome: OutcomeNeedsBinding, SenderOpenID: "ou_user"})
+
+ stub.mu.Lock()
+ defer stub.mu.Unlock()
+ if len(stub.bindingCalls) != 1 {
+ t.Fatalf("expected one binding prompt attempt, got %d", len(stub.bindingCalls))
+ }
+ if len(stub.interactiveOut) != 0 {
+ t.Fatalf("did not expect fallback card outside group chat, got %d", len(stub.interactiveOut))
+ }
+ })
+ }
+}
+
+func TestLarkOutcomeReplierNeedsBindingPreservesPromptAndFallbackErrors(t *testing.T) {
+ t.Parallel()
+ log := slog.New(slog.NewTextHandler(io.Discard, nil))
+ bindingErr := &APIError{Op: "send binding prompt", Code: codeNoAvailability, Msg: "private unavailable"}
+ fallbackErr := errors.New("fallback send failed")
+ stub := &stubAPIClientWithRecorder{
+ configured: true,
+ bindingErr: bindingErr,
+ sendErr: fallbackErr,
+ }
+ inst := Installation{AppID: "cli_x"}
+ inst.ID = mustUUID("11111111-1111-1111-1111-111111111111")
+ inst.WorkspaceID = mustUUID("33333333-3333-3333-3333-333333333333")
+ rep := NewLarkOutcomeReplier(OutcomeReplierConfig{
+ APIClient: stub,
+ BindingSvc: fakeBindingMinter{raw: "token"},
+ Credentials: stubCredentialsResolver{secret: "s"},
+ Queries: stubReplierQueries{},
+ AppURL: "https://multica.test",
+ Logger: log,
+ })
+
+ err := rep.(*LarkOutcomeReplier).sendBindingPrompt(context.Background(), inst, InboundMessage{ChatID: "oc_chat", ChatType: ChatTypeGroup, SenderOpenID: "ou_user"},
+ DispatchResult{Outcome: OutcomeNeedsBinding, SenderOpenID: "ou_user"})
+ if err == nil {
+ t.Fatal("expected fallback failure")
+ }
+ if !strings.Contains(err.Error(), bindingErr.Error()) {
+ t.Fatalf("error should preserve original binding failure %q, got %q", bindingErr.Error(), err.Error())
+ }
+ if !errors.Is(err, fallbackErr) {
+ t.Fatalf("error should wrap fallback failure; got %v", err)
+ }
+}
+
+func TestLarkOutcomeReplierNeedsBindingDoesNotFallbackForNonAvailabilityError(t *testing.T) {
+ t.Parallel()
+ log := slog.New(slog.NewTextHandler(io.Discard, nil))
+ stub := &stubAPIClientWithRecorder{
+ configured: true,
+ bindingErr: &APIError{
+ Op: "send binding prompt",
+ Code: 230002,
+ Msg: "some other business error",
+ },
+ }
+ rep := NewLarkOutcomeReplier(OutcomeReplierConfig{
+ APIClient: stub,
+ BindingSvc: fakeBindingMinter{raw: "token"},
+ Credentials: stubCredentialsResolver{secret: "s"},
+ Queries: stubReplierQueries{},
+ AppURL: "https://multica.test",
+ Logger: log,
+ })
+
+ rep.Reply(context.Background(), Installation{}, InboundMessage{ChatID: "oc_chat", ChatType: ChatTypeGroup, SenderOpenID: "ou_user"},
+ DispatchResult{Outcome: OutcomeNeedsBinding, SenderOpenID: "ou_user"})
+
+ stub.mu.Lock()
+ defer stub.mu.Unlock()
+ if len(stub.bindingCalls) != 1 {
+ t.Fatalf("expected one binding prompt attempt, got %d", len(stub.bindingCalls))
+ }
+ if len(stub.interactiveOut) != 0 {
+ t.Fatalf("did not expect fallback card on unrelated binding error, got %d", len(stub.interactiveOut))
+ }
+}
+
// TestLarkOutcomeReplierIssueCreatedSendsConfirmation pins the
// recovered /issue confirmation path. Before the plain-text refactor
// the design called for a "已创建 [MUL-xxx]" card; the refactor