test(coderd/x/chatd/chatprompt): drop tests of the legacy content codec (#30997)
This PR deletes the tests of the legacy chat message encodings (plain strings, fantasy envelopes and legacy tool rows, all stored with `content_version` 0), and the test-only writers that built those rows (`MarshalContent` and `MarshalToolResult` in `export_test.go`). It changes tests only. The next layer removes the legacy decoder that these tests cover. **Why it is safe** Deleted tests that covered only the legacy format: - The legacy cases of `TestParseContent_BackwardCompat`: legacy system strings, fantasy envelopes and legacy tool rows. Its six cases of current-format parts in version 0 rows stay, because they need no legacy writer. The next layer moves them to version 1 rows. - `TestInjectFileID_StripsInlineData`: the test-only `MarshalContent` writer. - `TestSDKPartsNeverProduceFantasyEnvelopeShape`: the invariant behind `isFantasyEnvelopeFormat`, the legacy format detector. - `TestParseContent_ErrorPaths/unknown_role`: the role switch in the legacy decoder. The V1 decoder has no role switch. The version 0 malformed-input cases of this test stay, because they need no legacy writer. The next layer deletes them with the decoder. Deleted tests that also covered current behavior, checked with mutants of `chatprompt.go`: - `TestConvertMessagesWithFiles_BackwardCompat` (file ID resolution): dropping resolved file data, or not collecting user file IDs, still fails more than 10 remaining tests, including `TestConvertMessagesWithFiles_ResolvesFileData`. - `TestProviderMetadataRoundTrip` (provider metadata becomes provider options): dropping the conversion still fails `TestConvertMessagesWithFiles_Conversation` and `TestAssistantWriteRoundTrip`. - `TestProviderExecutedResult_LegacyToolRow` (provider-executed results in legacy tool rows are dropped before replay): keeping provider-executed results in `injectMissingToolUses` still fails `TestInjectMissingToolUses_DropsProviderExecutedOrphans` and `TestInjectMissingToolUses_DropsOnlyProviderExecutedMessage`. The 17 mutants from the layer below give the same result here as on that layer. **Review focus** The `export_test.go` deletion. `MarshalToolResult` uses `toolResultRaw`, which the next layer deletes, so the writer goes first. **Validation** - `go test ./coderd/x/chatd/chatprompt/ -count=1`: ok - `golangci-lint run --fix=false ./coderd/x/chatd/chatprompt/...`: 0 issues - pre-commit hook: passed **Stack** This stack retires chatd compatibility paths for chat data that older Coder versions stored. 1. #30996 stamp chat message fixtures with the current content version 2. #30997 drop tests of the legacy content codec (this PR) 3. #30998 retire the V0 chat message content decoder 4. #31000 inline the model config provider identity 5. #31005 retire the `close_agent` tool alias > Xum, an AI agent, opened this PR for @ibetitsmike and wrote this description.
This commit is contained in:
1 parent
31b8fd1b88
commit
e973f00480
2 files changed
-496
No files matched your search
@@ -534,101 +534,6 @@ func TestConvertMessagesWithFiles_MixedResolvedAndMissingFilePartsInSingleMessag
|
||||
)
|
||||
}
|
||||
|
||||
func TestConvertMessagesWithFiles_BackwardCompat(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
// A legacy message with inline data and a file_id: ParseContent
|
||||
// extracts the file_id and clears inline data (resolved at LLM
|
||||
// dispatch time). When a resolver provides data, the file part
|
||||
// in the LLM prompt should contain the resolved data.
|
||||
fileID := uuid.New()
|
||||
resolvedData := []byte("resolved-image-data")
|
||||
|
||||
rawContent := mustJSON(t, []json.RawMessage{
|
||||
mustJSON(t, map[string]any{
|
||||
"type": "file",
|
||||
"data": map[string]any{
|
||||
"media_type": "image/png",
|
||||
"data": []byte("inline-image-data"),
|
||||
"file_id": fileID.String(),
|
||||
},
|
||||
}),
|
||||
})
|
||||
|
||||
resolver := func(_ context.Context, ids []uuid.UUID) (map[uuid.UUID]chatprompt.FileData, error) {
|
||||
result := make(map[uuid.UUID]chatprompt.FileData)
|
||||
for _, id := range ids {
|
||||
if id == fileID {
|
||||
result[id] = chatprompt.FileData{
|
||||
Data: resolvedData,
|
||||
MediaType: "image/png",
|
||||
}
|
||||
}
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
prompt, err := chatprompt.ConvertMessagesWithFiles(
|
||||
context.Background(),
|
||||
[]database.ChatMessage{
|
||||
{
|
||||
Role: database.ChatMessageRoleUser,
|
||||
Visibility: database.ChatMessageVisibilityBoth,
|
||||
Content: pqtype.NullRawMessage{RawMessage: rawContent, Valid: true},
|
||||
},
|
||||
},
|
||||
resolver,
|
||||
slogtest.Make(t, nil),
|
||||
nil,
|
||||
uuid.NullUUID{},
|
||||
)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, prompt, 1)
|
||||
require.Len(t, prompt[0].Content, 1)
|
||||
|
||||
filePart, ok := fantasy.AsMessagePart[fantasy.FilePart](prompt[0].Content[0])
|
||||
require.True(t, ok, "expected FilePart")
|
||||
require.Equal(t, resolvedData, filePart.Data)
|
||||
require.Equal(t, "image/png", filePart.MediaType)
|
||||
}
|
||||
|
||||
func TestInjectFileID_StripsInlineData(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
fileID := uuid.New()
|
||||
imageData := []byte("raw-image-bytes")
|
||||
|
||||
// Marshal a file content block with inline data, then inject
|
||||
// a file_id. The result should have file_id but no data.
|
||||
content, err := chatprompt.MarshalContent([]fantasy.Content{
|
||||
fantasy.FileContent{
|
||||
MediaType: "image/png",
|
||||
Data: imageData,
|
||||
},
|
||||
}, map[int]uuid.UUID{0: fileID})
|
||||
require.NoError(t, err)
|
||||
|
||||
// Parse the stored content to verify shape.
|
||||
var blocks []json.RawMessage
|
||||
require.NoError(t, json.Unmarshal(content.RawMessage, &blocks))
|
||||
require.Len(t, blocks, 1)
|
||||
|
||||
var envelope struct {
|
||||
Type string `json:"type"`
|
||||
Data struct {
|
||||
MediaType string `json:"media_type"`
|
||||
Data *json.RawMessage `json:"data,omitempty"`
|
||||
FileID string `json:"file_id"`
|
||||
} `json:"data"`
|
||||
}
|
||||
require.NoError(t, json.Unmarshal(blocks[0], &envelope))
|
||||
require.Equal(t, "file", envelope.Type)
|
||||
require.Equal(t, "image/png", envelope.Data.MediaType)
|
||||
require.Equal(t, fileID.String(), envelope.Data.FileID)
|
||||
// Data should be nil (omitted) since injectFileID strips it.
|
||||
require.Nil(t, envelope.Data.Data, "inline data should be stripped")
|
||||
}
|
||||
|
||||
// TestInjectMissingToolResults_SkipsProviderExecuted verifies that
|
||||
// provider-executed tool calls (e.g. web_search) do not receive
|
||||
// synthetic error results when their results are missing from the
|
||||
@@ -1079,109 +984,6 @@ func TestProviderExecutedResultInAssistantContent(t *testing.T) {
|
||||
require.True(t, foundText, "expected text part in assistant message")
|
||||
}
|
||||
|
||||
// TestProviderExecutedResult_LegacyToolRow verifies backward
|
||||
// compatibility: PE tool results that were stored as separate
|
||||
// tool-role rows (legacy persistence) are still handled correctly
|
||||
// by the repair passes, orphaned PE results are dropped, and
|
||||
// matching PE results in the same step work via the existing
|
||||
// injectMissingToolUses logic.
|
||||
func TestProviderExecutedResult_LegacyToolRow(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
// Assistant with PE web_search + regular tool call.
|
||||
assistantContent, err := chatprompt.MarshalContent([]fantasy.Content{
|
||||
fantasy.ToolCallContent{
|
||||
ToolCallID: "srvtoolu_WS",
|
||||
ToolName: "web_search",
|
||||
Input: `{"query":"test"}`,
|
||||
ProviderExecuted: true,
|
||||
},
|
||||
fantasy.ToolCallContent{
|
||||
ToolCallID: "toolu_exec",
|
||||
ToolName: "execute",
|
||||
Input: `{"command":"ls"}`,
|
||||
},
|
||||
fantasy.TextContent{Text: "Results."},
|
||||
}, nil)
|
||||
require.NoError(t, err)
|
||||
|
||||
// Legacy: PE result stored as separate tool-role message.
|
||||
peResult, err := chatprompt.MarshalToolResult(
|
||||
"srvtoolu_WS", "web_search",
|
||||
json.RawMessage(`{"results":"cached"}`),
|
||||
false, false, true, // providerExecuted is true.
|
||||
nil,
|
||||
)
|
||||
require.NoError(t, err)
|
||||
execResult, err := chatprompt.MarshalToolResult(
|
||||
"toolu_exec", "execute",
|
||||
json.RawMessage(`{"output":"file.txt"}`),
|
||||
false, false, false,
|
||||
nil,
|
||||
)
|
||||
require.NoError(t, err)
|
||||
userContent, err := chatprompt.MarshalContent([]fantasy.Content{
|
||||
fantasy.TextContent{Text: "next"},
|
||||
}, nil)
|
||||
require.NoError(t, err)
|
||||
|
||||
prompt := convertMessagesWithoutFiles(t, []database.ChatMessage{
|
||||
{Role: database.ChatMessageRoleAssistant, Visibility: database.ChatMessageVisibilityBoth, Content: assistantContent},
|
||||
{Role: database.ChatMessageRoleTool, Visibility: database.ChatMessageVisibilityBoth, Content: peResult},
|
||||
{Role: database.ChatMessageRoleTool, Visibility: database.ChatMessageVisibilityBoth, Content: execResult},
|
||||
{Role: database.ChatMessageRoleUser, Visibility: database.ChatMessageVisibilityBoth, Content: userContent},
|
||||
})
|
||||
|
||||
// The PE tool result should be dropped by injectMissingToolUses,
|
||||
// leaving: assistant, tool(exec), user.
|
||||
require.Len(t, prompt, 3, "expected 3 messages after PE result is dropped")
|
||||
require.Equal(t, fantasy.MessageRoleAssistant, prompt[0].Role)
|
||||
require.Equal(t, fantasy.MessageRoleTool, prompt[1].Role)
|
||||
require.Equal(t, fantasy.MessageRoleUser, prompt[2].Role)
|
||||
|
||||
// Tool message should only contain the exec result, not the PE one.
|
||||
toolIDs := extractToolResultIDs(t, prompt[1])
|
||||
require.Equal(t, []string{"toolu_exec"}, toolIDs)
|
||||
}
|
||||
|
||||
// TestSDKPartsNeverProduceFantasyEnvelopeShape guards the structural
|
||||
// invariant that isFantasyEnvelopeFormat relies on: no SDK part type
|
||||
// serializes with a top-level "data" field containing a JSON object
|
||||
// (starting with '{'). Fantasy envelopes always have
|
||||
// "data":{object}, while ChatMessagePart.Data is []byte which
|
||||
// serializes to a base64 string or is omitted. If this test fails,
|
||||
// the format discriminator can no longer distinguish legacy fantasy
|
||||
// content from SDK parts, and parseAssistantRole / parseUserRole
|
||||
// would silently lose data on legacy rows.
|
||||
func TestSDKPartsNeverProduceFantasyEnvelopeShape(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
parts := []codersdk.ChatMessagePart{
|
||||
{Type: codersdk.ChatMessagePartTypeText, Text: "hello"},
|
||||
{Type: codersdk.ChatMessagePartTypeFile, FileID: uuid.NullUUID{UUID: uuid.New(), Valid: true}, MediaType: "image/png"},
|
||||
{Type: codersdk.ChatMessagePartTypeFile, MediaType: "image/png", Data: []byte("fake-image-data")},
|
||||
{Type: codersdk.ChatMessagePartTypeFileReference, FileName: "main.go", StartLine: 1, EndLine: 10, Content: "func main() {}"},
|
||||
{Type: codersdk.ChatMessagePartTypeReasoning, Text: "thinking..."},
|
||||
{Type: codersdk.ChatMessagePartTypeToolCall, ToolCallID: "abc", ToolName: "read_file", Args: json.RawMessage(`{"path":"main.go"}`)},
|
||||
{Type: codersdk.ChatMessagePartTypeToolResult, ToolCallID: "abc", ToolName: "read_file", Result: json.RawMessage(`{"output":"code"}`)},
|
||||
{Type: codersdk.ChatMessagePartTypeSource, SourceID: "s1", URL: "https://example.com", Title: "Example"},
|
||||
}
|
||||
for _, part := range parts {
|
||||
raw, err := json.Marshal(part)
|
||||
require.NoError(t, err)
|
||||
var fields map[string]json.RawMessage
|
||||
require.NoError(t, json.Unmarshal(raw, &fields))
|
||||
if data, ok := fields["data"]; ok {
|
||||
trimmed := bytes.TrimSpace(data)
|
||||
require.NotEmpty(t, trimmed)
|
||||
assert.NotEqual(t, byte('{'), trimmed[0],
|
||||
"SDK part type %q serializes with data field starting with '{', "+
|
||||
"would be misidentified as fantasy envelope by isFantasyEnvelopeFormat",
|
||||
part.Type)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// nullRaw wraps raw JSON bytes in a NullRawMessage for test input.
|
||||
func nullRaw(data json.RawMessage) pqtype.NullRawMessage {
|
||||
return pqtype.NullRawMessage{RawMessage: data, Valid: true}
|
||||
@@ -1192,37 +994,6 @@ func TestParseContent_BackwardCompat(t *testing.T) {
|
||||
|
||||
fileID := uuid.New()
|
||||
|
||||
// Build legacy fantasy assistant content using MarshalContent.
|
||||
legacyAssistantReasoning, err := chatprompt.MarshalContent([]fantasy.Content{
|
||||
fantasy.ReasoningContent{
|
||||
Text: "let me think...",
|
||||
ProviderMetadata: fantasy.ProviderMetadata{
|
||||
"anthropic": &fantasyanthropic.ProviderCacheControlOptions{
|
||||
CacheControl: fantasyanthropic.CacheControl{Type: "ephemeral"},
|
||||
},
|
||||
},
|
||||
},
|
||||
}, nil)
|
||||
require.NoError(t, err)
|
||||
|
||||
legacyAssistantSource, err := chatprompt.MarshalContent([]fantasy.Content{
|
||||
fantasy.SourceContent{
|
||||
ID: "src_001",
|
||||
URL: "https://example.com/doc",
|
||||
Title: "Example Doc",
|
||||
},
|
||||
}, nil)
|
||||
require.NoError(t, err)
|
||||
|
||||
legacyAssistantToolCall, err := chatprompt.MarshalContent([]fantasy.Content{
|
||||
fantasy.ToolCallContent{
|
||||
ToolCallID: "call_123",
|
||||
ToolName: "read_file",
|
||||
Input: `{"path":"main.go"}`,
|
||||
},
|
||||
}, nil)
|
||||
require.NoError(t, err)
|
||||
|
||||
// Build new SDK format using MarshalParts.
|
||||
sdkMetadata := json.RawMessage(`{"anthropic":{"type":"anthropic.cache_control_options","data":{"cache_control":{"type":"ephemeral"}}}}`)
|
||||
|
||||
@@ -1255,129 +1026,6 @@ func TestParseContent_BackwardCompat(t *testing.T) {
|
||||
raw pqtype.NullRawMessage
|
||||
check func(t *testing.T, parts []codersdk.ChatMessagePart)
|
||||
}{
|
||||
{
|
||||
name: "system/plain_string",
|
||||
role: codersdk.ChatMessageRoleSystem,
|
||||
raw: nullRaw(mustJSON(t, "You are helpful.")),
|
||||
check: func(t *testing.T, parts []codersdk.ChatMessagePart) {
|
||||
require.Len(t, parts, 1)
|
||||
assert.Equal(t, codersdk.ChatMessagePartTypeText, parts[0].Type)
|
||||
assert.Equal(t, "You are helpful.", parts[0].Text)
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "user/fantasy_text",
|
||||
role: codersdk.ChatMessageRoleUser,
|
||||
raw: nullRaw(mustJSON(t, []json.RawMessage{
|
||||
mustJSON(t, map[string]any{
|
||||
"type": "text",
|
||||
"data": map[string]any{"text": "hello from user"},
|
||||
}),
|
||||
})),
|
||||
check: func(t *testing.T, parts []codersdk.ChatMessagePart) {
|
||||
require.Len(t, parts, 1)
|
||||
assert.Equal(t, codersdk.ChatMessagePartTypeText, parts[0].Type)
|
||||
assert.Equal(t, "hello from user", parts[0].Text)
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "assistant/fantasy_text",
|
||||
role: codersdk.ChatMessageRoleAssistant,
|
||||
raw: nullRaw(mustJSON(t, []json.RawMessage{
|
||||
mustJSON(t, map[string]any{
|
||||
"type": "text",
|
||||
"data": map[string]any{"text": "hello from assistant"},
|
||||
}),
|
||||
})),
|
||||
check: func(t *testing.T, parts []codersdk.ChatMessagePart) {
|
||||
require.Len(t, parts, 1)
|
||||
assert.Equal(t, codersdk.ChatMessagePartTypeText, parts[0].Type)
|
||||
assert.Equal(t, "hello from assistant", parts[0].Text)
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "user/plain_string",
|
||||
role: codersdk.ChatMessageRoleUser,
|
||||
raw: nullRaw(mustJSON(t, "just a plain string")),
|
||||
check: func(t *testing.T, parts []codersdk.ChatMessagePart) {
|
||||
require.Len(t, parts, 1)
|
||||
assert.Equal(t, codersdk.ChatMessagePartTypeText, parts[0].Type)
|
||||
assert.Equal(t, "just a plain string", parts[0].Text)
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "user/fantasy_file_with_file_id",
|
||||
role: codersdk.ChatMessageRoleUser,
|
||||
raw: nullRaw(mustJSON(t, []json.RawMessage{
|
||||
mustJSON(t, map[string]any{
|
||||
"type": "file",
|
||||
"data": map[string]any{
|
||||
"media_type": "image/png",
|
||||
"file_id": fileID.String(),
|
||||
},
|
||||
}),
|
||||
})),
|
||||
check: func(t *testing.T, parts []codersdk.ChatMessagePart) {
|
||||
require.Len(t, parts, 1)
|
||||
assert.Equal(t, codersdk.ChatMessagePartTypeFile, parts[0].Type)
|
||||
assert.Equal(t, "image/png", parts[0].MediaType)
|
||||
assert.True(t, parts[0].FileID.Valid)
|
||||
assert.Equal(t, fileID, parts[0].FileID.UUID)
|
||||
assert.Nil(t, parts[0].Data, "inline data cleared when file_id present")
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "assistant/fantasy_reasoning_with_metadata",
|
||||
role: codersdk.ChatMessageRoleAssistant,
|
||||
raw: legacyAssistantReasoning,
|
||||
check: func(t *testing.T, parts []codersdk.ChatMessagePart) {
|
||||
require.Len(t, parts, 1)
|
||||
assert.Equal(t, codersdk.ChatMessagePartTypeReasoning, parts[0].Type)
|
||||
assert.Equal(t, "let me think...", parts[0].Text)
|
||||
require.NotNil(t, parts[0].ProviderMetadata, "ProviderMetadata must be preserved")
|
||||
assert.Contains(t, string(parts[0].ProviderMetadata), "anthropic")
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "assistant/fantasy_source",
|
||||
role: codersdk.ChatMessageRoleAssistant,
|
||||
raw: legacyAssistantSource,
|
||||
check: func(t *testing.T, parts []codersdk.ChatMessagePart) {
|
||||
require.Len(t, parts, 1)
|
||||
assert.Equal(t, codersdk.ChatMessagePartTypeSource, parts[0].Type)
|
||||
assert.Equal(t, "src_001", parts[0].SourceID)
|
||||
assert.Equal(t, "https://example.com/doc", parts[0].URL)
|
||||
assert.Equal(t, "Example Doc", parts[0].Title)
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "assistant/fantasy_tool_call",
|
||||
role: codersdk.ChatMessageRoleAssistant,
|
||||
raw: legacyAssistantToolCall,
|
||||
check: func(t *testing.T, parts []codersdk.ChatMessagePart) {
|
||||
require.Len(t, parts, 1)
|
||||
assert.Equal(t, codersdk.ChatMessagePartTypeToolCall, parts[0].Type)
|
||||
assert.Equal(t, "call_123", parts[0].ToolCallID)
|
||||
assert.Equal(t, "read_file", parts[0].ToolName)
|
||||
assert.JSONEq(t, `{"path":"main.go"}`, string(parts[0].Args))
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "tool/legacy_result_row",
|
||||
role: codersdk.ChatMessageRoleTool,
|
||||
raw: nullRaw(mustJSON(t, []map[string]any{{
|
||||
"tool_call_id": "call_123",
|
||||
"tool_name": "read_file",
|
||||
"result": json.RawMessage(`{"output":"package main"}`),
|
||||
}})),
|
||||
check: func(t *testing.T, parts []codersdk.ChatMessagePart) {
|
||||
require.Len(t, parts, 1)
|
||||
assert.Equal(t, codersdk.ChatMessagePartTypeToolResult, parts[0].Type)
|
||||
assert.Equal(t, "call_123", parts[0].ToolCallID)
|
||||
assert.Equal(t, "read_file", parts[0].ToolName)
|
||||
assert.JSONEq(t, `{"output":"package main"}`, string(parts[0].Result))
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "user/sdk_text",
|
||||
role: codersdk.ChatMessageRoleUser,
|
||||
@@ -1502,59 +1150,6 @@ func TestParseContent_V1(t *testing.T) {
|
||||
})
|
||||
}
|
||||
|
||||
// TestProviderMetadataRoundTrip verifies that Anthropic cache
|
||||
// control hints survive the full path: legacy fantasy DB row →
|
||||
// ParseContent → SDK part (ProviderMetadata) → partsToMessageParts
|
||||
// → fantasy.MessagePart (ProviderOptions).
|
||||
func TestProviderMetadataRoundTrip(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
legacyContent, err := chatprompt.MarshalContent([]fantasy.Content{
|
||||
fantasy.TextContent{
|
||||
Text: "cached response",
|
||||
ProviderMetadata: fantasy.ProviderMetadata{
|
||||
"anthropic": &fantasyanthropic.ProviderCacheControlOptions{
|
||||
CacheControl: fantasyanthropic.CacheControl{Type: "ephemeral"},
|
||||
},
|
||||
},
|
||||
},
|
||||
}, nil)
|
||||
require.NoError(t, err)
|
||||
|
||||
// Step 1: ParseContent preserves metadata on the SDK part.
|
||||
parts, err := chatprompt.ParseContent(testMsg(codersdk.ChatMessageRoleAssistant, legacyContent))
|
||||
require.NoError(t, err)
|
||||
require.Len(t, parts, 1)
|
||||
require.NotNil(t, parts[0].ProviderMetadata,
|
||||
"ProviderMetadata must survive ParseContent")
|
||||
|
||||
// Step 2: ConvertMessagesWithFiles reconstructs typed
|
||||
// ProviderOptions on the fantasy part.
|
||||
prompt, err := chatprompt.ConvertMessagesWithFiles(
|
||||
context.Background(),
|
||||
[]database.ChatMessage{{
|
||||
Role: database.ChatMessageRoleAssistant,
|
||||
Visibility: database.ChatMessageVisibilityBoth,
|
||||
Content: legacyContent,
|
||||
}},
|
||||
nil,
|
||||
slogtest.Make(t, nil),
|
||||
nil,
|
||||
uuid.NullUUID{},
|
||||
)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, prompt, 1)
|
||||
require.Len(t, prompt[0].Content, 1)
|
||||
|
||||
textPart, ok := fantasy.AsMessagePart[fantasy.TextPart](prompt[0].Content[0])
|
||||
require.True(t, ok, "expected TextPart")
|
||||
require.Equal(t, "cached response", textPart.Text)
|
||||
|
||||
cc := fantasyanthropic.GetCacheControl(textPart.ProviderOptions)
|
||||
require.NotNil(t, cc, "Anthropic cache control must survive round-trip")
|
||||
require.Equal(t, "ephemeral", cc.Type)
|
||||
}
|
||||
|
||||
// TestFileReferencePreservation verifies file-reference parts
|
||||
// survive the storage round-trip and convert to text for LLMs.
|
||||
func TestFileReferencePreservation(t *testing.T) {
|
||||
@@ -1989,13 +1584,6 @@ func TestParseContent_ErrorPaths(t *testing.T) {
|
||||
assert.Nil(t, parts)
|
||||
})
|
||||
|
||||
t.Run("unknown_role", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
_, err := chatprompt.ParseContent(testMsg(codersdk.ChatMessageRole("banana"), nullRaw(json.RawMessage(`"hello"`))))
|
||||
require.Error(t, err)
|
||||
assert.Contains(t, err.Error(), "unsupported chat message role")
|
||||
})
|
||||
|
||||
t.Run("system/malformed_json", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
_, err := chatprompt.ParseContent(testMsgV1(codersdk.ChatMessageRoleSystem, nullRaw(json.RawMessage(`not json`))))
|
||||
|
||||
@@ -1,12 +1,7 @@
|
||||
package chatprompt
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
|
||||
"charm.land/fantasy"
|
||||
"github.com/google/uuid"
|
||||
"github.com/sqlc-dev/pqtype"
|
||||
"golang.org/x/xerrors"
|
||||
|
||||
"cdr.dev/slog/v3"
|
||||
"github.com/coder/coder/v2/codersdk"
|
||||
@@ -32,85 +27,6 @@ var ToolResultContentToPartForTest = func(logger slog.Logger, content fantasy.To
|
||||
return toolResultContentToPart(logger, content, nil)
|
||||
}
|
||||
|
||||
// MarshalContent encodes message content blocks in legacy fantasy
|
||||
// envelope format. Retained for backward-compatible test fixtures
|
||||
// that create legacy-format DB rows. Production write paths use
|
||||
// MarshalParts instead.
|
||||
func MarshalContent(blocks []fantasy.Content, fileIDs map[int]uuid.UUID) (pqtype.NullRawMessage, error) {
|
||||
if len(blocks) == 0 {
|
||||
return pqtype.NullRawMessage{}, nil
|
||||
}
|
||||
|
||||
encodedBlocks := make([]json.RawMessage, 0, len(blocks))
|
||||
for i, block := range blocks {
|
||||
encoded, err := json.Marshal(block)
|
||||
if err != nil {
|
||||
return pqtype.NullRawMessage{}, xerrors.Errorf(
|
||||
"encode content block %d: %w",
|
||||
i,
|
||||
err,
|
||||
)
|
||||
}
|
||||
if fid, ok := fileIDs[i]; ok {
|
||||
// Inline file_id injection into the fantasy envelope's
|
||||
// data sub-object, stripping inline data.
|
||||
var envelope struct {
|
||||
Type string `json:"type"`
|
||||
Data struct {
|
||||
MediaType string `json:"media_type"`
|
||||
Data json.RawMessage `json:"data,omitempty"`
|
||||
FileID string `json:"file_id,omitempty"`
|
||||
ProviderMetadata *json.RawMessage `json:"provider_metadata,omitempty"`
|
||||
} `json:"data"`
|
||||
}
|
||||
if err := json.Unmarshal(encoded, &envelope); err == nil {
|
||||
envelope.Data.FileID = fid.String()
|
||||
envelope.Data.Data = nil
|
||||
if patched, err := json.Marshal(envelope); err == nil {
|
||||
encoded = patched
|
||||
}
|
||||
}
|
||||
}
|
||||
encodedBlocks = append(encodedBlocks, encoded)
|
||||
}
|
||||
|
||||
data, err := json.Marshal(encodedBlocks)
|
||||
if err != nil {
|
||||
return pqtype.NullRawMessage{}, xerrors.Errorf("encode content blocks: %w", err)
|
||||
}
|
||||
return pqtype.NullRawMessage{RawMessage: data, Valid: true}, nil
|
||||
}
|
||||
|
||||
// MarshalToolResult encodes a single tool result in the legacy
|
||||
// tool-row format. Retained for test fixtures that create
|
||||
// legacy-format DB rows. Production write paths use MarshalParts.
|
||||
// The stored shape is
|
||||
// [{"tool_call_id":…,"tool_name":…,"result":…,"is_error":…,"is_media":…}].
|
||||
func MarshalToolResult(toolCallID, toolName string, result json.RawMessage, isError bool, isMedia bool, providerExecuted bool, providerMetadata fantasy.ProviderMetadata) (pqtype.NullRawMessage, error) {
|
||||
var metaJSON json.RawMessage
|
||||
if len(providerMetadata) > 0 {
|
||||
var err error
|
||||
metaJSON, err = json.Marshal(providerMetadata)
|
||||
if err != nil {
|
||||
return pqtype.NullRawMessage{}, xerrors.Errorf("encode provider metadata: %w", err)
|
||||
}
|
||||
}
|
||||
row := toolResultRaw{
|
||||
ToolCallID: toolCallID,
|
||||
ToolName: toolName,
|
||||
Result: result,
|
||||
IsError: isError,
|
||||
IsMedia: isMedia,
|
||||
ProviderExecuted: providerExecuted,
|
||||
ProviderMetadata: metaJSON,
|
||||
}
|
||||
data, err := json.Marshal([]toolResultRaw{row})
|
||||
if err != nil {
|
||||
return pqtype.NullRawMessage{}, xerrors.Errorf("encode tool result: %w", err)
|
||||
}
|
||||
return pqtype.NullRawMessage{RawMessage: data, Valid: true}, nil
|
||||
}
|
||||
|
||||
// WorkspaceFilePartToTextForTest exposes workspaceFilePartToText for
|
||||
// external tests.
|
||||
var WorkspaceFilePartToTextForTest = workspaceFilePartToText
|
||||
Reference in new issue
Block a user