@@ -16,6 +16,11 @@ const image = (data: string): Anthropic.Messages.ImageBlockParam => ({
1616 source : { type : "base64" , media_type : "image/jpeg" , data } ,
1717} )
1818const text = ( value : string ) : Anthropic . Messages . TextBlockParam => ( { type : "text" , text : value } )
19+ const nested = ( id : string , content : Anthropic . Messages . ToolResultBlockParam [ "content" ] ) => ( {
20+ type : "tool_result" as const ,
21+ tool_use_id : id ,
22+ content,
23+ } )
1924
2025describe ( "orderToolResultsFirst" , ( ) => {
2126 it ( "repairs the persisted #1774 shape so every tool_result leads the message" , ( ) => {
@@ -29,10 +34,10 @@ describe("orderToolResultsFirst", () => {
2934
3035 const [ repaired ] = orderToolResultsFirst ( [ stuck ] )
3136
37+ // The image moves into the read_file result, the shape the Anthropic API expects.
3238 expect ( repaired . content ) . toEqual ( [
33- toolResult ( "read" ) ,
39+ nested ( "read" , [ text ( "result read" ) , image ( "jpeg" ) ] ) ,
3440 toolResult ( "cmd" ) ,
35- image ( "jpeg" ) ,
3641 text ( "<environment_details>" ) ,
3742 ] )
3843 expect ( repaired . ts ) . toBe ( 16 )
@@ -55,14 +60,39 @@ describe("orderToolResultsFirst", () => {
5560
5661 expect ( repaired . content ) . toEqual ( [
5762 toolResult ( "a" ) ,
58- toolResult ( "b" ) ,
59- toolResult ( "c" ) ,
60- image ( "1" ) ,
61- image ( "2" ) ,
63+ nested ( "b" , [ text ( "result b" ) , image ( "1" ) ] ) ,
64+ nested ( "c" , [ text ( "result c" ) , image ( "2" ) ] ) ,
6265 text ( "t" ) ,
6366 ] )
6467 } )
6568
69+ it ( "appends an image to a result whose content is already an array" , ( ) => {
70+ const withArray = nested ( "a" , [ text ( "first" ) , text ( "second" ) ] )
71+
72+ const [ repaired ] = orderToolResultsFirst ( [ { role : "user" , content : [ withArray , image ( "1" ) , toolResult ( "b" ) ] } ] )
73+
74+ expect ( repaired . content ) . toEqual ( [ nested ( "a" , [ text ( "first" ) , text ( "second" ) , image ( "1" ) ] ) , toolResult ( "b" ) ] )
75+ // The original result block is not mutated.
76+ expect ( withArray . content ) . toEqual ( [ text ( "first" ) , text ( "second" ) ] )
77+ } )
78+
79+ it ( "keeps an image standalone when no result directly precedes it" , ( ) => {
80+ const [ repaired ] = orderToolResultsFirst ( [
81+ {
82+ role : "user" ,
83+ content : [ image ( "lead" ) , toolResult ( "a" ) , text ( "note" ) , image ( "after-text" ) , toolResult ( "b" ) ] ,
84+ } ,
85+ ] )
86+
87+ expect ( repaired . content ) . toEqual ( [
88+ toolResult ( "a" ) ,
89+ toolResult ( "b" ) ,
90+ image ( "lead" ) ,
91+ text ( "note" ) ,
92+ image ( "after-text" ) ,
93+ ] )
94+ } )
95+
6696 it ( "repairs interleaving introduced by merging consecutive user messages" , ( ) => {
6797 const merged = mergeConsecutiveApiMessages ( [
6898 { role : "user" , content : [ toolResult ( "a" ) , text ( "note" ) ] } ,
0 commit comments