fix: report AI table binding validation failures

This commit is contained in:
姚章浩
2026-08-14 11:11:07 +08:00
parent b4b68d8b21
commit a3defdd1c0
3 changed files with 108 additions and 3 deletions
+13
View File
@@ -317,6 +317,10 @@ func newAsyncChatCallbackRouter(handler chatCallbackHandler) func(context.Contex
if err != nil {
return nil, err
}
sourceType := safeCallbackMessageType(data.Msgtype)
if sourceType == "link" || sourceType == "richtext" {
log.Printf("DingTalk callback normalized: source_msgtype=%s normalized_msgtype=%s text_present=%t", sourceType, safeCallbackMessageType(cb.Msgtype), strings.TrimSpace(cb.Text) != "")
}
messageID := strings.TrimSpace(cb.MsgID)
if messageID == "" {
return nil, errors.New("dingtalk stream: msgId is required")
@@ -346,6 +350,15 @@ func newAsyncChatCallbackRouter(handler chatCallbackHandler) func(context.Contex
}
}
func safeCallbackMessageType(raw string) string {
switch strings.ToLower(strings.TrimSpace(raw)) {
case "text", "picture", "richtext", "link":
return strings.ToLower(strings.TrimSpace(raw))
default:
return "other"
}
}
// StreamClient wraps the official DingTalk Stream SDK client. Robot callbacks
// are acknowledged before the potentially slow QA/card work begins. The SDK
// default auto-reconnect stays enabled while running; Close disables it so the
+38 -3
View File
@@ -150,16 +150,51 @@ func (c *Controller) Handle(ctx context.Context, in SettingInput) (string, error
}
kind := action + "_table"
err = c.repo.SaveBinding(ctx, ResourceBinding{Kind: kind, TenantKey: in.TenantKey, BaseID: link.BaseID, SheetID: link.SheetID, ViewID: link.ViewID, OperatorID: in.UnionID, CreatedByStaffID: in.StaffID})
if err == nil {
_ = c.repo.DeleteSettingSession(ctx, in.TenantKey, in.StaffID)
return fmt.Sprintf("✅ %s已解析并保存为待验证配置。", map[string]string{"question": "问题AI表格", "faq": "FAQ表格"}[action]), nil
if err != nil {
return tableBindingFailureReply(action, err), nil
}
_ = c.repo.DeleteSettingSession(ctx, in.TenantKey, in.StaffID)
return fmt.Sprintf("✅ %sSchema验证通过并已激活,DobotAI将短暂重启加载Dispatcher。", map[string]string{"question": "问题AI表格", "faq": "FAQ表格"}[action]), nil
default:
return "未知设置项。发送 /setting 查看菜单。", nil
}
return "", err
}
func tableBindingFailureReply(action string, err error) string {
label := map[string]string{"question": "问题AI表格", "faq": "FAQ表格"}[action]
if label == "" {
label = "AI表格"
}
code := "table_validation_failed"
guidance := "请检查链接是否来自目标表格中的任意记录,并确认字段名称和类型符合提示要求。"
raw := ""
if err != nil {
raw = strings.ToLower(err.Error())
}
switch {
case strings.Contains(raw, "schema_http_401"), strings.Contains(raw, "schema_http_403"), strings.Contains(raw, "schema_token_failed"):
code = "table_permission_denied"
guidance = "请确认机器人应用已开通钉钉AI表格接口权限,并确认当前管理员对目标表格有访问和编辑权限。"
case strings.Contains(raw, "missing_field"):
code = "table_schema_missing_field"
guidance = "目标表缺少必需字段,请按上一条提示补齐字段后重试。"
case strings.Contains(raw, "duplicate_field"):
code = "table_schema_duplicate_field"
guidance = "目标表存在重名必需字段,请保留唯一字段后重试。"
case strings.Contains(raw, "field_type_mismatch"):
code = "table_schema_field_type_mismatch"
guidance = "目标表的必需字段类型不正确,请按上一条提示调整字段类型后重试。"
case strings.Contains(raw, "schema_network_failed"), strings.Contains(raw, "schema_request_failed"), strings.Contains(raw, "schema_read_failed"):
code = "table_schema_network_failed"
guidance = "钉钉AI表格接口暂时不可用,请稍后重试。"
case strings.Contains(raw, "schema_decode_failed"), strings.Contains(raw, "schema_empty"):
code = "table_schema_response_invalid"
guidance = "未读取到可用字段,请确认链接指向AI表格中的具体数据表。"
}
return fmt.Sprintf("❌ %s验证失败,新配置未激活。\n错误码:%s\n%s\n当前设置仍在10分钟等待期内,可直接重新发送链接卡片;发送“取消”退出。", label, code, guidance)
}
func tableBindingInstructions(action string) string {
if action == "faq" {
return "请在10分钟内直接发送FAQ表中任意一条记录的链接(钉钉显示为链接卡片也可以直接发送)。\n\n" +
+57
View File
@@ -2,6 +2,7 @@ package settings
import (
"context"
"errors"
"strings"
"testing"
"time"
@@ -13,6 +14,7 @@ type memoryRepo struct {
bindings map[string]ResourceBinding
candidate BootstrapCandidate
sessions map[string]SettingSession
saveErr error
}
func newMemoryRepo() *memoryRepo {
@@ -26,6 +28,9 @@ func (r *memoryRepo) SetPreference(_ context.Context, tenant, channel, staff, lo
return nil
}
func (r *memoryRepo) SaveBinding(_ context.Context, b ResourceBinding) error {
if r.saveErr != nil {
return r.saveErr
}
r.bindings[b.Kind] = b
return nil
}
@@ -184,6 +189,58 @@ func TestControllerFAQBindingPromptExplainsPermissionsSchemaActivationAndLinkCar
}
}
}
func TestControllerReportsFAQPermissionFailureAndKeepsWaitingSession(t *testing.T) {
r := newMemoryRepo()
r.admins["t/a"] = true
c := NewController(r)
if _, err := c.Handle(context.Background(), SettingInput{TenantKey: "t", StaffID: "a", Text: "/setting faq", ConversationType: "direct"}); err != nil {
t.Fatal(err)
}
r.saveErr = errors.New("schema_http_403")
out, err := c.Handle(context.Background(), SettingInput{
TenantKey: "t", StaffID: "a", UnionID: "union", ConversationType: "direct",
Text: "https://alidocs.dingtalk.com/i/nodes/base?sheetId=sheet&viewId=view",
})
if err != nil {
t.Fatalf("validation failure must become an actionable reply: %v", err)
}
for _, want := range []string{"table_permission_denied", "未激活", "机器人应用", "管理员", "重新发送链接卡片", "取消"} {
if !strings.Contains(out, want) {
t.Fatalf("reply=%q must contain %q", out, want)
}
}
if _, ok := r.sessions["t/a"]; !ok {
t.Fatal("failed validation must keep the setting session for retry")
}
if _, ok := r.bindings["faq_table"]; ok {
t.Fatal("failed validation must not save a binding")
}
}
func TestTableBindingFailureReplyUsesStableCodes(t *testing.T) {
tests := []struct {
err error
code string
}{
{errors.New("schema_http_403"), "table_permission_denied"},
{errors.New("schema_token_failed"), "table_permission_denied"},
{errors.New("missing_field"), "table_schema_missing_field"},
{errors.New("duplicate_field"), "table_schema_duplicate_field"},
{errors.New("field_type_mismatch"), "table_schema_field_type_mismatch"},
{errors.New("schema_network_failed"), "table_schema_network_failed"},
{errors.New("something private happened"), "table_validation_failed"},
}
for _, tt := range tests {
out := tableBindingFailureReply("faq", tt.err)
if !strings.Contains(out, tt.code) {
t.Fatalf("error=%q reply=%q want code=%q", tt.err, out, tt.code)
}
if tt.code == "table_validation_failed" && strings.Contains(out, tt.err.Error()) {
t.Fatalf("reply leaked raw unknown error: %q", out)
}
}
}
func TestControllerDetectsBootstrapCandidate(t *testing.T) {
r := newMemoryRepo()
c := NewController(r)