@@ -399,7 +399,7 @@ def reply_to(post, custom_instructions: nil, &blk)
399399 PostCustomPrompt . none
400400
401401 reply = +""
402- start = Time . now
402+ post_streamer = nil
403403
404404 post_type =
405405 post . post_type == Post . types [ :whisper ] ? Post . types [ :whisper ] : Post . types [ :regular ]
@@ -448,6 +448,8 @@ def reply_to(post, custom_instructions: nil, &blk)
448448
449449 context [ :skip_tool_details ] ||= !bot . persona . class . tool_details
450450
451+ post_streamer = PostStreamer . new ( delay : Rails . env . test? ? 0 : 0.5 ) if stream_reply
452+
451453 new_custom_prompts =
452454 bot . reply ( context ) do |partial , cancel , placeholder , type |
453455 reply << partial
@@ -461,22 +463,20 @@ def reply_to(post, custom_instructions: nil, &blk)
461463 reply_post . update! ( raw : reply , cooked : PrettyText . cook ( reply ) )
462464 end
463465
464- if stream_reply
465- # Minor hack to skip the delay during tests.
466- if placeholder . blank?
467- next if ( Time . now - start < 0.5 ) && !Rails . env . test?
468- start = Time . now
469- end
470-
471- Discourse . redis . expire ( redis_stream_key , 60 )
472-
473- publish_update ( reply_post , { raw : raw } )
466+ if post_streamer
467+ post_streamer . run_later {
468+ Discourse . redis . expire ( redis_stream_key , 60 )
469+ publish_update ( reply_post , { raw : raw } )
470+ }
474471 end
475472 end
476473
477474 return if reply . blank?
478475
479476 if stream_reply
477+ post_streamer . finish
478+ post_streamer = nil
479+
480480 # land the final message prior to saving so we don't clash
481481 reply_post . cooked = PrettyText . cook ( reply )
482482 publish_final_update ( reply_post )
@@ -514,6 +514,7 @@ def reply_to(post, custom_instructions: nil, &blk)
514514
515515 reply_post
516516 ensure
517+ post_streamer &.finish ( skip_callback : true )
517518 publish_final_update ( reply_post ) if stream_reply
518519 if reply_post && post . post_number == 1 && post . topic . private_message?
519520 title_playground ( reply_post )
0 commit comments