File tree Expand file tree Collapse file tree 1 file changed +20
-1
lines changed Expand file tree Collapse file tree 1 file changed +20
-1
lines changed Original file line number Diff line number Diff line change @@ -934,13 +934,32 @@ const chatgpt = {
934
934
return reject ( `🤖 chatgpt.js >> Message/response with index ${ msgToGet + 1 } `
935
935
+ ` is out of bounds. Only ${ userMessages . length } messages/responses exist!` )
936
936
937
+ const isUserMessageAncestor = ( messageId , targetUserId ) => {
938
+ let currentId = messageId ;
939
+ const maxDepth = 10 ; // Protection against infinite loops
940
+ let depth = 0 ;
941
+ while ( currentId && depth < maxDepth ) {
942
+ const currentMessage = data [ currentId ] ;
943
+ if ( ! currentMessage ?. message ) {
944
+ return false ;
945
+ }
946
+ if ( currentMessage . id === targetUserId ) {
947
+ return true ;
948
+ }
949
+ currentId = currentMessage . parent ;
950
+ depth ++ ;
951
+ }
952
+ return false ;
953
+ } ;
954
+
937
955
// Fill [chatGPTMessages]
938
956
for ( const userMessage of userMessages ) {
939
957
let sub = [ ]
940
958
for ( const key in data ) {
941
959
if ( data [ key ] . message != null && data [ key ] . message . author . role == 'assistant'
942
- && data [ key ] . parent == userMessage . id )
960
+ && isUserMessageAncestor ( key , userMessage . id ) ) {
943
961
sub . push ( data [ key ] . message )
962
+ }
944
963
}
945
964
sub . sort ( ( a , b ) => a . create_time - b . create_time ) // sort in chronological order
946
965
sub = sub . map ( x => { // pull out msgs after sorting
You can’t perform that action at this time.
0 commit comments