@@ -99,40 +99,43 @@ func findUserInputStartIdx(msg []rune, msgRuneLineLocations []int, userInput []r
9999 return IndexSubslice (msgPrefix , userInputPrefix )
100100}
101101
102+ // Find the next match between the message and the user input.
103+ // We're assuming that user input likely won't be truncated much,
104+ // but it's likely some characters will be missing (e.g. OpenAI Codex strips
105+ // "```" and instead formats enclosed text as a code block).
106+ // We're going to see if any of the next 5 runes in the message
107+ // match any of the next 5 runes in the user input.
108+ func findNextMatch (knownMsgMatchIdx int , knownUserInputMatchIdx int , msg []rune , userInput []rune ) (int , int ) {
109+ for i := range 5 {
110+ for j := range 5 {
111+ userInputIdx := knownUserInputMatchIdx + i + 1
112+ msgIdx := knownMsgMatchIdx + j + 1
113+
114+ if userInputIdx >= len (userInput ) || msgIdx >= len (msg ) {
115+ return - 1 , - 1
116+ }
117+ if userInput [userInputIdx ] == msg [msgIdx ] {
118+ return msgIdx , userInputIdx
119+ }
120+ }
121+ }
122+ return - 1 , - 1
123+ }
124+
102125// Find where the user input ends in the message. Returns the index of the last rune
103126// of the user input in the message.
104127func findUserInputEndIdx (userInputStartIdx int , msg []rune , userInput []rune ) int {
105128 userInputIdx := 0
106129 msgIdx := userInputStartIdx
107- OuterLoop:
108130 for {
109- if userInputIdx >= len (userInput ) {
131+ m , u := findNextMatch (msgIdx , userInputIdx , msg , userInput )
132+ if m == - 1 || u == - 1 {
110133 break
111134 }
112- if msgIdx >= len (msg ) {
113- break
114- }
115- if userInput [userInputIdx ] == msg [msgIdx ] {
116- userInputIdx ++
117- msgIdx ++
118- continue
119- }
120- // If we haven't found a match, we'll search the next 5 runes of the message.
121- // If we can't find a match, we'll assume the echoed user input was truncated.
122- // 5 is arbitrary.
123- for i := 1 ; i <= 5 ; i ++ {
124- if msgIdx + i >= len (msg ) {
125- break
126- }
127- if userInput [userInputIdx ] == msg [msgIdx + i ] {
128- userInputIdx ++
129- msgIdx = msgIdx + i
130- continue OuterLoop
131- }
132- }
133- break
135+ msgIdx = m
136+ userInputIdx = u
134137 }
135- return msgIdx - 1
138+ return msgIdx
136139}
137140
138141// RemoveUserInput removes the user input from the message.
0 commit comments