Plugin Directory

Changeset 3336671


Ignore:
Timestamp:
07/30/2025 01:41:44 PM (7 months ago)
Author:
mxchat
Message:

minor bug fix for streaming responses and enhanced update to loops action email collection.

Location:
mxchat-basic
Files:
95 added
6 edited

Legend:

Unmodified
Added
Removed
  • mxchat-basic/trunk/includes/class-mxchat-addons.php

    r3335923 r3336671  
    161161     */
    162162    public function enqueue_styles() {
    163         $plugin_version = '2.3.3';
     163        $plugin_version = '2.3.4';
    164164
    165165        wp_enqueue_style(
  • mxchat-basic/trunk/includes/class-mxchat-admin.php

    r3335923 r3336671  
    42964296        ? $this->options['triggered_phrase_response']
    42974297        : $default_response;
    4298 
    42994298    echo sprintf(
    43004299        '<textarea id="triggered_phrase_response" name="triggered_phrase_response" rows="3" cols="50">%s</textarea>',
    43014300        esc_textarea($triggered_response)
    43024301    );
    4303     echo '<p class="description">' . esc_html__('Enter the chatbot response when a trigger keyword is detected, prompting the user to share their email.', 'mxchat') . '</p>';
     4302    echo '<p class="description">' . esc_html__('Enter the instruction for the AI when a trigger keyword is detected. The AI will use this as guidance to naturally ask for the user\'s email in a conversational way.', 'mxchat') . '</p>';
    43044303}
    43054304
     
    43094308        ? $this->options['email_capture_response']
    43104309        : $default_response;
    4311 
    43124310    echo sprintf(
    43134311        '<textarea id="email_capture_response" name="email_capture_response" rows="3" cols="50">%s</textarea>',
    43144312        esc_textarea($email_capture_response)
    43154313    );
    4316     echo '<p class="description">' . esc_html__('Enter the message to send when a user provides their email.', 'mxchat') . '</p>';
    4317 }
    4318 
     4314    echo '<p class="description">' . esc_html__('Enter the instruction for the AI when a user provides their email. The AI will use this as guidance to naturally confirm the email capture in a conversational way.', 'mxchat') . '</p>';
     4315}
    43194316public function mxchat_pre_chat_message_callback() {
    43204317    // Load the entire 'mxchat_options' array
     
    56465643public function mxchat_enqueue_admin_assets() {
    56475644    // Get plugin version (define this in your main plugin file)
    5648     $version = defined('MXCHAT_VERSION') ? MXCHAT_VERSION : '2.3.3';
     5645    $version = defined('MXCHAT_VERSION') ? MXCHAT_VERSION : '2.3.4';
    56495646   
    56505647    // Use file modification time for development (remove in production)
     
    61286125    }
    61296126
    6130     // Sanitize Triggered Phrase Response
     6127// Sanitize Triggered Phrase Response
    61316128    if (isset($input['triggered_phrase_response'])) {
    61326129        $new_input['triggered_phrase_response'] = wp_kses_post($input['triggered_phrase_response']);
    61336130    }
    6134 
    61356131    if (isset($input['email_capture_response'])) {
    6136         $new_input['email_capture_response'] = sanitize_textarea_field($input['email_capture_response']);
     6132        $new_input['email_capture_response'] = wp_kses_post($input['email_capture_response']);
    61376133    }
    61386134
  • mxchat-basic/trunk/includes/class-mxchat-integrator.php

    r3335923 r3336671  
    758758    }
    759759
    760     // Check if the message is an email address
    761     if (is_email($message)) {
     760   
     761if (is_email($message)) {
    762762        // Add the email to Loops
    763763        $this->add_email_to_loops($message);
    764    
    765         // Send success response
    766         $response_message = $this->options['email_capture_response'] ??
    767                            esc_html__('Thank you! Your coupon is on the way!', 'mxchat');
    768    
    769         // Clear streaming headers if they were set
    770         if ($is_streaming) {
    771             header_remove('Content-Type');
    772             header_remove('Cache-Control');
    773             header_remove('Connection');
    774             header_remove('X-Accel-Buffering');
    775             header('Content-Type: application/json');
    776         }
    777    
    778         $email_response = [
    779             'success' => true,
    780             'status' => 'email_captured',
    781             'message' => $response_message
    782         ];
    783        
    784         if ($testing_data !== null) {
    785             $email_response['testing_data'] = $testing_data;
    786         }
    787        
    788         wp_send_json($email_response);
    789         wp_die();
     764       
     765        // Get the user's success message instruction
     766        $user_success_message = $this->options['email_capture_response'] ?? __('Thank you for providing your email! You\'ve been added to our list.', 'mxchat');
     767       
     768        // Set instruction for AI using the user's success message
     769        $this->current_action_instruction = $user_success_message;
     770       
     771        // Clear the email capture transient since we got the email
     772        delete_transient('mxchat_email_capture_' . $user_id);
     773    }
     774   
     775    // NEW: Check if we're in an email capture flow but user hasn't provided email yet
     776    elseif (get_transient('mxchat_email_capture_' . $user_id)) {
     777        // Check if the message contains an email (not the whole message being an email)
     778        if (preg_match('/\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b/', $message, $matches)) {
     779            $extracted_email = $matches[0];
     780           
     781            // Add the extracted email to Loops
     782            $this->add_email_to_loops($extracted_email);
     783           
     784            // Get the user's success message instruction
     785            $user_success_message = $this->options['email_capture_response'] ?? __('Thank you for providing your email! You\'ve been added to our list.', 'mxchat');
     786           
     787            // Set instruction for AI using the user's success message
     788            $this->current_action_instruction = $user_success_message;
     789           
     790            // Clear the email capture transient since we got the email
     791            delete_transient('mxchat_email_capture_' . $user_id);
     792        }
     793        // If no email found but we're in capture mode, remind them
     794        else {
     795            // Get the original instruction to remind them
     796            $original_instruction = $this->options['triggered_phrase_response'] ?? __("Please provide your email address.", 'mxchat');
     797            $this->current_action_instruction = $original_instruction;
     798        }
    790799    }
    791800
     
    10691078    // Build context with both knowledge base and PDF content if available
    10701079    $context_content = "User asked: '{$message}'\n\n";
     1080   
     1081    // NEW: Add action instruction if present (add this right after the above line)
     1082    if (!empty($this->current_action_instruction)) {
     1083        $context_content .= "===== SPECIAL INSTRUCTION =====\n";
     1084        $context_content .= "IMPORTANT: " . $this->current_action_instruction . "\n";
     1085        $context_content .= "Respond naturally and conversationally while following this instruction.\n";
     1086        $context_content .= "===== END SPECIAL INSTRUCTION =====\n\n";
     1087       
     1088        // Clear the instruction after using it
     1089        $this->current_action_instruction = null;
     1090    }
     1091
    10711092
    10721093    // NEW: Add page context if available and contextual awareness is enabled
     
    13471368//verified good
    13481369public function mxchat_handle_email_capture($message, $user_id, $session_id) {
    1349     // Log the message safely
    1350     //error_log("Triggered email capture intent for message: " . sanitize_text_field($message));
    1351 
    1352     // Initiate email capture flow
    1353     $response = esc_html($this->options['triggered_phrase_response'] ?? esc_html__("Would you like to join our mailing list? Please provide your email below.", 'mxchat'));
     1370    // Get the user's original instruction/message
     1371    $user_instruction = esc_html($this->options['triggered_phrase_response'] ?? esc_html__("Please provide your email address.", 'mxchat'));
     1372   
     1373    // Set instruction for AI - just pass along what the user wanted to say
     1374    $this->current_action_instruction = $user_instruction;
     1375   
     1376    // Set the transient to track email capture flow
    13541377    set_transient('mxchat_email_capture_' . $user_id, true, 5 * MINUTE_IN_SECONDS);
    1355     $this->mxchat_save_chat_message($session_id, 'bot', $response);
    1356    
    1357     // FIXED: Return response data instead of sending JSON directly
    1358     // This allows the main chat handler to add testing data before sending
    1359     return [
    1360         'text' => $response,
    1361         'html' => '',
    1362         'session_id' => $session_id
    1363     ];
     1378   
     1379    // Return false to let the AI generate the response
     1380    return false;
    13641381}
    13651382
     
    52945311public function mxchat_enqueue_scripts_styles() {
    52955312    // Define version numbers for the styles and scripts
    5296     $chat_style_version = '2.3.3';
    5297     $chat_script_version = '2.3.3';
     5313    $chat_style_version = '2.3.4';
     5314    $chat_script_version = '2.3.4';
    52985315    // Enqueue the script
    52995316    wp_enqueue_script(
  • mxchat-basic/trunk/js/chat-script.js

    r3335923 r3336671  
    509509            //console.log("Received JSON response instead of stream, handling as regular response");
    510510            return response.json().then(data => {
    511 
     511                // Handle as regular JSON response
     512                $('.bot-message.temporary-message').remove();
     513               
    512514                // FIXED: Always check for testing panel, not just in testing mode
    513515                if (window.mxchatTestPanelInstance && data.testing_data) {
     
    515517                    window.mxchatTestPanelInstance.handleTestingData(data.testing_data);
    516518                }
    517                
    518                 // Handle as regular JSON response
    519                 $('.bot-message.temporary-message').remove();
    520519               
    521520                // Handle different response formats (including intent responses)
     
    557556        }
    558557
    559         // Continue with streaming processing
    560         const reader = response.body.getReader();
    561         const decoder = new TextDecoder();
    562         let buffer = '';
    563 
    564         function processStream() {
    565             reader.read().then(({ done, value }) => {
    566                 if (done) {
    567                     //console.log("Streaming completed, final content:", accumulatedContent);
    568                     if (callback) {
    569                         callback(accumulatedContent);
     558        // NEW: Check if it's event-stream but might contain JSON (Cloudflare issue)
     559        if (contentType && contentType.includes('text/event-stream')) {
     560            // First, try to read the entire response to check if it's actually JSON
     561            return response.text().then(fullText => {
     562                // Check if the response looks like a single JSON object instead of SSE format
     563                const trimmedText = fullText.trim();
     564                if (trimmedText.startsWith('{') && trimmedText.endsWith('}') && !trimmedText.includes('data: ')) {
     565                    //console.log("Detected JSON in event-stream wrapper, parsing as JSON fallback");
     566                    try {
     567                        const data = JSON.parse(trimmedText);
     568                       
     569                        // Handle as regular JSON response
     570                        $('.bot-message.temporary-message').remove();
     571                       
     572                        // Check for testing panel data
     573                        if (window.mxchatTestPanelInstance && data.testing_data) {
     574                            window.mxchatTestPanelInstance.handleTestingData(data.testing_data);
     575                        }
     576                       
     577                        // Handle response content
     578                        if (data.text || data.html || data.message) {
     579                            if (data.text && typeof customMxChatFilter === 'function') {
     580                                data.text = customMxChatFilter(data.text, "response");
     581                            }
     582                            if (data.message && typeof customMxChatFilter === 'function') {
     583                                data.message = customMxChatFilter(data.message, "response");
     584                            }
     585                           
     586                            if (data.text && data.html) {
     587                                replaceLastMessage("bot", data.text, data.html);
     588                            } else if (data.text) {
     589                                replaceLastMessage("bot", data.text);
     590                            } else if (data.html) {
     591                                replaceLastMessage("bot", "", data.html);
     592                            } else if (data.message) {
     593                                replaceLastMessage("bot", data.message);
     594                            }
     595                        }
     596                       
     597                        // Handle other response properties
     598                        if (data.chat_mode) {
     599                            updateChatModeIndicator(data.chat_mode);
     600                        }
     601                       
     602                        if (data.data && data.data.filename) {
     603                            showActivePdf(data.data.filename);
     604                            activePdfFile = data.data.filename;
     605                        }
     606                       
     607                        if (callback) {
     608                            callback(data.text || data.message || '');
     609                        }
     610                       
     611                        return; // Exit early, we handled it as JSON
     612                    } catch (e) {
     613                        //console.log("Failed to parse as JSON, continuing with streaming logic");
    570614                    }
    571                     return;
    572                 }
    573 
    574                 buffer += decoder.decode(value, { stream: true });
    575                 const lines = buffer.split('\n');
    576                 buffer = lines.pop() || '';
    577 
     615                }
     616               
     617                // If we get here, it's actual streaming data, process it normally
     618                const lines = fullText.split('\n');
     619                let buffer = '';
     620               
    578621                for (const line of lines) {
    579622                    if (line.startsWith('data: ')) {
     
    591634                            const json = JSON.parse(data);
    592635                           
    593                             // FIXED: Always check for testing panel and handle testing data properly
     636                            // Handle testing data
    594637                            if (json.testing_data && !testingDataReceived) {
    595638                                //console.log('Testing data received in stream:', json.testing_data);
     
    615658                    }
    616659                }
    617 
    618                 processStream();
     660               
     661                if (callback) {
     662                    callback(accumulatedContent);
     663                }
    619664            });
    620665        }
    621666
    622         processStream();
     667        // If we get here, something unexpected happened, fall back to regular processing
     668        //console.log("Unexpected content type, falling back to text processing");
     669        return response.text().then(text => {
     670            //console.log("Raw response text:", text);
     671            // Try to extract any meaningful content and display it
     672            replaceLastMessage("bot", "Received response but couldn't process streaming format. Please try again.");
     673        });
    623674    })
    624675    .catch(error => {
    625676        //console.error('Streaming error:', error);
     677        // Fall back to regular chat on any error
    626678        callMxChat(message, callback);
    627679    });
    628680}
     681
    629682
    630683// Function to update message during streaming
  • mxchat-basic/trunk/mxchat-basic.php

    r3335923 r3336671  
    33 * Plugin Name: MxChat
    44 * Description: AI chatbot for WordPress with OpenAI, Claude, xAI, DeepSeek, live agent, PDF uploads, WooCommerce, and training on website data.
    5  * Version: 2.3.3
     5 * Version: 2.3.4
    66 * Author: MxChat
    77 * Author URI: https://mxchat.ai
     
    1717
    1818// Define plugin version constant for asset versioning
    19 define('MXCHAT_VERSION', '2.3.3');
     19define('MXCHAT_VERSION', '2.3.4');
    2020
    2121function mxchat_load_textdomain() {
  • mxchat-basic/trunk/readme.txt

    r3335923 r3336671  
    66Tested up to: 6.8
    77Requires PHP: 7.2
    8 Stable tag: 2.3.3
     8Stable tag: 2.3.4
    99License: GPLv2 or later
    1010License URI: https://www.gnu.org/licenses/gpl-2.0.html
     
    175175== Changelog ==
    176176
     177= 2.3.4 - July 30, 2025 =
     178- Fixed streaming compatibility issues with Cloudflare and WP Engine by implementing automatic fallback to regular chat when streaming is buffered.
     179- Enhanced email capture intents to use AI-generated conversational responses instead of hard-coded messages, allowing for more natural user interactions while maintaining the same functionality.
     180
    177181= 2.3.3 - July 29, 2025 =
    178182- Improved streaming performance by fixing output buffering issues using enhanced flush logic.
     
    489493== Upgrade Notice ==
    490494
    491 = 2.3.3 =
    492 This update brings faster streaming, smarter license management, and more intelligent AI behavior.
    493 - Streaming is now smoother and more responsive thanks to improved output flushing.
    494 - License keys can now be activated, deactivated, and tracked by domain.
    495 - Add contextual guidance to your chatbot using new `data-mxchat-context` HTML attributes.
    496 - Transcript timestamps now respect your WordPress site's timezone for accurate conversation history.
     495= 2.3.4 =
     496- Fixed streaming compatibility issues with Cloudflare and WP Engine by implementing automatic fallback to regular chat when streaming is buffered.
     497- Enhanced email capture intents to use AI-generated conversational responses instead of hard-coded messages, allowing for more natural user interactions while maintaining the same functionality.
    497498
    498499== License & Warranty ==
Note: See TracChangeset for help on using the changeset viewer.