From d2029296fe31ceff7d572ceda3931b23c6fecf03 Mon Sep 17 00:00:00 2001 From: roberttwang Date: Sat, 28 Nov 2026 18:25:53 +0800 Subject: [PATCH 1/4] fix(settings): diagnose CodeBuddy model probe failures --- internal/httpapi/assistant_models.go | 44 ++++++-- internal/httpapi/cli_models_probe.go | 87 +++++++++++---- internal/httpapi/cli_models_probe_test.go | 128 ++++++++++++++++++++++ web/app/workbench.js | 7 +- 4 files changed, 236 insertions(+), 30 deletions(-) diff --git a/internal/httpapi/assistant_models.go b/internal/httpapi/assistant_models.go index 71b6c9bf2..4bf66a825 100644 --- a/internal/httpapi/assistant_models.go +++ b/internal/httpapi/assistant_models.go @@ -5,6 +5,7 @@ import ( "crypto/sha256" "encoding/hex" "errors" + "fmt" "os" "os/exec" "regexp" @@ -56,7 +57,7 @@ func prefetchAssistantModels() {} // CodeBuddy publishes the models available in each network environment in its // --help output; the list differs between international, internal and iOA. var ( - cliModelPattern = regexp.MustCompile(`Currently supported: \(([^)]*)\)`) + cliModelPattern = regexp.MustCompile(`(?i)Currently\s+supported\s*:\s*\(([^)]*)\)`) cliModelMu sync.Mutex cliModelCache = map[string]cliModelEntry{} cliModelGeneration uint64 @@ -92,28 +93,57 @@ func cliModelCacheKey(environment, apiKey string) string { } func discoverCodeBuddyModels(ctx context.Context, environment, apiKey string) []string { - bin, err := resolveCodeBuddyBin() - if err != nil { + models, _ := readCodeBuddyModels(ctx, environment, apiKey) + if len(models) == 0 { return nil } + return models +} + +func readCodeBuddyModels(ctx context.Context, environment, apiKey string) ([]string, error) { + bin, err := resolveAssistantEngineBin(assistantEngineCodeBuddy) + if err != nil { + if errors.Is(err, errAssistantCLIMissing) { + return nil, err + } + return nil, errors.New("无法定位 CodeBuddy CLI,请检查平台服务器上的 CLI 配置") + } dir, err := os.MkdirTemp("", "loopforge-models-") if err != nil { - return nil + return nil, errors.New("无法为 CodeBuddy CLI 创建临时目录,请检查平台服务器上的目录权限") } defer os.RemoveAll(dir) ctx, cancel := context.WithTimeout(ctx, 20*time.Second) defer cancel() cmd := exec.CommandContext(ctx, bin, "--help") cmd.Dir = dir + cmd.WaitDelay = time.Second cmd.Env = []string{"PATH=" + os.Getenv("PATH"), "HOME=" + dir, "CODEBUDDY_CONFIG_DIR=" + dir, "CODEBUDDY_INTERNET_ENVIRONMENT=" + environment} if key := strings.TrimSpace(apiKey); key != "" { cmd.Env = append(cmd.Env, "CODEBUDDY_API_KEY="+key) } out, err := cmd.Output() + if errors.Is(ctx.Err(), context.DeadlineExceeded) || errors.Is(err, exec.ErrWaitDelay) { + return nil, errors.New("获取 CodeBuddy 模型列表超时,请重试或手动添加模型") + } if err != nil { - return nil + var exit *exec.ExitError + if errors.As(err, &exit) { + if assistantAuthFailureText(string(exit.Stderr)) || isCredentialRejection(string(out)) { + return nil, errAssistantCredentialRejected + } + return nil, fmt.Errorf("CodeBuddy CLI 获取模型时异常退出(退出码 %d),请检查平台服务器上的 CLI", exit.ExitCode()) + } + return nil, errors.New("无法启动 CodeBuddy CLI,请检查平台服务器上的安装与文件权限") + } + models := parseCodeBuddyModels(string(out)) + if models == nil { + if isCredentialRejection(string(out)) { + return nil, errAssistantCredentialRejected + } + return nil, errors.New("无法解析 CodeBuddy CLI 的模型列表,请检查 CLI 版本或手动添加模型") } - return parseCodeBuddyModels(string(out)) + return models, nil } func parseCodeBuddyModels(help string) []string { @@ -121,7 +151,7 @@ func parseCodeBuddyModels(help string) []string { if m == nil { return nil } - var models []string + models := []string{} for _, id := range strings.Split(m[1], ",") { id = strings.TrimSpace(id) if id == "" || id == "echo" || strings.Contains(id, ":") { diff --git a/internal/httpapi/cli_models_probe.go b/internal/httpapi/cli_models_probe.go index 2e46325c5..014fe31af 100644 --- a/internal/httpapi/cli_models_probe.go +++ b/internal/httpapi/cli_models_probe.go @@ -32,7 +32,7 @@ type cliModelProbeResult struct { const assistantAnthropicAPIBase = "https://api.anthropic.com" -// probeCLIModels backs 「获取可用模型」 for a personal model catalog. +// probeCLIModels backs 「获取可用模型」 and 「测试连接」 for a personal model catalog. // The form's unsaved API Key, Base URL and protocol win over the stored ones // so a user can probe before saving; nothing is stored. Like // verifyGitToken it answers 200 with a structured result. @@ -56,6 +56,8 @@ func (h *usersHandlers) probeCLIModels(c *gin.Context) { // Protocol is the agent CLI's form value; null keeps the stored one. Protocol *string `json:"protocol"` Environment *string `json:"environment"` + ConnectOnly bool `json:"connectOnly"` + Model string `json:"model"` } if !decode(c, &req) { return @@ -97,27 +99,12 @@ func (h *usersHandlers) probeCLIModels(c *gin.Context) { } } if engine == assistantEngineCodeBuddy && baseURL == "" { - ctx, cancel := context.WithTimeout(c.Request.Context(), 15*time.Second) - defer cancel() - var models []domain.CLIModel - for _, id := range discoverCLIModels(ctx, environment, apiKey) { - if !codeBuddyIsDefaultModel(id) && assistantValidEngineModel(id) { - models = append(models, domain.CLIModel{ID: id}) - } - } - if len(models) == 0 { - if _, err := resolveAssistantEngineBin(engine); errors.Is(err, errAssistantCLIMissing) { - c.JSON(http.StatusOK, cliModelProbeResult{Error: err.Error()}) - return - } - c.JSON(http.StatusOK, cliModelProbeResult{Error: "CodeBuddy CLI 没有返回模型,请检查 CLI 和个人凭据"}) - return - } - source := "official" - if apiKey == "" { - source = "builtin" + ctx := c.Request.Context() + if req.ConnectOnly { + c.JSON(http.StatusOK, testOfficialCodeBuddyConnection(ctx, environment, apiKey, strings.TrimSpace(req.Model))) + } else { + c.JSON(http.StatusOK, probeOfficialCodeBuddyModels(ctx, environment, apiKey)) } - c.JSON(http.StatusOK, cliModelProbeResult{Models: cliModelsWithEfforts(engine, models, ""), Source: source}) return } if engine == runtime.AgentCLICursor { @@ -174,6 +161,64 @@ func (h *usersHandlers) probeCLIModels(c *gin.Context) { c.JSON(http.StatusOK, cliModelProbeResult{Models: cliModelsWithEfforts(engine, cliModelsOf(models), configuredBaseURL), Source: source, Connected: true}) } +func probeOfficialCodeBuddyModels(ctx context.Context, environment, apiKey string) cliModelProbeResult { + ids, err := readCodeBuddyModels(ctx, environment, apiKey) + if err != nil { + return cliModelProbeResult{Error: err.Error()} + } + var models []domain.CLIModel + for _, id := range ids { + if !codeBuddyIsDefaultModel(id) && assistantValidEngineModel(id) { + models = append(models, domain.CLIModel{ID: id}) + } + } + if len(models) == 0 { + return cliModelProbeResult{Error: "CodeBuddy CLI 没有列出可添加的模型,可手动添加模型"} + } + source := "official" + if apiKey == "" { + source = "builtin" + } + return cliModelProbeResult{Models: cliModelsWithEfforts(assistantEngineCodeBuddy, models, ""), Source: source} +} + +func testOfficialCodeBuddyConnection(ctx context.Context, environment, apiKey, model string) cliModelProbeResult { + if apiKey == "" { + return cliModelProbeResult{Error: "请先填写 CodeBuddy API Key"} + } + if model == "" || codeBuddyIsDefaultModel(model) { + // This Flash model is available on all three official sites. + model = "deepseek-v4.1-flash" + } + if !assistantValidEngineModel(model) { + return cliModelProbeResult{Error: "用于测试连接的模型 ID 无效"} + } + ctx, cancel := context.WithTimeout(ctx, 20*time.Second) + defer cancel() + reply, _, err := runAssistantCLI(ctx, assistantCLIRequest{ + Model: assistantEngineCodeBuddy + ":" + model, + Prompt: "Reply with OK.", + SystemPrompt: "Respond briefly to the connection check.", + ReviewOnly: true, + }, domain.User{CodeBuddyAPIKey: apiKey, CodeBuddyInternetEnvironment: environment}, nil) + switch { + case errors.Is(err, context.DeadlineExceeded): + return cliModelProbeResult{Error: "测试 CodeBuddy 连接超时,请检查平台网络后重试"} + case errors.Is(err, errAssistantCLIMissing): + return cliModelProbeResult{Error: err.Error()} + case errors.Is(err, errAssistantCredentialRejected), + assistantAuthFailureText(reply), err != nil && assistantAuthFailureText(err.Error()): + return cliModelProbeResult{Error: errAssistantCredentialRejected.Error()} + case err == nil: + return cliModelProbeResult{Connected: true, Source: "official"} + } + failure := classifyAssistantFailureText(domain.AssistantFailure{}, err, err.Error()) + if failure.Message != "" { + return cliModelProbeResult{Error: failure.Message} + } + return cliModelProbeResult{Error: "CodeBuddy 未完成连接测试,请检查平台服务器上的 CLI 或模型服务后重试"} +} + func discoverGeminiModels(ctx context.Context, key, baseURL string) ([]assistantDiscoveredModel, error) { client := *http.DefaultClient client.CheckRedirect = func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse } diff --git a/internal/httpapi/cli_models_probe_test.go b/internal/httpapi/cli_models_probe_test.go index 5d558c31b..c9714421b 100644 --- a/internal/httpapi/cli_models_probe_test.go +++ b/internal/httpapi/cli_models_probe_test.go @@ -3,13 +3,17 @@ package httpapi import ( "bytes" "context" + "encoding/json" "io" "net/http" "net/http/httptest" + "os" + "path/filepath" "reflect" "strconv" "strings" "testing" + "time" "agentflow/internal/domain" @@ -73,6 +77,130 @@ func TestProbeCodeBuddyIOAModelsReportsMissingCLI(t *testing.T) { } } +func TestProbeOfficialCodeBuddyModelsReportsSpecificResults(t *testing.T) { + for _, tt := range []struct { + name, body, wantError, wantModel string + deadline time.Duration + }{ + { + name: "wrapped help heading", + body: `printf 'Currently\n supported :\n (fixture-model, echo, default-model, --invalid)\n'`, + wantModel: "fixture-model", + }, + { + name: "unrecognized output", + body: `printf 'Ordinary CLI help\n'`, + wantError: "无法解析 CodeBuddy CLI 的模型列表", + }, + { + name: "no selectable models", + body: `printf 'Currently supported: (default, echo, default-model)\n'`, + wantError: "没有列出可添加的模型", + }, + { + name: "unsuccessful process", + body: `printf '%s\n' "$CODEBUDDY_API_KEY" >&2; exit 17`, + wantError: "退出码 17", + }, + { + name: "rejected api key", + body: `printf 'HTTP 401: invalid api key %s\n' "$CODEBUDDY_API_KEY" >&2; exit 1`, + wantError: "拒绝了你的 API Key", + }, + { + name: "timed out", + body: `exec /bin/sleep 5`, + wantError: "获取 CodeBuddy 模型列表超时", + deadline: 50 * time.Millisecond, + }, + } { + t.Run(tt.name, func(t *testing.T) { + installCodeBuddyProbeFixture(t, "[ \"$1\" = --help ] || exit 91\n"+tt.body) + ctx := context.Background() + if tt.deadline > 0 { + withDeadline, cancel := context.WithTimeout(ctx, tt.deadline) + defer cancel() + ctx = withDeadline + } + result := probeOfficialCodeBuddyModels(ctx, "internal", "test-only-catalog-key") + if result.Connected || strings.Contains(result.Error, "test-only-catalog-key") { + t.Fatalf("catalog probe returned an unsafe result: %+v", result) + } + if tt.wantError != "" { + if !strings.Contains(result.Error, tt.wantError) || len(result.Models) != 0 { + t.Fatalf("want %q with no models, got %+v", tt.wantError, result) + } + } else if result.Error != "" || result.Source != "official" || len(result.Models) != 1 || result.Models[0].ID != tt.wantModel { + t.Fatalf("want model %q, got %+v", tt.wantModel, result) + } + }) + } +} + +func TestProbeOfficialCodeBuddyConnectionUsesFormOrSavedCredentials(t *testing.T) { + installCodeBuddyProbeFixture(t, ` +model= +while [ "$#" -gt 0 ]; do + if [ "$1" = --model ]; then + model=$2 + shift + fi + shift +done +case "$CODEBUDDY_API_KEY:$CODEBUDDY_INTERNET_ENVIRONMENT:$model" in + saved-fixture:internal:deepseek-v4.1-flash|draft-fixture:ioa:manual-model) + printf '%s\n' '{"type":"result","subtype":"success","result":"OK"}' ;; + rejected-fixture:ioa:manual-model) + printf '%s\n' '{"type":"assistant","message":{"content":[{"type":"text","text":"401 Authentication required"}]}}' '{"type":"result","subtype":"success","result":""}' ;; + *) exit 91 ;; +esac +`) + f := cvBNewHTTPFixture(t) + path := "/api/users/" + strconv.FormatInt(f.user.ID, 10) + saved := cvBRequest(t, f, http.MethodPut, path+"/credentials", map[string]string{ + "codeBuddyApiKey": "saved-fixture", "codeBuddyInternetEnvironment": "internal", + }, true) + if saved.Code != http.StatusOK { + t.Fatalf("saving test credentials: %d", saved.Code) + } + for _, tt := range []struct { + name, key, model, wantError string + }{ + {name: "saved settings and default test model"}, + {name: "draft settings and manually configured model", key: "draft-fixture", model: "manual-model"}, + {name: "authentication failed even with a clean exit", key: "rejected-fixture", model: "manual-model", wantError: "拒绝了你的 API Key"}, + {name: "invalid model", key: "draft-fixture", model: "--model", wantError: "模型 ID 无效"}, + } { + t.Run(tt.name, func(t *testing.T) { + body := map[string]any{"engine": "codebuddy", "connectOnly": true, "model": tt.model} + if tt.key != "" { + body["apiKey"], body["environment"] = tt.key, "ioa" + } + response := cvBRequest(t, f, http.MethodPost, path+"/cli-models/probe", body, true) + var result cliModelProbeResult + if response.Code != http.StatusOK || json.Unmarshal(response.Body.Bytes(), &result) != nil { + t.Fatalf("connection response: %d %s", response.Code, response.Body) + } + if tt.wantError == "" { + if !result.Connected || result.Error != "" || result.Source != "official" || len(result.Models) != 0 { + t.Fatalf("expected a live connection result, got %+v", result) + } + } else if result.Connected || !strings.Contains(result.Error, tt.wantError) { + t.Fatalf("want %q with no connection, got %+v", tt.wantError, result) + } + }) + } +} + +func installCodeBuddyProbeFixture(t *testing.T, script string) { + t.Helper() + bin := filepath.Join(t.TempDir(), "codebuddy") + if err := os.WriteFile(bin, []byte("#!/bin/sh\n"+script+"\n"), 0700); err != nil { + t.Fatal(err) + } + t.Setenv("AGENTFLOW_CODEBUDDY_BIN", bin) +} + func TestDiscoverGeminiModelsKeepsGenerativeIDs(t *testing.T) { service := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.Method != http.MethodGet || r.URL.Path != "/v1beta/models" || r.Header.Get("x-goog-api-key") != "fixture-key" { diff --git a/web/app/workbench.js b/web/app/workbench.js index a69d04521..2c1ba2acb 100644 --- a/web/app/workbench.js +++ b/web/app/workbench.js @@ -360,7 +360,7 @@ function credentialCatalogProbeHTML(catalog,kind){ }).join(''); const protocol=catalog.closest('.credential-editor-form')?.querySelector('select[name="protocol"]')?.value||catalog.dataset.catalogProtocol; const sources={builtin:'CLI 内置模型',official:'来自官方服务',runner:'来自这台机器的账号登录'}; - const source=sources[probe.source]||`来自 Base URL 的 ${escapeHTML(credentialModelsEndpoint(kind,protocol))}`; + const source=kind?.models?.engine==='codebuddy'&&probe.source==='official'?'来自 CodeBuddy CLI':sources[probe.source]||`来自 Base URL 的 ${escapeHTML(credentialModelsEndpoint(kind,protocol))}`; return `
${credentialGlyph('search',14)}
${items}
${source} · 勾选的模型会加入目录,取消勾选会移出
`; @@ -384,6 +384,9 @@ async function probeCredentialCatalog(row,catalog,button,connectOnly=false){ const extra=form?.querySelector('input[name="baseUrl"], input[name="extra"]'),secret=form?.querySelector('[name="secret"]')?.value.trim()||'',protocol=form?.querySelector('select[name="protocol"]')?.value,environment=form?.querySelector('select[name="extra"]')?.value; const extraError=extra?(extra.name==='baseUrl'?credentialBaseURLError(extra.value):credentialExtraError(kind,extra.value,protocol)):''; if(extraError){toast(extraError,'err');extra.focus();return} + const engine=kind?.models?.engine,baseUrl=extra?.value.trim(); + const liveCodeBuddyCheck=connectOnly&&engine==='codebuddy'&&!baseUrl; + const model=liveCodeBuddyCheck?readCredentialCatalog(catalog)[0]?.id:undefined; const token=(catalog.probeToken||0)+1;catalog.probeToken=token;catalog.probe=null; panel.hidden=false; panel.innerHTML=`

${credentialSpinner(13)}${connectOnly?'正在测试连接…':'正在获取可用模型…'}

`; @@ -393,7 +396,7 @@ async function probeCredentialCatalog(row,catalog,button,connectOnly=false){ let result; try{ result=catalog.probeModels?await catalog.probeModels():await api(`/api/users/${state.currentUser.id}/cli-models/probe`,{method:'POST',body:JSON.stringify({ - engine:kind.models.engine,apiKey:secret,baseUrl:extra?.value.trim(),protocol,environment + engine,apiKey:secret,baseUrl,protocol,environment,connectOnly:liveCodeBuddyCheck||undefined,model }),silent:true}); } catch(err){result={error:err.message}} From 436436aeeb2649065e256a6c2c7729a27750cf39 Mon Sep 17 00:00:00 2001 From: roberttwang Date: Sat, 28 Nov 2026 18:29:35 +0800 Subject: [PATCH 2/4] test(settings): cover CodeBuddy connection requests --- webtest/tests/runner-codebuddy-environment.test.mjs | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/webtest/tests/runner-codebuddy-environment.test.mjs b/webtest/tests/runner-codebuddy-environment.test.mjs index 00ea84ee7..cd3f8ec2d 100644 --- a/webtest/tests/runner-codebuddy-environment.test.mjs +++ b/webtest/tests/runner-codebuddy-environment.test.mjs @@ -140,7 +140,7 @@ test('CLI model editor keeps machine account and personal API Key catalogs indep app.router.post('/api/runners/runner-cb/models/probe', { source:'runner', models:[{id:'codex/account-model',name:'Account model'}], }); - app.router.post('/api/users/1/cli-models/probe', { + app.router.post('/api/users/1/cli-models/probe', ({body}) => body.connectOnly ? {source:'official', connected:true} : { source:'official', models:[model,{id:'another-model',name:'Another model'}], }); app.router.put('/api/runners/runner-cb/models', ({body}) => { @@ -181,8 +181,14 @@ test('CLI model editor keeps machine account and personal API Key catalogs indep assert.deepEqual(modelIDs(), [model.id]); picker('probe').click(); await settle(); - assert.match(app.document.querySelector('.runner-model-editor').textContent, /来自官方服务/); + assert.match(app.document.querySelector('.runner-model-editor').textContent, /来自 CodeBuddy CLI/); assert.deepEqual(app.router.calls.find(c => c.path.endsWith('/cli-models/probe')).body, {engine:'codebuddy',apiKey:''}); + picker('connection').click(); + await settle(); + assert.match(app.document.querySelector('.runner-model-editor [data-catalog-probe]').textContent, /连接成功/); + assert.deepEqual(app.router.calls.filter(c => c.path.endsWith('/cli-models/probe')).at(-1).body, { + engine:'codebuddy', apiKey:'', connectOnly:true, model:model.id, + }); app.document.querySelector('#confirmCancelBtn').click(); }); From eeaa38e1a03c082f37942de6315a711f3dd7bfff Mon Sep 17 00:00:00 2001 From: roberttwang Date: Sat, 28 Nov 2026 11:40:48 +0000 Subject: [PATCH 3/4] fix(settings): name the model when CodeBuddy answers with an empty result A mistyped or unavailable model ID makes CodeBuddy stream the reason only in an assistant text block ("400 model [x] service info not found") and finish with an empty result payload, so the connection test classified it as a generic MISSING_RESULT and told the user to retry. Keep the last assistant text and pass it to the failure classifier, accept the bracketed model form, and have the connection test name the model it could not use. Co-Authored-By: Claude Code --- internal/httpapi/assistant.go | 12 +++++ internal/httpapi/assistant_failure.go | 5 +- internal/httpapi/assistant_failure_test.go | 53 ++++++++++++++++++++++ internal/httpapi/cli_models_probe.go | 9 ++++ 4 files changed, 78 insertions(+), 1 deletion(-) diff --git a/internal/httpapi/assistant.go b/internal/httpapi/assistant.go index 073d88594..fd31ef823 100644 --- a/internal/httpapi/assistant.go +++ b/internal/httpapi/assistant.go @@ -1743,6 +1743,10 @@ func runAssistantCLI(ctx context.Context, req assistantCLIRequest, user domain.U var streamFilter assistantStreamFilter var stderrTail []string var missingSession, modelStarted, credentialRejected bool + // The CLI sometimes reports the reason (e.g. an unknown model) only in an + // assistant text block and exits with an empty result payload; keep it so + // the failure classification can name the real cause. + var lastAssistantText string var usageCollector assistantCLIUsage if engine == assistantEngineCodeBuddy || engine == assistantEngineClaude { usageCollector.session = newAssistantSessionUsage(root, sessionID, req.Resume, engine) @@ -1833,6 +1837,11 @@ func runAssistantCLI(ctx context.Context, req assistantCLIRequest, user domain.U resetClaudeText := result.Message.ID == "" || result.Message.ID != claudeMessageID for _, block := range result.Message.Content { credentialRejected = credentialRejected || isCredentialRejection(block.Text) + if block.Type == "text" { + if text := strings.TrimSpace(block.Text); text != "" && !assistantCLINoticeText(text) { + lastAssistantText = text + } + } if !captureClaudeText || result.ParentToolUseID != "" || block.Type != "text" { continue } @@ -1910,6 +1919,9 @@ func runAssistantCLI(ctx context.Context, req assistantCLIRequest, user domain.U assistantDiagnosticsFrom(ctx).platform("protocol.result_text_recovered", "Claude Code 本轮成功但结果正文为空,采用已收到的回复", user) } out, err := decodeAssistantCLIResult(final, resultError, err, stderrTail) + if err != nil && errors.Is(err, errAssistantMissingResult) && lastAssistantText != "" { + err = fmt.Errorf("%w; assistant=%s", err, truncateRunes(lastAssistantText, 500)) + } if err != nil && req.RunnerLogin && ctx.Err() == nil && !errors.Is(err, runtime.ErrConversationNotStarted) { text := strings.ToLower(err.Error()) if assistantAuthFailureText(text) || strings.Contains(text, "not logged in") || strings.Contains(text, "login expired") || strings.Contains(text, "please run /login") { diff --git a/internal/httpapi/assistant_failure.go b/internal/httpapi/assistant_failure.go index 59e5b0d42..8d6b62bb2 100644 --- a/internal/httpapi/assistant_failure.go +++ b/internal/httpapi/assistant_failure.go @@ -162,7 +162,10 @@ func classifyAssistantFailureParts(f domain.AssistantFailure, err error) (domain return c, false } -var assistantModelMissingRe = regexp.MustCompile("(?i)\\bmodel\\s+[`'\"]?[^\\s`'\"]*[`'\"]?\\s*(?:does not exist|not found|is not available)") +// CodeBuddy reports an unknown model as `400 model [id] service info not found` +// and OpenAI-compatible providers as `The model `x` does not exist ...`, so the +// pattern accepts a bracketed, quoted or bare ID plus the provider's wording. +var assistantModelMissingRe = regexp.MustCompile("(?i)\\bmodel\\s*[`'\"]?(?:\\[[^\\]]+\\]|[^\\s`'\"]*)[`'\"]?\\s*(?:does not exist|not found|is not available|service info not found)") func classifyAssistantFailureText(f domain.AssistantFailure, err error, text string) domain.AssistantFailure { message := strings.ToLower(text) diff --git a/internal/httpapi/assistant_failure_test.go b/internal/httpapi/assistant_failure_test.go index c63c8514b..f85523657 100644 --- a/internal/httpapi/assistant_failure_test.go +++ b/internal/httpapi/assistant_failure_test.go @@ -328,3 +328,56 @@ func TestFailedSharedGenerationSnapshotKeepsCauseAndRetryHistory(t *testing.T) { }) } } + +func TestAssistantCLIReportsModelRejectionFromAssistantText(t *testing.T) { + // CodeBuddy answers a mistyped model ID with an assistant text block and a + // result whose payload is empty; the model error must survive the decode so + // the connection test can say the model is unavailable instead of "retry". + for _, tc := range []struct { + name, text string + }{ + {"bracketed model", "400 model [deepseek-v4.1-flsh] service info not found"}, + {"plain model", "400 model deepseek-v4.1-flsh not found"}, + } { + t.Run(tc.name, func(t *testing.T) { + dir := t.TempDir() + bin := filepath.Join(dir, "codebuddy") + script := "#!/bin/sh\ncat <<'RESULT'\n" + + `{"type":"assistant","message":{"content":[{"type":"text","text":"` + tc.text + `"}]}}` + "\n" + + `{"type":"result","subtype":"error_during_execution","is_error":true,"result":""}` + "\nRESULT\n" + if err := os.WriteFile(bin, []byte(script), 0o700); err != nil { + t.Fatal(err) + } + t.Setenv("AGENTFLOW_CODEBUDDY_BIN", bin) + _, _, err := runAssistantCLI(context.Background(), assistantCLIRequest{Prompt: "Reply with OK.", SessionRoot: dir}, domain.User{ID: 1, CodeBuddyAPIKey: "test-private-key"}, nil) + if err == nil { + t.Fatal("empty result was accepted") + } + failure := classifyAssistantFailureText(domain.AssistantFailure{}, err, err.Error()) + if failure.Code != "MODEL_UNAVAILABLE" { + t.Fatalf("code=%s message=%q err=%v", failure.Code, failure.Message, err) + } + }) + } +} + +func TestTestCodeBuddyConnectionNamesInvalidModel(t *testing.T) { + dir := t.TempDir() + bin := filepath.Join(dir, "codebuddy") + script := "#!/bin/sh\n" + + "for a in \"$@\"; do case \"$a\" in --help) echo 'Available models:'; echo ' deepseek-v4.1-flash'; exit 0;; esac; done\n" + + "cat <<'RESULT'\n" + + `{"type":"assistant","message":{"content":[{"type":"text","text":"400 model [deepseek-v4.1-flsh] service info not found"}]}}` + "\n" + + `{"type":"result","subtype":"error_during_execution","is_error":true,"result":""}` + "\nRESULT\n" + if err := os.WriteFile(bin, []byte(script), 0o700); err != nil { + t.Fatal(err) + } + t.Setenv("AGENTFLOW_CODEBUDDY_BIN", bin) + result := testOfficialCodeBuddyConnection(context.Background(), "ioa", "test-private-key", "deepseek-v4.1-flsh") + if result.Connected || result.Error == "" { + t.Fatalf("mistyped model reported as connected: %+v", result) + } + if !strings.Contains(result.Error, "deepseek-v4.1-flsh") || strings.Contains(result.Error, "未返回完整回答") { + t.Fatalf("error %q does not name the model", result.Error) + } +} diff --git a/internal/httpapi/cli_models_probe.go b/internal/httpapi/cli_models_probe.go index 014fe31af..1cf3855a1 100644 --- a/internal/httpapi/cli_models_probe.go +++ b/internal/httpapi/cli_models_probe.go @@ -213,6 +213,15 @@ func testOfficialCodeBuddyConnection(ctx context.Context, environment, apiKey, m return cliModelProbeResult{Connected: true, Source: "official"} } failure := classifyAssistantFailureText(domain.AssistantFailure{}, err, err.Error()) + switch failure.Code { + case "MODEL_UNAVAILABLE": + failure.Message = "CodeBuddy 无法使用模型 " + model + ",请确认模型 ID 拼写正确,并在当前网络环境下可用" + case "MISSING_RESULT": + // An empty answer with no recognisable reason is almost always a model + // the current network environment cannot serve, so name the model and + // the way out instead of asking the user to retry blindly. + failure.Message = "CodeBuddy 没有返回回答,请确认模型 " + model + " 在当前网络环境下可用,或换成模型目录里的其他模型" + } if failure.Message != "" { return cliModelProbeResult{Error: failure.Message} } From dca54d7fe66d974e5093e73b3d66b8a1965a073c Mon Sep 17 00:00:00 2001 From: roberttwang Date: Sat, 28 Nov 2026 12:04:42 +0000 Subject: [PATCH 4/4] fix(settings): carry only provider rejections into the missing-result error Appending every narration block changed the error text main's Claude recovery path asserts, so only model/auth rejections are appended. Co-Authored-By: Claude Code --- internal/httpapi/assistant.go | 5 ++++- internal/httpapi/assistant_failure.go | 9 +++++++++ 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/internal/httpapi/assistant.go b/internal/httpapi/assistant.go index fd31ef823..331b759cf 100644 --- a/internal/httpapi/assistant.go +++ b/internal/httpapi/assistant.go @@ -1919,7 +1919,10 @@ func runAssistantCLI(ctx context.Context, req assistantCLIRequest, user domain.U assistantDiagnosticsFrom(ctx).platform("protocol.result_text_recovered", "Claude Code 本轮成功但结果正文为空,采用已收到的回复", user) } out, err := decodeAssistantCLIResult(final, resultError, err, stderrTail) - if err != nil && errors.Is(err, errAssistantMissingResult) && lastAssistantText != "" { + // A model the account cannot use only shows up in that text block. Append it + // for classification; plain narration keeps the original error so the + // generic "interrupted, retry" reply and its tests are unchanged. + if err != nil && errors.Is(err, errAssistantMissingResult) && assistantProviderRejectionText(lastAssistantText) { err = fmt.Errorf("%w; assistant=%s", err, truncateRunes(lastAssistantText, 500)) } if err != nil && req.RunnerLogin && ctx.Err() == nil && !errors.Is(err, runtime.ErrConversationNotStarted) { diff --git a/internal/httpapi/assistant_failure.go b/internal/httpapi/assistant_failure.go index 8d6b62bb2..c03bea11f 100644 --- a/internal/httpapi/assistant_failure.go +++ b/internal/httpapi/assistant_failure.go @@ -224,3 +224,12 @@ func classifyAssistantFailureText(f domain.AssistantFailure, err error, text str // that was missing is reported separately, and a finished install replaces // both that report and this generic text. const assistantGenerationFailedMessage = "AI 助手生成失败,请稍后重试" + +// assistantProviderRejectionText reports whether an assistant text block is a +// provider rejection (e.g. `400 model [x] service info not found`) rather than +// narration, so only those are carried into the missing-result error. +func assistantProviderRejectionText(text string) bool { + text = strings.TrimSpace(text) + return strings.HasPrefix(text, "400 ") || strings.HasPrefix(text, "403 ") || + assistantModelMissingRe.MatchString(text) || assistantAuthFailureText(text) +}