An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:bug: Keep Agent chats usable with text-only models https://github.com/siyuan-note/siyuan/issues/18466
Daniel5409e4415636
diff --git a/kernel/agent/agent.go b/kernel/agent/agent.goindex f4d3964956..3a1664f1b6 100644--- a/kernel/agent/agent.go+++ b/kernel/agent/agent.go@@ -443,7 +443,7 @@ type agentCheckpoint struct {LastCommittedTurnID string `json:"lastCommittedTurnID,omitempty"`}-func AgentChat(ctx context.Context, client *openai.Client, model string, contextLimit int, sessionID string, userEntryID string, contentRevision int64, userMessage string, language string, references []Reference, editorCtx EditorContext, pluginActions []PluginAction, regenerate bool, confirmTimeout time.Duration, maxRetries int, reasoningEffort string, requestTimeout, streamIdleTimeout time.Duration) <-chan AgentEvent {+func AgentChat(ctx context.Context, client *openai.Client, model, imageCapabilityKey string, contextLimit int, sessionID string, userEntryID string, contentRevision int64, userMessage string, language string, references []Reference, editorCtx EditorContext, pluginActions []PluginAction, regenerate bool, confirmTimeout time.Duration, maxRetries int, reasoningEffort string, requestTimeout, streamIdleTimeout time.Duration) <-chan AgentEvent {ch := make(chan AgentEvent, 256)go func() {@@ -641,11 +641,19 @@ func AgentChat(ctx context.Context, client *openai.Client, model string, contextmodelRound := 0toolCallRounds := 0overflowRetryPending := false+ imageInputDisabled := imageInputUnsupportedCached(imageCapabilityKey)+ projectImageMessages := func(source []openai.ChatCompletionMessage) ([]openai.ChatCompletionMessage, bool) {+ if imageInputDisabled {+ return downgradeImageInput(source)+ }+ return source, false+ }compactionErrorMessage := func(err error) string {if errors.Is(err, errContextCannotBeCompacted) || isContextOverflow(err) {return kernelModel.Conf.Language(352)}- return getAgentRequestErrorMessage(err, messages)+ requestMessages, _ := projectImageMessages(messages)+ return getAgentRequestErrorMessage(err, requestMessages)}compactContext := func(requestTools []openai.Tool, force bool) (bool, error) {@@ -659,7 +667,8 @@ func AgentChat(ctx context.Context, client *openai.Client, model string, contextif inputBudget <= 0 {return false, fmt.Errorf("%w: no input budget remains", errContextCannotBeCompacted)}- if !force && estimateChatRequestTokens(model, messages, requestTools) <= inputBudget {+ estimatedMessages, _ := projectImageMessages(messages)+ if !force && estimateChatRequestTokens(model, estimatedMessages, requestTools) <= inputBudget {return false, nil}@@ -682,6 +691,7 @@ func AgentChat(ctx context.Context, client *openai.Client, model string, contextcandidate := candidates[i]candidateCheckpointMsgs := checkpointMessagesAfterCompaction(sessionEntries, candidate, tail)candidateMessages := checkpointMessagesToOpenAIWithSummary(candidateCheckpointMsgs, language, pluginActions, nil)+ candidateMessages, _ = projectImageMessages(candidateMessages)baseTokens := estimateChatRequestTokens(model, candidateMessages, requestTools)return compactionSummaryMinTokens <= inputBudget-baseTokens-compactionSummaryOverhead})@@ -692,7 +702,8 @@ func AgentChat(ctx context.Context, client *openai.Client, model string, contextselectedCheckpointMsgs := checkpointMessagesAfterCompaction(sessionEntries, selectedEntryCount, tail)selectedMessages := checkpointMessagesToOpenAIWithSummary(selectedCheckpointMsgs, language, pluginActions, nil)- baseTokens := estimateChatRequestTokens(model, selectedMessages, requestTools)+ estimatedSelectedMessages, _ := projectImageMessages(selectedMessages)+ baseTokens := estimateChatRequestTokens(model, estimatedSelectedMessages, requestTools)summaryMaxTokens := min(compactionSummaryMaxTokens, inputBudget-baseTokens-compactionSummaryOverhead)@@ -722,7 +733,8 @@ func AgentChat(ctx context.Context, client *openai.Client, model string, context}nextMessages := checkpointMessagesToOpenAIWithSummary(selectedCheckpointMsgs, language, pluginActions, nextCompaction)- if estimateChatRequestTokens(model, nextMessages, requestTools) > inputBudget {+ estimatedNextMessages, _ := projectImageMessages(nextMessages)+ if estimateChatRequestTokens(model, estimatedNextMessages, requestTools) > inputBudget {return false, fmt.Errorf("%w: compacted context still exceeds the input budget", errContextCannotBeCompacted)}if err := saveRuntimeCompaction(sessionID, nextCompaction); err != nil {@@ -776,7 +788,15 @@ func AgentChat(ctx context.Context, client *openai.Client, model string, contextReasoningEffort: reasoningEffort,}- stream, firstResp, roundCancel, streamErr := createStreamWithRetry(ctx, client, req, maxRetries, requestTimeout, streamIdleTimeout, delayForCategory, ch)+ stream, firstResp, roundCancel, requestMessages, imageDowngraded, imageUnsupportedDetected, streamErr :=+ createImageCompatibleStream(ctx, client, req, imageCapabilityKey, imageInputDisabled, maxRetries,+ requestTimeout, streamIdleTimeout, delayForCategory, ch)+ if imageUnsupportedDetected {+ imageInputDisabled = true+ }+ if imageDowngraded {+ logging.LogDebugf("agent image input downgraded for model [%s]", model)+ }if streamErr != nil {if isContextOverflow(streamErr) && !overflowRetryPending {compacted, err := compactContext(requestTools, true)@@ -801,7 +821,7 @@ func AgentChat(ctx context.Context, client *openai.Client, model string, contextsendCriticalEvent(ctx, ch, AgentEvent{Type: "error", Error: kernelModel.Conf.Language(352)})return}- sendCriticalEvent(ctx, ch, AgentEvent{Type: "error", Error: getAgentRequestErrorMessage(streamErr, messages)})+ sendCriticalEvent(ctx, ch, AgentEvent{Type: "error", Error: getAgentRequestErrorMessage(streamErr, requestMessages)})return}overflowRetryPending = false@@ -1229,7 +1249,7 @@ func AgentChat(ctx context.Context, client *openai.Client, model string, contextContent: content,ReasoningContent: reasoningBuilder.String(),})- turn.TokenBreakdown = computeBreakdownIfNeeded(model, messages, tools, lastPromptTokens)+ turn.TokenBreakdown = computeBreakdownIfNeeded(model, requestMessages, requestTools, lastPromptTokens)if !saveTurn("finished") {return}diff --git a/kernel/agent/attachments.go b/kernel/agent/attachments.goindex 4ffb73722c..757d4384dd 100644--- a/kernel/agent/attachments.go+++ b/kernel/agent/attachments.go@@ -17,9 +17,13 @@package agentimport (+ "context""encoding/base64"+ "errors""fmt""strings"+ "sync"+ "time""github.com/sashabaranov/go-openai"mcptools "github.com/siyuan-note/siyuan/kernel/mcp/tools"@@ -29,8 +33,18 @@ import (const (maxAgentImagesPerRequest = 4maxAgentImageBytesPerRequest = 20 * 1024 * 1024+ imageInputUnsupportedTTL = 30 * time.Minute)+const imageInputOmittedText = "One or more image attachments were omitted because the current model does not " ++ "support image input. Use only the existing text and metadata, and do not claim to have inspected the omitted images."++type imageInputCapabilityCacheEntry struct {+ expiresAt time.Time+}++var imageInputUnsupportedCache sync.Map+func mergeAgentAttachments(current []AgentAttachment, attachments []mcptools.ModelAttachment) (merged, added []AgentAttachment, err error) {imageCount := len(current)totalBytes := 0@@ -183,3 +197,178 @@ func withoutAttachmentMessages(messages []openai.ChatCompletionMessage) []openai}return filtered}++func containsImageInput(messages []openai.ChatCompletionMessage) bool {+ for _, message := range messages {+ for _, part := range message.MultiContent {+ if part.Type == openai.ChatMessagePartTypeImageURL {+ return true+ }+ }+ }+ return false+}++// downgradeImageInput 仅生成请求投影,不修改包含原始附件的会话消息。+func downgradeImageInput(messages []openai.ChatCompletionMessage) ([]openai.ChatCompletionMessage, bool) {+ downgraded := make([]openai.ChatCompletionMessage, len(messages))+ changed := false+ for i, message := range messages {+ downgraded[i] = message+ hasImage := false+ texts := make([]string, 0, len(message.MultiContent)+1)+ for _, part := range message.MultiContent {+ if part.Type == openai.ChatMessagePartTypeImageURL {+ hasImage = true+ continue+ }+ if part.Type != openai.ChatMessagePartTypeText || strings.TrimSpace(part.Text) == "" ||+ isSyntheticImageInstruction(part.Text) {+ continue+ }+ texts = append(texts, part.Text)+ }+ if !hasImage {+ continue+ }+ changed = true+ texts = append(texts, imageInputOmittedText)+ downgraded[i].Content = strings.Join(texts, "\n")+ downgraded[i].MultiContent = nil+ }+ return downgraded, changed+}++func isSyntheticImageInstruction(text string) bool {+ return strings.HasPrefix(text, "SiYuan attached image ") ||+ strings.HasPrefix(text, "One or more image attachments were omitted because they were unavailable")+}++func imageInputUnsupportedCached(key string) bool {+ if key == "" {+ return false+ }+ value, ok := imageInputUnsupportedCache.Load(key)+ if !ok {+ return false+ }+ entry, ok := value.(imageInputCapabilityCacheEntry)+ if !ok || time.Now().After(entry.expiresAt) {+ imageInputUnsupportedCache.Delete(key)+ return false+ }+ return true+}++func rememberImageInputUnsupported(key string) {+ if key == "" {+ return+ }+ imageInputUnsupportedCache.Store(key, imageInputCapabilityCacheEntry{+ expiresAt: time.Now().Add(imageInputUnsupportedTTL),+ })+}++func messagesForImageCapability(messages []openai.ChatCompletionMessage, capabilityKey string) ([]openai.ChatCompletionMessage, bool) {+ if !imageInputUnsupportedCached(capabilityKey) {+ return messages, false+ }+ return downgradeImageInput(messages)+}++// isImageInputUnsupportedError 只接受明确的图片能力校验错误,避免掩盖工具、鉴权等其他请求错误。+func isImageInputUnsupportedError(err error) bool {+ statusCode, detail, ok := imageInputValidationError(err)+ if !ok || (statusCode != 0 && statusCode != 400 && statusCode != 422) {+ return false+ }+ detail = strings.ToLower(detail)+ return containsAny(detail,+ "does not support image", "doesn't support image", "does not support vision", "doesn't support vision",+ "does not support multimodal", "doesn't support multimodal", "does not support multi-modal",+ "doesn't support multi-modal", "does not accept image", "doesn't accept image", "cannot accept image",+ "image input is not supported", "image inputs are not supported", "image input unsupported",+ "unsupported image input", "image_url is not supported", "input_image is not supported",+ "image_url is only supported by", "input_image is only supported by", "model only supports text",+ "model only support text", "only supports text input", "only support text input",+ "only text input is supported", "only text content is supported", "text-only model", "text only model",+ "not a vision model",+ "not a multimodal model", "not a multi-modal model", "模型不支持图片", "模型不支持图像",+ "不支持图片输入", "不支持图像输入", "不支持多模态", "无法处理图片", "无法处理图像",+ "模型仅支持文本", "模型只支持文本", "仅支持文本输入", "只支持文本输入", "仅支持文本内容", "只支持文本内容")+}++func imageInputValidationError(err error) (statusCode int, detail string, ok bool) {+ var apiErr *openai.APIError+ if errors.As(err, &apiErr) {+ detail = apiErr.Message + " " + apiErr.Type + " " + fmt.Sprint(apiErr.Code)+ if apiErr.Param != nil {+ detail += " " + *apiErr.Param+ }+ return apiErr.HTTPStatusCode, detail, true+ }+ var requestErr *openai.RequestError+ if errors.As(err, &requestErr) {+ return requestErr.HTTPStatusCode, requestErr.Error(), true+ }+ return 0, "", false+}++func containsAny(value string, candidates ...string) bool {+ for _, candidate := range candidates {+ if strings.Contains(value, candidate) {+ return true+ }+ }+ return false+}++// createImageCompatibleStream 在上游明确拒绝图片且尚未产生输出时,使用纯文本请求投影兼容重试一次。+func createImageCompatibleStream(+ ctx context.Context,+ client *openai.Client,+ req openai.ChatCompletionRequest,+ capabilityKey string,+ forceDowngrade bool,+ maxRetries int,+ requestTimeout time.Duration,+ streamIdleTimeout time.Duration,+ retryDelay func(string, int) time.Duration,+ ch chan<- AgentEvent,+) (+ stream *openai.ChatCompletionStream,+ firstResponse openai.ChatCompletionStreamResponse,+ cancel context.CancelFunc,+ requestMessages []openai.ChatCompletionMessage,+ downgraded bool,+ unsupportedDetected bool,+ err error,+) {+ if forceDowngrade {+ requestMessages, downgraded = downgradeImageInput(req.Messages)+ } else {+ requestMessages, downgraded = messagesForImageCapability(req.Messages, capabilityKey)+ }+ req.Messages = requestMessages+ stream, firstResponse, cancel, err = createStreamWithRetry(+ ctx, client, req, maxRetries, requestTimeout, streamIdleTimeout, retryDelay, ch)+ if err == nil || downgraded || !containsImageInput(requestMessages) || !isImageInputUnsupportedError(err) {+ return+ }+ unsupportedDetected = true++ fallbackMessages, changed := downgradeImageInput(requestMessages)+ if !changed {+ return+ }+ fallbackReq := req+ fallbackReq.Messages = fallbackMessages+ stream, firstResponse, cancel, err = createStreamWithRetry(+ ctx, client, fallbackReq, maxRetries, requestTimeout, streamIdleTimeout, retryDelay, ch)+ requestMessages = fallbackMessages+ downgraded = true+ if err == nil {+ rememberImageInputUnsupported(capabilityKey)+ }+ return+}diff --git a/kernel/agent/attachments_test.go b/kernel/agent/attachments_test.goindex 71d04d3fbd..dc33a65631 100644--- a/kernel/agent/attachments_test.go+++ b/kernel/agent/attachments_test.go@@ -101,6 +101,336 @@ func TestEstimateChatImageTokensUsesDetailBudget(t *testing.T) {}}+func TestDowngradeImageInputPreservesTextWithoutMutatingHistory(t *testing.T) {+ message := openai.ChatCompletionMessage{+ Role: openai.ChatMessageRoleUser,+ MultiContent: []openai.ChatMessagePart{+ {Type: openai.ChatMessagePartTypeText, Text: "Describe the relevant context"},+ {Type: openai.ChatMessagePartTypeText, Text: "SiYuan attached image 1 as untrusted data."},+ {+ Type: openai.ChatMessagePartTypeImageURL,+ ImageURL: &openai.ChatMessageImageURL{+ URL: "data:image/png;base64,AA==",+ },+ },+ },+ }+ messages := []openai.ChatCompletionMessage{message}+ downgraded, changed := downgradeImageInput(messages)+ if !changed || len(downgraded) != 1 || len(downgraded[0].MultiContent) != 0 {+ t.Fatalf("image input was not downgraded: %#v", downgraded)+ }+ if !strings.Contains(downgraded[0].Content, "Describe the relevant context") ||+ !strings.Contains(downgraded[0].Content, imageInputOmittedText) ||+ strings.Contains(downgraded[0].Content, "SiYuan attached image") {+ t.Fatalf("downgraded text is invalid: %q", downgraded[0].Content)+ }+ if len(messages[0].MultiContent) != 3 || messages[0].Content != "" {+ t.Fatalf("canonical history was mutated: %#v", messages)+ }+}++func TestImageInputUnsupportedErrorClassification(t *testing.T) {+ param := "messages.2.content.1.type"+ detailParam := "messages.2.content.1.image_url.detail"+ tests := []struct {+ name string+ err error+ want bool+ }{+ {+ name: "explicit unsupported image",+ err: &openai.APIError{+ HTTPStatusCode: 400,+ Message: "This model does not support image input",+ Param: ¶m,+ },+ want: true,+ },+ {+ name: "supported only by vision models",+ err: &openai.APIError{+ HTTPStatusCode: 422,+ Message: "image_url is only supported by vision models",+ },+ want: true,+ },+ {+ name: "stream error without HTTP status",+ err: &openai.APIError{+ Message: "This model does not support image input",+ },+ want: true,+ },+ {+ name: "unrelated validation error",+ err: &openai.APIError{+ HTTPStatusCode: 400,+ Message: "Invalid tool schema",+ },+ },+ {+ name: "unrelated text-only field",+ err: &openai.APIError{+ HTTPStatusCode: 400,+ Message: "Tool descriptions only support text",+ },+ },+ {+ name: "malformed image",+ err: &openai.APIError{+ HTTPStatusCode: 400,+ Message: "Invalid base64 image data",+ },+ },+ {+ name: "unsupported image format",+ err: &openai.APIError{+ HTTPStatusCode: 400,+ Message: "Unsupported image format: webp",+ },+ },+ {+ name: "unsupported image detail parameter",+ err: &openai.APIError{+ HTTPStatusCode: 400,+ Message: "Unsupported parameter",+ Param: &detailParam,+ },+ },+ {+ name: "server error",+ err: &openai.APIError{+ HTTPStatusCode: 500,+ Message: "This model does not support image input",+ },+ },+ }+ for _, test := range tests {+ t.Run(test.name, func(t *testing.T) {+ if got := isImageInputUnsupportedError(test.err); got != test.want {+ t.Fatalf("classification = %v, want %v", got, test.want)+ }+ })+ }+}++func TestCreateImageCompatibleStreamDowngradesAndCaches(t *testing.T) {+ const capabilityKey = "provider\x00model\x00endpoint"+ imageInputUnsupportedCache.Delete(capabilityKey)+ t.Cleanup(func() { imageInputUnsupportedCache.Delete(capabilityKey) })++ attachmentMessage, _ := buildAttachmentMessage([]AgentAttachment{testAgentAttachment()})+ req := openai.ChatCompletionRequest{+ Model: "test-model",+ Messages: []openai.ChatCompletionMessage{attachmentMessage},+ Stream: true,+ }+ var requests atomic.Int32+ var imageRequests atomic.Int32+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ requests.Add(1)+ body, err := io.ReadAll(r.Body)+ if err != nil {+ t.Errorf("read request failed: %v", err)+ return+ }+ if strings.Contains(string(body), `"type":"image_url"`) {+ imageRequests.Add(1)+ w.Header().Set("Content-Type", "application/json")+ w.WriteHeader(http.StatusBadRequest)+ if _, err = io.WriteString(w, `{"error":{"message":"This model does not support image input","type":"invalid_request_error","code":"unsupported_value"}}`); err != nil {+ t.Errorf("write error response failed: %v", err)+ }+ return+ }+ flusher := prepareTestStream(t, w)+ writeTestStreamChunk(t, w, flusher, "continued as text")+ writeTestStreamDone(t, w, flusher)+ }))+ defer server.Close()++ call := func() {+ stream, _, cancel, requestMessages, downgraded, unsupportedDetected, err := createImageCompatibleStream(+ context.Background(), newTestOpenAIClient(server.URL), req, capabilityKey, false, 0,+ time.Second, time.Second, noRetryDelay, make(chan AgentEvent, 2),+ )+ if err != nil {+ t.Fatalf("compatible stream failed: %v", err)+ }+ if !downgraded || containsImageInput(requestMessages) ||+ !strings.Contains(requestMessages[0].Content, imageInputOmittedText) {+ t.Fatalf("unexpected request projection: %#v", requestMessages)+ }+ if requests.Load() == 2 && !unsupportedDetected {+ t.Fatal("initial image capability error was not reported")+ }+ stream.Close()+ cancel()+ }+ call()+ call()++ if requests.Load() != 3 || imageRequests.Load() != 1 {+ t.Fatalf("unexpected capability probing: requests=%d, imageRequests=%d", requests.Load(), imageRequests.Load())+ }+ if !containsImageInput(req.Messages) {+ t.Fatal("canonical request lost its image input")+ }+}++func TestCreateImageCompatibleStreamHandlesInitialSSEError(t *testing.T) {+ attachmentMessage, _ := buildAttachmentMessage([]AgentAttachment{testAgentAttachment()})+ req := openai.ChatCompletionRequest{+ Model: "test-model",+ Messages: []openai.ChatCompletionMessage{attachmentMessage},+ Stream: true,+ }+ var requests atomic.Int32+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ requests.Add(1)+ body, err := io.ReadAll(r.Body)+ if err != nil {+ t.Errorf("read request failed: %v", err)+ return+ }+ flusher := prepareTestStream(t, w)+ if strings.Contains(string(body), `"type":"image_url"`) {+ if _, err = io.WriteString(w, `data: {"error":{"message":"This model does not support image input","type":"invalid_request_error"}}`+"\n\n"); err != nil {+ t.Errorf("write stream error failed: %v", err)+ return+ }+ flusher.Flush()+ return+ }+ writeTestStreamChunk(t, w, flusher, "continued as text")+ writeTestStreamDone(t, w, flusher)+ }))+ defer server.Close()++ stream, _, cancel, requestMessages, downgraded, unsupportedDetected, err := createImageCompatibleStream(+ context.Background(), newTestOpenAIClient(server.URL), req, "", false, 0,+ time.Second, time.Second, noRetryDelay, make(chan AgentEvent, 2),+ )+ if err != nil {+ t.Fatalf("SSE capability fallback failed: %v", err)+ }+ if !downgraded || !unsupportedDetected || containsImageInput(requestMessages) || requests.Load() != 2 {+ t.Fatalf("SSE capability error was not downgraded: downgraded=%v, detected=%v, requests=%d",+ downgraded, unsupportedDetected, requests.Load())+ }+ stream.Close()+ cancel()+}++func TestCreateImageCompatibleStreamKeepsTurnDowngradedAfterFallbackError(t *testing.T) {+ attachmentMessage, _ := buildAttachmentMessage([]AgentAttachment{testAgentAttachment()})+ req := openai.ChatCompletionRequest{+ Model: "test-model",+ Messages: []openai.ChatCompletionMessage{attachmentMessage},+ Stream: true,+ }+ var requests atomic.Int32+ var imageRequests atomic.Int32+ var textRequests atomic.Int32+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ requests.Add(1)+ body, err := io.ReadAll(r.Body)+ if err != nil {+ t.Errorf("read request failed: %v", err)+ return+ }+ if strings.Contains(string(body), `"type":"image_url"`) {+ imageRequests.Add(1)+ w.Header().Set("Content-Type", "application/json")+ w.WriteHeader(http.StatusBadRequest)+ if _, err = io.WriteString(w, `{"error":{"message":"This model does not support image input","type":"invalid_request_error"}}`); err != nil {+ t.Errorf("write image error failed: %v", err)+ }+ return+ }+ if textRequests.Add(1) == 1 {+ w.Header().Set("Content-Type", "application/json")+ w.WriteHeader(http.StatusBadRequest)+ if _, err = io.WriteString(w, `{"error":{"message":"maximum context length exceeded","type":"invalid_request_error"}}`); err != nil {+ t.Errorf("write context error failed: %v", err)+ }+ return+ }+ flusher := prepareTestStream(t, w)+ writeTestStreamChunk(t, w, flusher, "continued after compaction")+ writeTestStreamDone(t, w, flusher)+ }))+ defer server.Close()++ _, _, _, _, downgraded, unsupportedDetected, err := createImageCompatibleStream(+ context.Background(), newTestOpenAIClient(server.URL), req, "", false, 0,+ time.Second, time.Second, noRetryDelay, make(chan AgentEvent, 2),+ )+ if err == nil || !downgraded || !unsupportedDetected {+ t.Fatalf("fallback error lost capability state: err=%v, downgraded=%v, detected=%v",+ err, downgraded, unsupportedDetected)+ }++ stream, _, cancel, requestMessages, downgraded, repeatedDetection, err := createImageCompatibleStream(+ context.Background(), newTestOpenAIClient(server.URL), req, "", unsupportedDetected, 0,+ time.Second, time.Second, noRetryDelay, make(chan AgentEvent, 2),+ )+ if err != nil {+ t.Fatalf("forced downgrade failed: %v", err)+ }+ if !downgraded || repeatedDetection || containsImageInput(requestMessages) ||+ requests.Load() != 3 || imageRequests.Load() != 1 {+ t.Fatalf("image capability was probed again: downgraded=%v, detected=%v, requests=%d, imageRequests=%d",+ downgraded, repeatedDetection, requests.Load(), imageRequests.Load())+ }+ stream.Close()+ cancel()+}++func TestCreateImageCompatibleStreamKeepsUnrelatedValidationError(t *testing.T) {+ attachmentMessage, _ := buildAttachmentMessage([]AgentAttachment{testAgentAttachment()})+ req := openai.ChatCompletionRequest{+ Model: "test-model",+ Messages: []openai.ChatCompletionMessage{attachmentMessage},+ Stream: true,+ }+ var requests atomic.Int32+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ requests.Add(1)+ w.Header().Set("Content-Type", "application/json")+ w.WriteHeader(http.StatusBadRequest)+ if _, err := io.WriteString(w, `{"error":{"message":"Invalid tool schema","type":"invalid_request_error"}}`); err != nil {+ t.Errorf("write error response failed: %v", err)+ }+ }))+ defer server.Close()++ _, _, _, requestMessages, downgraded, unsupportedDetected, err := createImageCompatibleStream(+ context.Background(), newTestOpenAIClient(server.URL), req, "unrelated-error", false, 0,+ time.Second, time.Second, noRetryDelay, make(chan AgentEvent, 2),+ )+ if err == nil || downgraded || unsupportedDetected || !containsImageInput(requestMessages) || requests.Load() != 1 {+ t.Fatalf("unrelated error triggered fallback: err=%v, downgraded=%v, detected=%v, requests=%d",+ err, downgraded, unsupportedDetected, requests.Load())+ }+}++func TestImageInputUnsupportedCacheExpires(t *testing.T) {+ const capabilityKey = "expired-capability"+ imageInputUnsupportedCache.Store(capabilityKey, imageInputCapabilityCacheEntry{+ expiresAt: time.Now().Add(-time.Second),+ })+ t.Cleanup(func() { imageInputUnsupportedCache.Delete(capabilityKey) })++ attachmentMessage, _ := buildAttachmentMessage([]AgentAttachment{testAgentAttachment()})+ messages := []openai.ChatCompletionMessage{attachmentMessage}+ projected, downgraded := messagesForImageCapability(messages, capabilityKey)+ if downgraded || !containsImageInput(projected) || imageInputUnsupportedCached(capabilityKey) {+ t.Fatalf("expired capability remained cached: downgraded=%v, messages=%#v", downgraded, projected)+ }+}+func TestCheckpointRestoresAttachmentAfterToolResults(t *testing.T) {checkpoint := []AgentMessage{{Role: "assistant",@@ -326,7 +656,7 @@ func TestAgentChatSendsToolAttachmentToCurrentModel(t *testing.T) {defer server.Close()events := AgentChat(- context.Background(), newTestOpenAIClient(server.URL), "test-model", 0, testSessionID, "user-1", 1,+ context.Background(), newTestOpenAIClient(server.URL), "test-model", "", 0, testSessionID, "user-1", 1,"look at the image", "English", nil, EditorContext{}, nil, false, time.Second, 0, "", time.Second, time.Second,)doneSeen := falsediff --git a/kernel/agent/compaction_test.go b/kernel/agent/compaction_test.goindex 6c38603c57..938e57d3c9 100644--- a/kernel/agent/compaction_test.go+++ b/kernel/agent/compaction_test.go@@ -278,7 +278,7 @@ func TestAgentChatCompactsBeforeSendingOversizedContext(t *testing.T) {defer server.Close()events := AgentChat(- context.Background(), newTestOpenAIClient(server.URL), "test-model", contextLimit, testSessionID,+ context.Background(), newTestOpenAIClient(server.URL), "test-model", "", contextLimit, testSessionID,"user-2", 1, "start the current task", "English", nil, EditorContext{}, nil, false,time.Second, 0, "", time.Second, time.Second,)@@ -372,7 +372,7 @@ func TestAgentChatRegenerateCompactionUsesTruncatedEditedHistory(t *testing.T) {defer server.Close()events := AgentChat(- context.Background(), newTestOpenAIClient(server.URL), "test-model", contextLimit, testSessionID,+ context.Background(), newTestOpenAIClient(server.URL), "test-model", "", contextLimit, testSessionID,"user-2", 1, editedTarget, "English", nil, EditorContext{}, nil, true,time.Second, 0, "", time.Second, time.Second,)@@ -467,7 +467,7 @@ func TestAgentChatRetriesOverflowAfterProactiveCompaction(t *testing.T) {defer server.Close()events := AgentChat(- context.Background(), newTestOpenAIClient(server.URL), "test-model", contextLimit, testSessionID,+ context.Background(), newTestOpenAIClient(server.URL), "test-model", "", contextLimit, testSessionID,"user-3", 1, "current task", "English", nil, EditorContext{}, nil, false,time.Second, 0, "", time.Second, time.Second,)diff --git a/kernel/agent/stream_timeout_test.go b/kernel/agent/stream_timeout_test.goindex 2666ad9f50..3068b34e50 100644--- a/kernel/agent/stream_timeout_test.go+++ b/kernel/agent/stream_timeout_test.go@@ -210,7 +210,7 @@ func TestAgentChatPartialStreamTimeoutSavesInterruptedWithoutRetry(t *testing.T)}))defer server.Close()- events := AgentChat(context.Background(), newTestOpenAIClient(server.URL), "test-model", 0, testSessionID, "user-1", 1, "hello", "English", nil, EditorContext{}, nil, false, time.Second, 3, "", time.Second, 50*time.Millisecond)+ events := AgentChat(context.Background(), newTestOpenAIClient(server.URL), "test-model", "", 0, testSessionID, "user-1", 1, "hello", "English", nil, EditorContext{}, nil, false, time.Second, 3, "", time.Second, 50*time.Millisecond)contentSeen := falseerrorSeen := falsefor event := range events {diff --git a/kernel/api/agent.go b/kernel/api/agent.goindex ae0b8373a8..7892cd78d3 100644--- a/kernel/api/agent.go+++ b/kernel/api/agent.go@@ -135,7 +135,9 @@ func agentChat(c *gin.Context) {contentRevision = *req.ContentRevision}contextLimit := agent.ResolveModelContextLimit(selectedModel.Name, selectedModel.ContextLength)- eventCh := agent.AgentChat(ctx, client, selectedModel.Name, contextLimit, req.SessionID, req.UserEntryID, contentRevision, req.Message, req.Language, req.References, req.EditorContext, req.PluginActions, req.Regenerate, confirmTimeout, maxRetries, req.ReasoningEffort, requestTimeout, streamIdleTimeout)+ imageCapabilityKey := fmt.Sprintf("%s\x00%s\x00%s\x00%s\x00%s",+ selectedProvider.ID, selectedModel.ID, selectedProvider.BaseURL, selectedProvider.Protocol, selectedModel.Name)+ eventCh := agent.AgentChat(ctx, client, selectedModel.Name, imageCapabilityKey, contextLimit, req.SessionID, req.UserEntryID, contentRevision, req.Message, req.Language, req.References, req.EditorContext, req.PluginActions, req.Regenerate, confirmTimeout, maxRetries, req.ReasoningEffort, requestTimeout, streamIdleTimeout)defer cancel()streamClosed := falsedefer func() {