Files
coder/coderd/x/chatd/chatfile_internal_test.go
Ethan 7a12022f3d fix: use one route-aware media rule for files and tool results (#31384)
Part of [CODAGT-1430](https://linear.app/codercom/issue/CODAGT-1430).
Stacked on #31383.

We had two rules for which media a model can take.
`AcceptsFilePartMediaType` filtered user attachments, whilst
`ToolResultMediaOmission` filtered tool results with its own lists, and
only let images through on Anthropic. Now that fantasy converts tool
result media like user files, the two should agree, so we'll keep one
rule.

`chatprovider.Model` now carries the configured provider type, and
`AcceptsFilePartMediaType` reads a table keyed on the route, i.e. the
configured provider plus the transport. `replaceUnsupportedMedia`
applies it to user file parts and tool result media alike, including the
pending tail of the turn prompt. As a result, tool result PDFs now reach
Anthropic, and the 5 MiB inline image cap only applies to images.

Azure OpenAI Chat Completions rejects file content parts with a 400
(`This model does not support file content types`, see
https://github.com/Azure/azure-sdk-for-net/issues/51873), and Gemini's
OpenAI-compatible endpoint ignores them. chatd reaches both through the
openai-compat client, so the rule rejects PDFs there, and the model gets
a text note instead of a failed request or a silently dropped file.

Unsupported tool result media now gets the same note fantasy writes
("The tool returned `<type>` content, which cannot be displayed."), so
the model sees one wording whichever layer drops it. I've also added a
Tool results section to the MCP servers docs, and fixed the File
attachments docs, which said every rejected attachment becomes text.
Only text files do; a rejected PDF becomes a note that names it.

I've also tested this end to end on Bedrock. I ran chatd from this
branch with an Anthropic provider pointed at our AI gateway's Bedrock
route (InvokeModel, us-east-2), plus an MCP tool that returns a PDF with
a code word inside. Claude Haiku 5.5 and Claude Opus 5.5 (adaptive
thinking) both read the code word from the tool result, and read it
again on the next turn, when the PDF is replayed from history. The
request carries the PDF as a `document` block inside `tool_result`, the
same body chatd sends to Anthropic.
2026-11-11 00:06:40 +11:00

347 lines
11 KiB
Go
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package chatd
import (
"context"
"strconv"
"testing"
"github.com/dustin/go-humanize"
"github.com/google/uuid"
"github.com/stretchr/testify/require"
"go.uber.org/mock/gomock"
"golang.org/x/xerrors"
"github.com/coder/coder/v2/coderd/database"
"github.com/coder/coder/v2/coderd/database/dbmock"
"github.com/coder/coder/v2/coderd/x/chatd/chaterror"
"github.com/coder/coder/v2/coderd/x/chatd/chatprovider"
"github.com/coder/coder/v2/coderd/x/chatd/chattest"
"github.com/coder/coder/v2/codersdk"
)
// routedModel returns a model whose requests reach the configured
// provider through the transport client.
func routedModel(transport, provider string) chatprovider.Model {
return chatprovider.NewModel(&chattest.FakeModel{ProviderName: transport, ModelName: "model"}, nil).
WithConfiguredProvider(provider)
}
// inlineImageCapFor returns the route's inline image cap. Fails the
// test if the route has no documented cap.
func inlineImageCapFor(t *testing.T, model chatprovider.Model) int {
t.Helper()
imageCap, ok := model.InlineImageCapBytes()
require.Truef(t, ok, "expected route %q/%q to have an inline image cap", model.RouteProvider(), model.Provider())
return imageCap
}
// TestChatFileResolver_RejectsOversizedImages is the server-side
// safety net for browser-side resize: oversize images that reach the
// resolver are rejected before any upstream request.
func TestChatFileResolver_RejectsOversizedImages(t *testing.T) {
t.Parallel()
// Computed so the table tracks any future cap retune.
anthropicCap := inlineImageCapFor(t, routedModel("anthropic", "anthropic"))
tests := []struct {
name string
transport string
provider string
mimetype string
size int
expectReject bool
expectProviderID string // classified.Provider after normalization
}{
{
name: "OversizedAnthropicPNG_Rejected",
transport: "anthropic",
provider: "anthropic",
mimetype: "image/png",
size: anthropicCap + 1,
expectReject: true,
expectProviderID: "anthropic",
},
{
name: "OversizedAnthropicJPEG_Rejected",
transport: "anthropic",
provider: "anthropic",
mimetype: "image/jpeg",
size: anthropicCap + 1024,
expectReject: true,
expectProviderID: "anthropic",
},
{
// Boundary is >=: exactly-at-limit is rejected.
// Anthropic's docs say "5 MB maximum" without
// specifying inclusivity, so reject strictly.
name: "AtLimitAnthropicImage_Rejected",
transport: "anthropic",
provider: "anthropic",
mimetype: "image/png",
size: anthropicCap,
expectReject: true,
expectProviderID: "anthropic",
},
{
name: "JustUnderLimitAnthropicImage_Accepted",
transport: "anthropic",
provider: "anthropic",
mimetype: "image/png",
size: anthropicCap - 1,
expectReject: false,
expectProviderID: "anthropic",
},
{
name: "UndersizedAnthropicImage_Accepted",
transport: "anthropic",
provider: "anthropic",
mimetype: "image/png",
size: 1024,
expectReject: false,
expectProviderID: "anthropic",
},
{
// Bedrock Claude models use the Anthropic transport and its cap.
name: "OversizedBedrockPNG_Rejected",
transport: "anthropic",
provider: "bedrock",
mimetype: "image/png",
size: anthropicCap + 1,
expectReject: true,
expectProviderID: "bedrock",
},
{
// Other Bedrock models use the OpenAI transport, which has
// no inline image cap.
name: "OversizedBedrockOpenAIPNG_Accepted",
transport: "openai",
provider: "bedrock",
mimetype: "image/png",
size: anthropicCap + 1,
expectReject: false,
expectProviderID: "bedrock",
},
{
name: "OversizedOpenAIImage_Accepted",
transport: "openai",
provider: "openai",
mimetype: "image/png",
size: anthropicCap + 1,
expectReject: false,
expectProviderID: "openai",
},
{
name: "OversizedAnthropicText_Accepted",
transport: "anthropic",
provider: "anthropic",
mimetype: "text/plain",
size: anthropicCap + 1,
expectReject: false,
expectProviderID: "anthropic",
},
{
name: "ProviderMixedCase_Rejected",
transport: "anthropic",
provider: "Anthropic",
mimetype: "image/png",
size: anthropicCap + 1,
expectReject: true,
expectProviderID: "anthropic",
},
{
name: "ProviderAllCaps_Rejected",
transport: "anthropic",
provider: "ANTHROPIC",
mimetype: "image/png",
size: anthropicCap + 1,
expectReject: true,
expectProviderID: "anthropic",
},
{
name: "ProviderPaddedWhitespace_Rejected",
transport: "anthropic",
provider: " anthropic ",
mimetype: "image/png",
size: anthropicCap + 1,
expectReject: true,
expectProviderID: "anthropic",
},
}
// One shared backing buffer sliced per case. The resolver only
// reads len(f.Data), so shared backing is safe and avoids N×max
// allocations in parallel.
maxSize := 0
for _, tc := range tests {
if tc.size > maxSize {
maxSize = tc.size
}
}
sharedData := make([]byte, maxSize)
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
t.Parallel()
ctx := context.Background()
ctrl := gomock.NewController(t)
db := dbmock.NewMockStore(ctrl)
server := &Server{db: db}
fileID := uuid.New()
row := database.ChatFile{
ID: fileID,
Name: "attachment.png",
Mimetype: tc.mimetype,
Data: sharedData[:tc.size],
}
db.EXPECT().
GetChatFilesByIDs(gomock.Any(), []uuid.UUID{fileID}).
Return([]database.ChatFile{row}, nil).
Times(1)
model := routedModel(tc.transport, tc.provider)
resolver := server.chatFileResolver(model)
got, err := resolver(ctx, []uuid.UUID{fileID})
if tc.expectReject {
require.Error(t, err)
require.Nil(t, got)
// Classification turns the generic upstream error
// into an actionable user-facing message.
classified := chaterror.Classify(err)
require.Equal(t, codersdk.ChatErrorKindConfig, classified.Kind)
require.Equal(t, tc.expectProviderID, classified.Provider)
require.False(t, classified.Retryable)
// User-facing message names the provider and shows
// the cap in human units; raw byte count stays in
// the wrapped developer error.
displayName := chatprovider.ProviderDisplayName(tc.expectProviderID)
require.Contains(t, classified.Message, displayName)
imageCap := inlineImageCapFor(t, model)
//nolint:gosec // imageCap is a small positive constant defined in chatprovider.
require.Contains(t, classified.Message, humanize.IBytes(uint64(imageCap)))
require.NotContains(
t,
classified.Message,
strconv.Itoa(imageCap),
"user-facing message should not include raw bytes",
)
// Wrapped error preserves exact bytes for logs.
require.Contains(t, err.Error(), strconv.Itoa(imageCap))
return
}
require.NoError(t, err)
require.Contains(t, got, fileID)
require.Equal(t, row.Data, got[fileID].Data)
require.Equal(t, tc.mimetype, got[fileID].MediaType)
})
}
}
// TestChatFileResolver_MultiFileFailsFastOnFirstOversized pins the
// "first bad file aborts the batch" contract.
func TestChatFileResolver_MultiFileFailsFastOnFirstOversized(t *testing.T) {
t.Parallel()
ctx := context.Background()
ctrl := gomock.NewController(t)
db := dbmock.NewMockStore(ctrl)
server := &Server{db: db}
anthropicModel := routedModel("anthropic", "anthropic")
anthropicCap := inlineImageCapFor(t, anthropicModel)
// Shared buffer; ok files take small prefixes.
buf := make([]byte, anthropicCap+1)
okFileA := database.ChatFile{
ID: uuid.New(),
Name: "ok-a.png",
Mimetype: "image/png",
Data: buf[:1024],
}
oversized := database.ChatFile{
ID: uuid.New(),
Name: "too-big.png",
Mimetype: "image/png",
Data: buf,
}
okFileB := database.ChatFile{
ID: uuid.New(),
Name: "ok-b.png",
Mimetype: "image/png",
Data: buf[:1024],
}
ids := []uuid.UUID{okFileA.ID, oversized.ID, okFileB.ID}
db.EXPECT().
GetChatFilesByIDs(gomock.Any(), ids).
Return([]database.ChatFile{okFileA, oversized, okFileB}, nil).
Times(1)
resolver := server.chatFileResolver(anthropicModel)
got, err := resolver(ctx, ids)
require.Error(t, err)
require.Nil(t, got)
classified := chaterror.Classify(err)
require.Equal(t, codersdk.ChatErrorKindConfig, classified.Kind)
// The error must identify the specific offending file so a user
// with several attachments knows which one to replace.
require.Contains(t, err.Error(), oversized.Name)
}
// TestChatFileResolver_PropagatesDBError confirms unrelated database
// failures pass through unchanged (not masked by the size check).
func TestChatFileResolver_PropagatesDBError(t *testing.T) {
t.Parallel()
ctx := context.Background()
ctrl := gomock.NewController(t)
db := dbmock.NewMockStore(ctrl)
server := &Server{db: db}
sentinel := xerrors.New("boom")
fileID := uuid.New()
db.EXPECT().
GetChatFilesByIDs(gomock.Any(), []uuid.UUID{fileID}).
Return(nil, sentinel).
Times(1)
resolver := server.chatFileResolver(routedModel("anthropic", "anthropic"))
got, err := resolver(ctx, []uuid.UUID{fileID})
require.ErrorIs(t, err, sentinel)
require.Nil(t, got)
}
// TestChatFileResolver_UnknownProviderSkipsCapCheck confirms providers
// without a documented inline cap are never rejected by the backstop.
func TestChatFileResolver_UnknownProviderSkipsCapCheck(t *testing.T) {
t.Parallel()
ctx := context.Background()
ctrl := gomock.NewController(t)
db := dbmock.NewMockStore(ctrl)
server := &Server{db: db}
fileID := uuid.New()
// Exactly 1 byte above the Anthropic cap is enough to prove
// the backstop is skipped for uncapped providers; no need to
// allocate tens of MiB in CI.
overAnyCap := inlineImageCapFor(t, routedModel("anthropic", "anthropic")) + 1
row := database.ChatFile{
ID: fileID,
Name: "huge.png",
Mimetype: "image/png",
Data: make([]byte, overAnyCap),
}
db.EXPECT().
GetChatFilesByIDs(gomock.Any(), []uuid.UUID{fileID}).
Return([]database.ChatFile{row}, nil).
Times(1)
resolver := server.chatFileResolver(routedModel("openai-compat", "openrouter"))
got, err := resolver(ctx, []uuid.UUID{fileID})
require.NoError(t, err)
require.Contains(t, got, fileID)
}