PluginProbe
MxChat – AI Chatbot & Content Generation for WordPress / 3.2.24
MxChat – AI Chatbot & Content Generation for WordPress v3.2.24
3.2.25 3.2.24 3.2.23 3.2.22 3.2.21 3.2.20 3.2.19 3.2.18 3.2.17 3.2.16 3.2.15 3.2.14 3.2.12 3.2.13 3.2.11 3.2.10 3.2.9 3.2.8 3.2.7 3.2.6 3.2.5 3.2.4 3.2.3 3.2.2 3.2.1 All 156 releases
← All changes | includes/admin-knowledge-page.php +952 -120 3.2.10 → 3.2.24 View file →
@@ -73,9 +73,9 @@
73 73 <span><?php esc_html_e('Auto-Sync', 'mxchat'); ?></span>
74 74 </button>
75 75 <button class="mxch-mobile-nav-link" data-target="chunking">
76 76 <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="7" height="7"/><rect x="14" y="3" width="7" height="7"/><rect x="14" y="14" width="7" height="7"/><rect x="3" y="14" width="7" height="7"/></svg>
77 - <span><?php esc_html_e('Content Chunking', 'mxchat'); ?></span>
77 + <span><?php esc_html_e('Chunking & Retrieval', 'mxchat'); ?></span>
78 78 </button>
79 79 <button class="mxch-mobile-nav-link" data-target="role-restrictions">
80 80 <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/></svg>
81 81 <span><?php esc_html_e('Role Restrictions', 'mxchat'); ?></span>
@@ -172,9 +172,9 @@
172 172 <button class="mxch-nav-link" data-target="chunking">
173 173 <span class="mxch-nav-link-icon">
174 174 <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="7" height="7"/><rect x="14" y="3" width="7" height="7"/><rect x="14" y="14" width="7" height="7"/><rect x="3" y="14" width="7" height="7"/></svg>
175 175 </span>
176 - <span class="mxch-nav-link-text"><?php esc_html_e('Content Chunking', 'mxchat'); ?></span>
176 + <span class="mxch-nav-link-text"><?php esc_html_e('Chunking & Retrieval', 'mxchat'); ?></span>
177 177 </button>
178 178 </div>
179 179
180 180 <div class="mxch-nav-item" data-section="role-restrictions">
@@ -275,13 +275,35 @@
275 275
276 276 // Render the Edit Entry Modal
277 277 mxchat_render_edit_entry_modal();
278 278
279 + // Render the read-only Knowledge Inspector modal (plan-d8cb4b)
280 + mxchat_render_inspect_entry_modal();
281 +
279 282 // Render the navigation JavaScript
280 283 mxchat_render_knowledge_page_scripts();
281 284 }
282 285
283 286 /**
287 + * Whether the selected bot answers from the WordPress database (plan 1f39d9).
288 + * That store is one table every bot reads. A bot has knowledge of its own only
289 + * on Pinecone (its own host or namespace) or an OpenAI Vector Store, so the
290 + * selector must not promise a per-bot knowledge base here.
291 + */
292 +function mxchat_knowledge_bot_uses_shared_database($bot_id) {
293 + $pinecone = class_exists('MxChat_Pinecone_Documents') ? MxChat_Pinecone_Documents::config($bot_id) : array();
294 + if (!empty($pinecone['use_pinecone'])) {
295 + return false;
296 + }
297 + $vectorstore_options = get_option('mxchat_openai_vectorstore_options', array());
298 + $vectorstore = apply_filters('mxchat_get_bot_vectorstore_config', array(
299 + 'use_vectorstore' => (is_array($vectorstore_options) ? ($vectorstore_options['mxchat_use_openai_vectorstore'] ?? '0') : '0') === '1',
300 + 'vectorstore_ids' => is_array($vectorstore_options) ? ($vectorstore_options['mxchat_vectorstore_ids'] ?? '') : '',
301 + ), $bot_id);
302 + return empty($vectorstore['use_vectorstore']);
303 +}
304 +
305 +/**
284 306 * Render Multi-Bot Selector
285 307 */
286 308 function mxchat_render_knowledge_bot_selector($multibot_active, $current_bot_id) {
287 309 if (!$multibot_active || !class_exists('MxChat_Multi_Bot_Manager')) {
@@ -304,9 +326,15 @@
304 326 </option>
305 327 <?php endforeach; ?>
306 328 </select>
307 329 <span style="color: var(--mxch-text-secondary); font-size: 13px;">
308 - <?php esc_html_e('Content will be added to the selected bot\'s knowledge base', 'mxchat'); ?>
330 + <?php
331 + if (mxchat_knowledge_bot_uses_shared_database($current_bot_id)) {
332 + esc_html_e('This bot answers from the WordPress database, which is shared with all bots: content added here is available to every bot that uses it. A bot gets a knowledge base of its own on Pinecone (its own host or namespace) or an OpenAI Vector Store.', 'mxchat');
333 + } else {
334 + esc_html_e('Content will be added to the selected bot\'s knowledge base', 'mxchat');
335 + }
336 + ?>
309 337 </span>
310 338 <span id="mxchat-bot-save-status" style="display: none; color: var(--mxch-success); font-size: 13px;">
311 339 ✓ <?php esc_html_e('Saved', 'mxchat'); ?>
312 340 </span>
@@ -436,8 +464,20 @@
436 464 $required_key_type = 'Voyage AI';
437 465 } elseif (strpos($embedding_model, 'gemini-embedding-') !== false) {
438 466 $required_key_type = 'Google Gemini';
439 467 }
468 +
469 + // Custom Provider embeddings (plan 418afd): the dropdown above is disabled
470 + // on such a site and no OpenAI, Voyage or Gemini key is needed. Ask the
471 + // same pre-flight the importers ask, so this notice cannot disagree with them.
472 + $embeds_with_custom_provider = is_array($options) && isset($options['custom_provider_for_embeddings']) && $options['custom_provider_for_embeddings'] === 'on';
473 + $custom_embedding_blocker = '';
474 + if ($embeds_with_custom_provider) {
475 + $custom_preflight = MxChat_Utils::embedding_preflight($options);
476 + $has_required_key = !empty($custom_preflight['ok']);
477 + $required_key_type = 'Custom Provider';
478 + $custom_embedding_blocker = (string) ($custom_preflight['reason'] ?? '');
479 + }
440 480 ?>
441 481 <div id="import-options" class="mxch-section active">
442 482 <div class="mxch-content-header">
443 483 <h1 class="mxch-content-title"><?php esc_html_e('Import Options', 'mxchat'); ?></h1>
@@ -453,9 +493,18 @@
453 493 <path d="m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3Z"/><line x1="12" y1="9" x2="12" y2="13"/><line x1="12" y1="17" x2="12.01" y2="17"/>
454 494 <?php endif; ?>
455 495 </svg>
456 496 <div>
457 - <?php if ($has_required_key): ?>
497 + <?php if ($embeds_with_custom_provider && $has_required_key): ?>
498 + <?php
499 + /* translators: %s: the embedding model name configured on the Custom Provider */
500 + printf(esc_html__('Knowledge is embedded through your Custom Provider (model: %s). No OpenAI, Voyage AI or Google Gemini key is needed for imports.', 'mxchat'), esc_html(MxChat_Utils::resolve_custom_embedding_model($options)));
501 + ?>
502 + <?php elseif ($embeds_with_custom_provider): ?>
503 + <strong><?php esc_html_e('Important:', 'mxchat'); ?></strong>
504 + <?php echo esc_html($custom_embedding_blocker); ?>
505 + <a href="<?php echo admin_url('admin.php?page=mxchat-max#api-keys'); ?>"><?php esc_html_e('Go to API Key Settings', 'mxchat'); ?></a>
506 + <?php elseif ($has_required_key): ?>
458 507 <?php echo wp_kses_post(sprintf(__('We detected your %s API key. <strong>Remember to add credits to your %s account</strong> before using the knowledgebase.', 'mxchat'), $required_key_type, $required_key_type)); ?>
459 508 <?php else: ?>
460 509 <strong><?php esc_html_e('Important:', 'mxchat'); ?></strong>
461 510 <?php echo sprintf(esc_html__('Before importing knowledge, you must add a %s API key with sufficient credits in the Chatbot settings.', 'mxchat'), $required_key_type); ?>
@@ -552,8 +601,30 @@
552 601 <h4><?php esc_html_e('PDF Upload', 'mxchat'); ?></h4>
553 602 <p><?php esc_html_e('Upload a PDF file from your computer.', 'mxchat'); ?></p>
554 603 </div>
555 604 </button>
605 +
606 + <!-- Document File Upload Option (plan 0485e5) -->
607 + <button type="button" class="mxchat-import-box" data-option="document-upload" data-type="document-upload">
608 + <div class="mxchat-import-icon">
609 + <span class="dashicons dashicons-media-text"></span>
610 + </div>
611 + <div class="mxchat-import-content">
612 + <h4><?php esc_html_e('Document Upload', 'mxchat'); ?></h4>
613 + <p><?php esc_html_e('Upload a Word document, text, or Markdown file (.docx, .txt, .md).', 'mxchat'); ?></p>
614 + </div>
615 + </button>
616 +
617 + <!-- YouTube Video Import Option -->
618 + <button type="button" class="mxchat-import-box" data-option="youtube" data-type="youtube">
619 + <div class="mxchat-import-icon">
620 + <span class="dashicons dashicons-youtube"></span>
621 + </div>
622 + <div class="mxchat-import-content">
623 + <h4><?php esc_html_e('YouTube', 'mxchat'); ?></h4>
624 + <p><?php esc_html_e('Index a video so the chat can surface it as a playable embed.', 'mxchat'); ?></p>
625 + </div>
626 + </button>
556 627 </div>
557 628
558 629 <!-- Detected Sitemaps Section (hidden by default, shown when Sitemap Import is clicked) -->
559 630 <div id="mxchat-detected-sitemaps" class="mxchat-detected-sitemaps" style="display: none;">
@@ -650,13 +721,89 @@
650 721 </div>
651 722 <p class="mxch-field-description">
652 723 <?php esc_html_e('Select a PDF file from your computer to import into the knowledge base. Maximum file size depends on your server settings.', 'mxchat'); ?>
653 724 </p>
725 + <div class="mxch-field">
726 + <input type="url" name="source_page_url" id="mxchat-pdf-source-url" class="mxch-input" placeholder="<?php esc_attr_e('Enter source URL (Optional)', 'mxchat'); ?>">
727 + <p class="mxch-field-description">
728 + <?php esc_html_e('The page this PDF lives on. Answers drawn from it link to that page. Leave empty and answers name the file and page without a link.', 'mxchat'); ?>
729 + </p>
730 + </div>
654 731 <button type="submit" name="submit_pdf_file" class="mxch-btn mxch-btn-primary">
655 732 <?php esc_html_e('Import PDF', 'mxchat'); ?>
656 733 </button>
657 734 </form>
658 735 </div>
736 +
737 + <div class="mxchat-import-input-area" id="mxchat-document-upload-area" style="display: none; margin-top: 20px;">
738 + <form id="mxchat-document-upload-form" method="post" action="<?php echo esc_url(admin_url('admin-post.php?action=mxchat_submit_document_file')); ?>" enctype="multipart/form-data">
739 + <?php wp_nonce_field('mxchat_submit_document_file_action', 'mxchat_submit_document_file_nonce'); ?>
740 + <?php if ($multibot_active && $current_bot_id !== 'default') : ?>
741 + <input type="hidden" name="bot_id" value="<?php echo esc_attr($current_bot_id); ?>">
742 + <?php endif; ?>
743 + <div class="mxch-field">
744 + <input type="file" name="document_file" id="mxchat-document-file-input" accept=".docx,.txt,.md" required>
745 + </div>
746 + <p class="mxch-field-description">
747 + <?php esc_html_e('Select a .docx, .txt, or .md file to import into the knowledge base. The text is extracted and indexed; the file itself is not stored. Re-uploading a file with the same name replaces its previous content.', 'mxchat'); ?>
748 + </p>
749 + <div class="mxch-field">
750 + <input type="url" name="source_page_url" id="mxchat-document-source-url" class="mxch-input" placeholder="<?php esc_attr_e('Enter source URL (Optional)', 'mxchat'); ?>">
751 + <p class="mxch-field-description">
752 + <?php esc_html_e('The page this document lives on. Answers drawn from it link to that page. Leave empty and answers name the file without a link.', 'mxchat'); ?>
753 + </p>
754 + </div>
755 + <button type="submit" name="submit_document_file" class="mxch-btn mxch-btn-primary">
756 + <?php esc_html_e('Import Document', 'mxchat'); ?>
757 + </button>
758 + </form>
759 + </div>
760 +
761 + <?php
762 + // Prefill state: set when an auto-import found no transcript — the
763 + // handler bounced back here so the admin can augment the entry with
764 + // a manual description (re-importing the same URL updates the row).
765 + $yt_prefill = isset($_GET['mxchat_yt_prefill']) && $_GET['mxchat_yt_prefill'] === '1';
766 + $yt_prefill_url = $yt_prefill && isset($_GET['yt_url']) ? esc_url_raw(rawurldecode(wp_unslash($_GET['yt_url']))) : '';
767 + $yt_prefill_title = $yt_prefill && isset($_GET['yt_title']) ? sanitize_text_field(rawurldecode(wp_unslash($_GET['yt_title']))) : '';
768 + ?>
769 + <div class="mxchat-import-input-area" id="mxchat-youtube-input-area" style="display: none; margin-top: 20px;">
770 + <form id="mxchat-youtube-form" method="post" action="<?php echo esc_url(admin_url('admin-post.php?action=mxchat_submit_youtube')); ?>"<?php echo $yt_prefill ? ' data-yt-prefill="1"' : ''; ?>>
771 + <?php wp_nonce_field('mxchat_submit_youtube_action', 'mxchat_submit_youtube_nonce'); ?>
772 + <?php if ($multibot_active && $current_bot_id !== 'default') : ?>
773 + <input type="hidden" name="bot_id" value="<?php echo esc_attr($current_bot_id); ?>">
774 + <?php endif; ?>
775 + <div class="mxch-field">
776 + <input type="url" name="youtube_url" id="mxchat-youtube-url" class="mxch-input" placeholder="<?php esc_attr_e('Paste a YouTube video URL (watch, youtu.be, or Shorts link)', 'mxchat'); ?>" required value="<?php echo esc_attr($yt_prefill_url); ?>">
777 + </div>
778 + <div class="mxch-field">
779 + <span class="mxch-field-label"><?php esc_html_e('How should this video be described for matching?', 'mxchat'); ?></span>
780 + <div style="display: flex; flex-direction: column; gap: 6px; margin-top: 8px;">
781 + <label style="display: flex; align-items: baseline; gap: 8px; cursor: pointer;">
782 + <input type="radio" name="youtube_description_mode" value="auto" <?php checked(!$yt_prefill); ?>>
783 + <span>
784 + <strong><?php esc_html_e('Auto-fetch', 'mxchat'); ?></strong>
785 + <span class="mxch-field-description" style="display: block; margin: 2px 0 0;"><?php esc_html_e('We pull the video\'s title, channel, and captions (when available) to describe it.', 'mxchat'); ?></span>
786 + </span>
787 + </label>
788 + <label style="display: flex; align-items: baseline; gap: 8px; cursor: pointer;">
789 + <input type="radio" name="youtube_description_mode" value="manual" <?php checked($yt_prefill); ?>>
790 + <span>
791 + <strong><?php esc_html_e('Write my own', 'mxchat'); ?></strong>
792 + <span class="mxch-field-description" style="display: block; margin: 2px 0 0;"><?php esc_html_e('You write the description the chatbot matches against — best for curated guides.', 'mxchat'); ?></span>
793 + </span>
794 + </label>
795 + </div>
796 + </div>
797 + <div class="mxch-field" id="mxchat-youtube-description-field" style="<?php echo $yt_prefill ? '' : 'display: none;'; ?>">
798 + <textarea name="youtube_description" id="mxchat-youtube-description" class="mxch-textarea" rows="5" placeholder="<?php esc_attr_e('Describe what this video covers and the questions it answers...', 'mxchat'); ?>"><?php echo esc_textarea($yt_prefill_title !== '' ? $yt_prefill_title . "\n\n" : ''); ?></textarea>
799 + <p class="mxch-field-description"><?php esc_html_e('This text is what gets matched against visitor questions. Importing the same video URL again updates its existing entry.', 'mxchat'); ?></p>
800 + </div>
801 + <button type="submit" name="submit_youtube" value="1" class="mxch-btn mxch-btn-primary">
802 + <?php esc_html_e('Import Video', 'mxchat'); ?>
803 + </button>
804 + </form>
805 + </div>
659 806 <?php endif; ?>
660 807 </div>
661 808 </div>
662 809 </div>
@@ -807,9 +954,10 @@
807 954 <div class="mxch-card">
808 955 <div class="mxch-card-header">
809 956 <h3 class="mxch-card-title">
810 957 <?php esc_html_e('Knowledge Entries', 'mxchat'); ?>
811 - <span id="mxchat-entry-count" style="font-weight: normal; color: var(--mxch-text-secondary);">(<?php echo esc_html($total_records); ?>)</span>
958 + <?php $count_unit = $count_unit ?? ''; ?>
959 + <span id="mxchat-entry-count" style="font-weight: normal; color: var(--mxch-text-secondary);" data-count="<?php echo esc_attr($total_records); ?>" data-unit="<?php echo esc_attr($count_unit); ?>"<?php if ($count_unit === 'vectors') : ?> title="<?php esc_attr_e('Pinecone reports vectors, not documents; a long entry is stored as several vectors.', 'mxchat'); ?>"<?php endif; ?>>(<?php echo esc_html(number_format_i18n($total_records)); ?><?php if ($count_unit === 'vectors') : ?> <?php esc_html_e('vectors', 'mxchat'); ?><?php endif; ?>)</span>
812 960 <?php if (!empty($use_vectorstore)) : ?>
813 961 <span style="display: inline-flex; align-items: center; gap: 4px; padding: 4px 8px; border-radius: 12px; font-size: 12px; font-weight: 500; margin-left: 8px; background: #fff3e0; color: #e65100;">
814 962 <span class="dashicons dashicons-database" style="font-size: 14px;"></span>
815 963 <?php esc_html_e('Not in use', 'mxchat'); ?>
@@ -989,10 +1137,19 @@
989 1137 <span style="color: var(--mxch-text-muted);"><?php esc_html_e('Manual Content', 'mxchat'); ?></span>
990 1138 <?php endif; ?>
991 1139 </td>
992 1140 <td class="mxchat-actions-cell" style="padding: 12px 16px; white-space: nowrap;">
993 - <?php if ($data_source !== 'pinecone') : ?>
994 1141 <button type="button"
1142 + class="mxch-btn mxch-btn-ghost mxch-btn-sm mxchat-inspect-entry-btn"
1143 + data-source-url="<?php echo esc_attr($source_url); ?>"
1144 + data-entry-id="<?php echo esc_attr($first_prompt->id); ?>"
1145 + data-data-source="<?php echo esc_attr($data_source); ?>"
1146 + data-bot-id="<?php echo esc_attr($current_bot_id); ?>"
1147 + data-nonce="<?php echo wp_create_nonce('mxchat_inspect_entry_nonce'); ?>"
1148 + title="<?php esc_attr_e('View indexed content', 'mxchat'); ?>">
1149 + <span class="dashicons dashicons-visibility" style="font-size: 14px;"></span>
1150 + </button>
1151 + <button type="button"
995 1152 class="mxch-btn mxch-btn-ghost mxch-btn-sm mxchat-edit-entry-btn"
996 1153 data-source-url="<?php echo esc_attr($source_url); ?>"
997 1154 data-entry-id="<?php echo esc_attr($first_prompt->id); ?>"
998 1155 data-data-source="<?php echo esc_attr($data_source); ?>"
@@ -1000,9 +1157,8 @@
1000 1157 data-nonce="<?php echo wp_create_nonce('mxchat_edit_entry_nonce'); ?>"
1001 1158 title="<?php esc_attr_e('Edit content', 'mxchat'); ?>">
1002 1159 <span class="dashicons dashicons-edit" style="font-size: 14px;"></span>
1003 1160 </button>
1004 - <?php endif; ?>
1005 1161 <button type="button"
1006 1162 class="mxch-btn mxch-btn-ghost mxch-btn-sm delete-button-group"
1007 1163 data-source-url="<?php echo esc_attr($source_url); ?>"
1008 1164 data-chunk-count="<?php echo esc_attr($chunk_count); ?>"
@@ -1139,10 +1295,19 @@
1139 1295 <span style="color: var(--mxch-text-muted);"><?php esc_html_e('Manual', 'mxchat'); ?></span>
1140 1296 <?php endif; ?>
1141 1297 </td>
1142 1298 <td style="padding: 12px 16px; white-space: nowrap;">
1143 - <?php if ($data_source !== 'pinecone') : ?>
1144 1299 <button type="button"
1300 + class="mxch-btn mxch-btn-ghost mxch-btn-sm mxchat-inspect-entry-btn"
1301 + data-source-url="<?php echo esc_attr($prompt->source_url ?? ''); ?>"
1302 + data-entry-id="<?php echo esc_attr($prompt->id); ?>"
1303 + data-data-source="<?php echo esc_attr($data_source); ?>"
1304 + data-bot-id="<?php echo esc_attr($current_bot_id); ?>"
1305 + data-nonce="<?php echo wp_create_nonce('mxchat_inspect_entry_nonce'); ?>"
1306 + title="<?php esc_attr_e('View indexed content', 'mxchat'); ?>">
1307 + <span class="dashicons dashicons-visibility" style="font-size: 14px;"></span>
1308 + </button>
1309 + <button type="button"
1145 1310 class="mxch-btn mxch-btn-ghost mxch-btn-sm mxchat-edit-entry-btn"
1146 1311 data-source-url="<?php echo esc_attr($prompt->source_url ?? ''); ?>"
1147 1312 data-entry-id="<?php echo esc_attr($prompt->id); ?>"
1148 1313 data-data-source="<?php echo esc_attr($data_source); ?>"
@@ -1150,9 +1315,8 @@
1150 1315 data-nonce="<?php echo wp_create_nonce('mxchat_edit_entry_nonce'); ?>"
1151 1316 title="<?php esc_attr_e('Edit content', 'mxchat'); ?>">
1152 1317 <span class="dashicons dashicons-edit" style="font-size: 14px;"></span>
1153 1318 </button>
1154 - <?php endif; ?>
1155 1319 <?php if ($data_source === 'pinecone') : ?>
1156 1320 <button type="button" class="mxch-btn mxch-btn-ghost mxch-btn-sm delete-button-ajax" data-vector-id="<?php echo esc_attr($prompt->id); ?>" data-bot-id="<?php echo esc_attr($current_bot_id); ?>" data-nonce="<?php echo wp_create_nonce('mxchat_delete_pinecone_prompt_nonce'); ?>" style="color: var(--mxch-error);">
1157 1321 <span class="dashicons dashicons-trash" style="font-size: 14px;"></span>
1158 1322 </button>
@@ -1170,10 +1334,21 @@
1170 1334 </table>
1171 1335 </div>
1172 1336
1173 1337 <!-- Pagination wrapper - always present so JS can populate it after processing -->
1174 - <div id="mxchat-kb-pagination" class="mxchat-kb-pagination-wrapper" style="<?php echo $total_pages > 1 ? 'padding: 16px; border-top: 1px solid var(--mxch-card-border); text-align: center;' : ''; ?>" data-current-page="<?php echo esc_attr($current_page); ?>" data-total-pages="<?php echo esc_attr($total_pages); ?>" data-search="<?php echo esc_attr($search_query); ?>" data-content-type="<?php echo esc_attr($content_type_filter); ?>">
1175 - <?php if ($total_pages > 1) : ?>
1338 + <?php
1339 + // Plan dd6e10: Pinecone's list endpoint is a cursor — there is no
1340 + // random access to page N, so over 500 vectors the screen offers
1341 + // Previous / Next only. The same markup is built for AJAX page
1342 + // loads by MxChat_Knowledge_Manager::mxchat_cursor_pagination_html().
1343 + $cursor_pagination = !empty($cursor_pagination);
1344 + $has_next = !empty($has_next);
1345 + $show_pagination = $cursor_pagination ? ($current_page > 1 || $has_next) : ($total_pages > 1);
1346 + ?>
1347 + <div id="mxchat-kb-pagination" class="mxchat-kb-pagination-wrapper" style="<?php echo $show_pagination ? 'padding: 16px; border-top: 1px solid var(--mxch-card-border); text-align: center;' : ''; ?>" data-current-page="<?php echo esc_attr($current_page); ?>" data-total-pages="<?php echo esc_attr($total_pages); ?>" data-search="<?php echo esc_attr($search_query); ?>" data-content-type="<?php echo esc_attr($content_type_filter); ?>">
1348 + <?php if ($cursor_pagination) : ?>
1349 + <?php echo MxChat_Knowledge_Manager::mxchat_cursor_pagination_html($current_page, $has_next, $search_query, $content_type_filter); // phpcs:ignore WordPress.Security.EscapeOutput -- escaped inside ?>
1350 + <?php elseif ($total_pages > 1) : ?>
1176 1351 <div class="mxchat-ajax-pagination" data-current-page="<?php echo esc_attr($current_page); ?>" data-total-pages="<?php echo esc_attr($total_pages); ?>">
1177 1352 <?php if ($current_page > 1) : ?>
1178 1353 <a href="#" class="mxchat-page-link" data-page="<?php echo ($current_page - 1); ?>"><?php esc_html_e('&laquo; Previous', 'mxchat'); ?></a>
1179 1354 <?php endif; ?>
@@ -1212,13 +1387,85 @@
1212 1387 <?php endif; ?>
1213 1388 </div>
1214 1389 </div>
1215 1390 </div>
1391 +
1392 + <?php mxchat_render_kb_reimport_card(!empty($current_bot_id) ? $current_bot_id : 'default'); ?>
1216 1393 </div>
1217 1394 <?php
1218 1395 }
1219 1396
1220 1397 /**
1398 + * "Re-import affected entries" card (plan 89739b).
1399 + *
1400 + * The owner-facing side of wp mxchat kb-reimport: check first (no embedding
1401 + * request, nothing written), read the list, then confirm. Both halves run in
1402 + * resumable steps through the mxchat_kb_reimport AJAX action; the script is
1403 + * js/knowledge-reimport.js. Everything dynamic is drawn there; this is the
1404 + * resting markup.
1405 + */
1406 +function mxchat_render_kb_reimport_card($current_bot_id = 'default') {
1407 + if (!class_exists('MxChat_Knowledge_Manager')) {
1408 + return;
1409 + }
1410 + ?>
1411 + <div class="mxch-card mxch-kb-reimport" id="mxchat-kb-reimport"
1412 + data-nonce="<?php echo esc_attr(wp_create_nonce('mxchat_kb_reimport')); ?>"
1413 + data-bot="<?php echo esc_attr($current_bot_id); ?>">
1414 + <div class="mxch-card-header">
1415 + <h3 class="mxch-card-title">
1416 + <svg class="mxch-card-title-icon" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="23 4 23 10 17 10"/><polyline points="1 20 1 14 7 14"/><path d="M3.51 9a9 9 0 0 1 14.85-3.36L23 10M1 14l4.64 4.36A9 9 0 0 0 20.49 15"/></svg>
1417 + <?php esc_html_e('Re-import affected entries', 'mxchat'); ?>
1418 + </h3>
1419 + </div>
1420 + <div class="mxch-card-body">
1421 + <p class="mxch-field-description"><?php esc_html_e('Earlier versions stored some imported text incorrectly: currency signs and accents were dropped, HTML character codes were left in, and right-to-left PDF text was saved backwards. This finds the entries that still hold that text and rebuilds them from their source. Checking changes nothing.', 'mxchat'); ?></p>
1422 +
1423 + <div class="mxch-kb-reimport-controls">
1424 + <div class="mxch-field">
1425 + <label class="mxch-field-label" for="mxchat-kb-reimport-before"><?php esc_html_e('Entries last written before', 'mxchat'); ?></label>
1426 + <input type="date" id="mxchat-kb-reimport-before" class="mxch-input mxch-input-sm" value="<?php echo esc_attr(MxChat_Knowledge_Manager::REIMPORT_DEFAULT_BEFORE); ?>" max="<?php echo esc_attr(gmdate('Y-m-d', time() + DAY_IN_SECONDS)); ?>" />
1427 + </div>
1428 + <button type="button" class="mxch-btn mxch-btn-secondary" id="mxchat-kb-reimport-check"><?php esc_html_e('Check knowledge base', 'mxchat'); ?></button>
1429 + </div>
1430 + <p class="mxch-field-hint"><?php esc_html_e('The date is the release that carried the last of these fixes. Choose a later one if this site was updated after that.', 'mxchat'); ?></p>
1431 +
1432 + <div class="mxch-kb-reimport-progress" hidden>
1433 + <div class="mxch-progress-bar" hidden><div class="mxch-progress-bar-fill"></div></div>
1434 + <p class="mxch-progress-label" aria-live="polite"></p>
1435 + </div>
1436 +
1437 + <div class="mxch-notice mxch-notice-error mxch-kb-reimport-error" role="alert" hidden>
1438 + <svg class="mxch-notice-icon" xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="12"/><line x1="12" y1="16" x2="12.01" y2="16"/></svg>
1439 + <span></span>
1440 + </div>
1441 +
1442 + <div class="mxch-kb-reimport-results" hidden>
1443 + <div class="mxch-notice mxch-notice-success mxch-kb-reimport-done" hidden>
1444 + <svg class="mxch-notice-icon" xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"/><polyline points="22 4 12 14.01 9 11.01"/></svg>
1445 + <span></span>
1446 + </div>
1447 + <div class="mxch-kb-reimport-counts"></div>
1448 + <ul class="mxch-kb-reimport-list mxch-kb-reimport-entries" hidden></ul>
1449 + <p class="mxch-field-hint mxch-kb-reimport-more" hidden></p>
1450 + <details class="mxch-disclosure mxch-kb-reimport-others" hidden>
1451 + <summary class="mxch-disclosure-summary"><span class="mxch-disclosure-summary-text"></span><span class="mxch-disclosure-summary-hint"><?php esc_html_e('Never changed or removed by this tool', 'mxchat'); ?></span></summary>
1452 + <div class="mxch-disclosure-body">
1453 + <ul class="mxch-kb-reimport-list mxch-kb-reimport-notes"></ul>
1454 + </div>
1455 + </details>
1456 + </div>
1457 + </div>
1458 + <div class="mxch-card-footer mxch-kb-reimport-footer" hidden>
1459 + <button type="button" class="mxch-btn mxch-btn-primary" id="mxchat-kb-reimport-apply"></button>
1460 + <button type="button" class="mxch-btn mxch-btn-ghost" id="mxchat-kb-reimport-clear"><?php esc_html_e('Clear', 'mxchat'); ?></button>
1461 + <span class="mxch-field-hint mxch-kb-reimport-cost"><?php esc_html_e('Each rewritten entry is embedded again with your embedding provider.', 'mxchat'); ?></span>
1462 + </div>
1463 + </div>
1464 + <?php
1465 +}
1466 +
1467 +/**
1221 1468 * Render Auto-Sync Section
1222 1469 */
1223 1470 function mxchat_render_auto_sync_section($knowledge_manager) {
1224 1471 ?>
@@ -1304,13 +1551,16 @@
1304 1551 $chunk_size = $chunking_settings['chunk_size'];
1305 1552 ?>
1306 1553 <div id="chunking" class="mxch-section">
1307 1554 <div class="mxch-content-header">
1308 - <h1 class="mxch-content-title"><?php esc_html_e('Content Chunking', 'mxchat'); ?></h1>
1309 - <p class="mxch-content-subtitle"><?php esc_html_e('Split large content into smaller segments for more accurate semantic search.', 'mxchat'); ?></p>
1555 + <h1 class="mxch-content-title"><?php esc_html_e('Chunking & Retrieval', 'mxchat'); ?></h1>
1556 + <p class="mxch-content-subtitle"><?php esc_html_e('Control how content is split for indexing and how the knowledge base is searched.', 'mxchat'); ?></p>
1310 1557 </div>
1311 1558
1312 1559 <div class="mxch-card">
1560 + <div class="mxch-card-header">
1561 + <h2 class="mxch-card-title"><?php esc_html_e('Chunking', 'mxchat'); ?></h2>
1562 + </div>
1313 1563 <div class="mxch-card-body mxchat-autosave-section">
1314 1564 <div class="mxch-notice mxch-notice-info" style="margin-bottom: 20px;">
1315 1565 <svg class="mxch-notice-icon" xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="10"/><line x1="12" y1="16" x2="12" y2="12"/><line x1="12" y1="8" x2="12.01" y2="8"/></svg>
1316 1566 <span><?php esc_html_e('Chunking improves retrieval quality for long documents. All chunks are reassembled before sending to the AI. Only applies to new submissions.', 'mxchat'); ?></span>
@@ -1332,8 +1582,83 @@
1332 1582 <p class="mxch-field-description"><?php esc_html_e('Recommended: 4000 characters (~1000 tokens). Range: 1000-10000. Larger chunks preserve more context.', 'mxchat'); ?></p>
1333 1583 </div>
1334 1584 </div>
1335 1585 </div>
1586 +
1587 + <?php
1588 + // Retrieval tuning (plan 11720c) — the hybrid keyword boost moved here
1589 + // from Settings → Behavior: it is KB retrieval tuning, so it lives with
1590 + // its natural siblings. SAME option key and save transport as before —
1591 + // the name routes to the mxchat_save_setting handler, whose
1592 + // mxchat_hybrid_keyword_toggle case still runs capability detection.
1593 + ?>
1594 + <div class="mxch-card">
1595 + <div class="mxch-card-header">
1596 + <h2 class="mxch-card-title"><?php esc_html_e('Retrieval', 'mxchat'); ?></h2>
1597 + </div>
1598 + <div class="mxch-card-body mxchat-autosave-section">
1599 + <div class="mxch-field">
1600 + <div style="display: flex; align-items: center; gap: 12px;">
1601 + <label class="mxchat-toggle-switch">
1602 + <input type="checkbox" name="mxchat_hybrid_keyword_toggle" id="mxchat_hybrid_keyword_toggle" class="mxchat-autosave-field" value="on" <?php checked(get_option('mxchat_hybrid_keyword_toggle', 'off'), 'on'); ?>>
1603 + <span class="mxchat-toggle-slider"></span>
1604 + </label>
1605 + <span style="font-weight: 500;"><?php esc_html_e('Hybrid keyword boost (WordPress database and Pinecone document indexes)', 'mxchat'); ?></span>
1606 + </div>
1607 + <p class="mxch-field-description" style="margin-top: 8px;"><?php esc_html_e('Combines keyword matching with vector similarity when searching your WordPress-database knowledge base or a Pinecone document index. Helps exact-token questions — product codes, SKUs, error codes, names — find the right document even when semantic similarity alone would miss it.', 'mxchat'); ?></p>
1608 + <p class="mxch-field-hint"><?php esc_html_e('Applies to the WordPress-database knowledge base and to Pinecone when the index type is Document index with full-text search; a classic Pinecone vector index is unaffected. Changes which sources are retrieved on existing installs, so test after enabling. The Transcripts sources panel labels how each match was found while this is on.', 'mxchat'); ?></p>
1609 + </div>
1610 + </div>
1611 + </div>
1612 +
1613 + <?php
1614 + // Video cards (plan f52492). Lives on the Knowledge screen because that
1615 + // is where the owner imported the video in the first place, and beside
1616 + // Retrieval because it is a retrieval-confidence question. Standalone
1617 + // options — see the mxchat_video_embed_* cases in class-ajax-handler.php.
1618 + $video_embed_enabled = MxChat_Utils::video_embed_enabled();
1619 + $video_embed_threshold = (int) round(MxChat_Utils::video_embed_threshold() * 100);
1620 + $mxchat_core_options = get_option('mxchat_options', array());
1621 + $site_threshold = isset($mxchat_core_options['similarity_threshold'])
1622 + ? (int) $mxchat_core_options['similarity_threshold']
1623 + : 35;
1624 + ?>
1625 + <div class="mxch-card">
1626 + <div class="mxch-card-header">
1627 + <h2 class="mxch-card-title"><?php esc_html_e('Video Cards', 'mxchat'); ?></h2>
1628 + </div>
1629 + <div class="mxch-card-body mxchat-autosave-section">
1630 + <div class="mxch-field" style="margin-bottom: 20px; padding-bottom: 20px; border-bottom: 1px solid var(--mxch-card-border);">
1631 + <div style="display: flex; align-items: center; gap: 12px;">
1632 + <label class="mxchat-toggle-switch">
1633 + <input type="checkbox" name="mxchat_video_embed_enabled" id="mxchat_video_embed_enabled" class="mxchat-autosave-field" value="on" <?php checked($video_embed_enabled, true); ?>>
1634 + <span class="mxchat-toggle-slider"></span>
1635 + </label>
1636 + <span style="font-weight: 500;"><?php esc_html_e('Show a video card when a YouTube source answers the question', 'mxchat'); ?></span>
1637 + </div>
1638 + <p class="mxch-field-description" style="margin-top: 8px;"><?php esc_html_e('Adds a click-to-play card beneath the reply when the answer came from a YouTube video you imported. Turn this off to stop video cards entirely without removing the videos from your knowledge base.', 'mxchat'); ?></p>
1639 + </div>
1640 +
1641 + <div class="mxch-field" id="mxchat-video-embed-threshold-field" style="<?php echo $video_embed_enabled ? '' : 'display: none;'; ?>">
1642 + <label class="mxch-field-label" for="mxchat_video_embed_threshold"><?php esc_html_e('Video Card Match Threshold (%)', 'mxchat'); ?></label>
1643 + <?php // Slider matching the site-wide Similarity Threshold exactly
1644 + // (plan 7afd54): same .slider-container / .range-slider /
1645 + // .range-value markup; the shared admin JS live-updates the
1646 + // <id>_value span on input and autosaves on change (once per
1647 + // drag release, so no request storm). Range/default/clamp
1648 + // unchanged — presentation only. ?>
1649 + <div class="slider-container">
1650 + <input type="range" name="mxchat_video_embed_threshold" id="mxchat_video_embed_threshold" class="range-slider mxchat-autosave-field" value="<?php echo esc_attr($video_embed_threshold); ?>" min="20" max="95" step="1">
1651 + <span id="mxchat_video_embed_threshold_value" class="range-value"><?php echo esc_html((int) $video_embed_threshold); ?></span>
1652 + </div>
1653 + <p class="mxch-field-description"><?php
1654 + /* translators: %d is the site-wide Similarity Threshold percentage. */
1655 + printf(esc_html__('How closely the video must match the question before its card is shown. Higher means fewer, more relevant cards. This is separate from the site-wide Similarity Threshold (currently %d%%), which decides what the AI reads — a video is worth reading from at a lower score than it is worth putting on screen.', 'mxchat'), (int) $site_threshold);
1656 + ?></p>
1657 + <p class="mxch-field-hint"><?php esc_html_e('Range 20-95. Raise this if visitors are shown videos unrelated to what they asked; lower it if a video that clearly answers the question is not appearing. The right number depends on your embedding model: older models such as text-embedding-ada-002 score even unrelated content around 70%, so those sites usually need 80 or higher before this has any effect. The Transcripts sources panel shows the match percentage of each source, which is the number to compare against.', 'mxchat'); ?></p>
1658 + </div>
1659 + </div>
1660 + </div>
1336 1661 </div>
1337 1662 <?php
1338 1663 }
1339 1664
@@ -1340,22 +1665,22 @@
1340 1665 /**
1341 1666 * Render Role Restrictions Section
1342 1667 */
1343 1668 function mxchat_render_role_restrictions_section($knowledge_manager) {
1344 - $role_options = array(
1345 - 'public' => __('Public (Everyone)', 'mxchat'),
1346 - 'logged_in' => __('Logged In Users', 'mxchat'),
1347 - 'subscriber' => __('Subscribers & Above', 'mxchat'),
1348 - 'contributor' => __('Contributors & Above', 'mxchat'),
1349 - 'author' => __('Authors & Above', 'mxchat'),
1350 - 'editor' => __('Editors & Above', 'mxchat'),
1351 - 'administrator' => __('Administrators Only', 'mxchat')
1352 - );
1669 + // Same source as the per-entry dropdown, so the two selectors cannot drift
1670 + // and both offer the site's custom roles (plan 6ab002). This screen used to
1671 + // hold its own hardcoded copy of the five built-ins.
1672 + $role_options = (is_object($knowledge_manager) && method_exists($knowledge_manager, 'mxchat_get_role_options'))
1673 + ? $knowledge_manager->mxchat_get_role_options()
1674 + : array(
1675 + 'public' => __('Public (Everyone)', 'mxchat'),
1676 + 'logged_in' => __('Logged In Users', 'mxchat'),
1677 + );
1353 1678 ?>
1354 1679 <div id="role-restrictions" class="mxch-section">
1355 1680 <div class="mxch-content-header">
1356 1681 <h1 class="mxch-content-title"><?php esc_html_e('Role-Based Content Restrictions', 'mxchat'); ?></h1>
1357 - <p class="mxch-content-subtitle"><?php esc_html_e('Automatically restrict content access based on WordPress tags.', 'mxchat'); ?></p>
1682 + <p class="mxch-content-subtitle"><?php esc_html_e('Automatically restrict tagged posts by role. Pages and untagged content are restricted per entry in the Knowledge list.', 'mxchat'); ?></p>
1358 1683 </div>
1359 1684
1360 1685 <div class="mxch-card">
1361 1686 <div class="mxch-card-body">
@@ -1360,16 +1685,17 @@
1360 1685 <div class="mxch-card">
1361 1686 <div class="mxch-card-body">
1362 1687 <div class="mxch-notice mxch-notice-info" style="margin-bottom: 20px;">
1363 1688 <svg class="mxch-notice-icon" xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="10"/><line x1="12" y1="16" x2="12" y2="12"/><line x1="12" y1="8" x2="12.01" y2="8"/></svg>
1364 - <span><strong><?php esc_html_e('How it works:', 'mxchat'); ?></strong> <?php esc_html_e('Add a tag below and select which role should have access. Content with that tag will be restricted to that role level.', 'mxchat'); ?></span>
1689 + <span><strong><?php esc_html_e('How it works:', 'mxchat'); ?></strong> <?php esc_html_e('Add a tag below and select which role should have access. Content with that tag will be restricted to that role level. Tags apply to posts — pages and other content have no tags, so restrict those from the role dropdown on the entry itself in the Knowledge list. Any role on this site can be chosen, including custom ones.', 'mxchat'); ?></span>
1365 1690 </div>
1366 1691
1367 1692 <h4 style="margin: 0 0 16px 0;"><?php esc_html_e('Add Tag-Role Mapping', 'mxchat'); ?></h4>
1368 1693 <div style="display: flex; gap: 15px; align-items: flex-end; flex-wrap: wrap; margin-bottom: 24px;">
1369 1694 <div class="mxch-field" style="flex: 1; min-width: 200px; margin-bottom: 0;">
1370 - <label class="mxch-field-label" for="mxchat-tag-input"><?php esc_html_e('Tag Name', 'mxchat'); ?></label>
1371 - <input type="text" id="mxchat-tag-input" class="mxch-input" placeholder="<?php esc_attr_e('e.g., premium, members-only', 'mxchat'); ?>">
1695 + <label class="mxch-field-label" for="mxchat-tag-input"><?php esc_html_e('Tag (name or slug)', 'mxchat'); ?></label>
1696 + <input type="text" id="mxchat-tag-input" class="mxch-input" placeholder="<?php esc_attr_e('e.g., Premium Content or premium-content', 'mxchat'); ?>">
1697 + <span class="mxch-field-hint"><?php esc_html_e('Enter an existing post tag by its display name or its slug.', 'mxchat'); ?></span>
1372 1698 </div>
1373 1699 <div class="mxch-field" style="flex: 1; min-width: 200px; margin-bottom: 0;">
1374 1700 <label class="mxch-field-label" for="mxchat-role-select"><?php esc_html_e('Required Role', 'mxchat'); ?></label>
1375 1701 <select id="mxchat-role-select" class="mxch-select">
@@ -1432,8 +1758,23 @@
1432 1758 </div>
1433 1759
1434 1760 <div class="mxch-card">
1435 1761 <div class="mxch-card-body mxchat-autosave-section">
1762 + <?php
1763 + // Install-level ACF→PDF import extraction (plan 11720c) — moved
1764 + // here from a per-import checkbox in the content-selector modal.
1765 + // Default OFF, matching its own "recommended only if…" guidance.
1766 + ?>
1767 + <div class="mxch-field" style="margin-bottom: 20px; padding-bottom: 20px; border-bottom: 1px solid var(--mxch-card-border);">
1768 + <div style="display: flex; align-items: center; gap: 12px;">
1769 + <label class="mxchat-toggle-switch">
1770 + <input type="checkbox" name="mxchat_acf_pdf_extraction" id="mxchat_acf_pdf_extraction" class="mxchat-autosave-field" value="on" <?php checked(get_option('mxchat_acf_pdf_extraction', '0'), '1'); ?>>
1771 + <span class="mxchat-toggle-slider"></span>
1772 + </label>
1773 + <span style="font-weight: 500;"><?php esc_html_e('Extract text from PDFs linked in ACF File/Image fields during imports', 'mxchat'); ?></span>
1774 + </div>
1775 + <p class="mxch-field-description" style="margin-top: 8px;"><?php esc_html_e('Applies to WordPress Content imports. Adds 200-500ms per post and ~30 KB to each knowledge base entry. Recommended only if your ACF setup uses PDF attachments for primary content. Editor-save extraction has its own toggle under Auto-Sync.', 'mxchat'); ?></p>
1776 + </div>
1436 1777 <?php if (!function_exists('acf_get_field_groups')): ?>
1437 1778 <div class="mxch-notice mxch-notice-info">
1438 1779 <svg class="mxch-notice-icon" xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="10"/><line x1="12" y1="16" x2="12" y2="12"/><line x1="12" y1="8" x2="12.01" y2="8"/></svg>
1439 1780 <span><?php esc_html_e('Advanced Custom Fields (ACF) plugin is not detected. Install and activate ACF to use this feature.', 'mxchat'); ?></span>
@@ -1448,30 +1789,55 @@
1448 1789 </div>
1449 1790 <?php else: ?>
1450 1791 <div class="mxch-notice mxch-notice-info" style="margin-bottom: 20px;">
1451 1792 <svg class="mxch-notice-icon" xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="10"/><line x1="12" y1="16" x2="12" y2="12"/><line x1="12" y1="8" x2="12.01" y2="8"/></svg>
1452 - <span><?php esc_html_e('Toggle fields ON to include them in knowledge base embeddings. Toggle OFF to exclude sensitive or irrelevant fields.', 'mxchat'); ?></span>
1793 + <span><?php esc_html_e('Toggle fields ON to include them in knowledge base embeddings. Toggle OFF to exclude sensitive or irrelevant fields. Exclusions apply everywhere a field appears — ACF location rules (post types, templates) do not scope this list.', 'mxchat'); ?></span>
1453 1794 </div>
1454 1795
1455 - <?php foreach ($all_acf_fields as $group_title => $fields): ?>
1456 - <div class="mxchat-acf-field-group" style="margin-bottom: 24px;">
1457 - <h4 style="margin: 0 0 12px 0; color: var(--mxch-text-primary); font-weight: 600;">
1458 - <?php echo esc_html($group_title); ?>
1459 - </h4>
1796 + <?php foreach ($all_acf_fields as $group_key => $group):
1797 + $fields = $group['fields'];
1798 + // Group toggle state derives from the per-field state —
1799 + // never stored on its own (plan bf57e0).
1800 + $excluded_count = 0;
1801 + foreach ($fields as $field) {
1802 + if (in_array($field['key'], $excluded_fields, true) || in_array($field['name'], $excluded_fields, true)) {
1803 + $excluded_count++;
1804 + }
1805 + }
1806 + $group_all_included = ($excluded_count === 0);
1807 + $group_partial = ($excluded_count > 0 && $excluded_count < count($fields));
1808 + ?>
1809 + <div class="mxchat-acf-field-group" style="margin-bottom: 24px;" data-mxchat-acf-group="<?php echo esc_attr($group_key); ?>">
1810 + <div style="display: flex; align-items: center; justify-content: space-between; margin: 0 0 12px 0;">
1811 + <h4 style="margin: 0; color: var(--mxch-text-primary); font-weight: 600;">
1812 + <?php echo esc_html($group['title']); ?>
1813 + </h4>
1814 + <label class="mxchat-toggle-switch" title="<?php esc_attr_e('Include or exclude every field in this group', 'mxchat'); ?>">
1815 + <input type="checkbox"
1816 + class="mxchat-acf-group-toggle"
1817 + data-group-key="<?php echo esc_attr($group_key); ?>"
1818 + data-nonce="<?php echo wp_create_nonce('mxchat_prompts_setting_nonce'); ?>"
1819 + <?php if ($group_partial): ?>data-indeterminate="1"<?php endif; ?>
1820 + <?php checked($group_all_included, true); ?>>
1821 + <span class="mxchat-toggle-slider"></span>
1822 + </label>
1823 + </div>
1460 1824 <div style="background: #f8fafc; border-radius: var(--mxch-radius-md); padding: 16px;">
1461 1825 <?php foreach ($fields as $field):
1462 - $field_name = $field['name'];
1463 - $is_enabled = !in_array($field_name, $excluded_fields);
1826 + // Toggles identify fields by ACF field KEY — names are shared
1827 + // across groups and collide (plan 30e81f). Legacy name entries
1828 + // (group inactive at migration time) still count as excluded.
1829 + $is_enabled = !in_array($field['key'], $excluded_fields, true) && !in_array($field['name'], $excluded_fields, true);
1464 1830 ?>
1465 1831 <div style="display: flex; align-items: center; justify-content: space-between; padding: 8px 0; border-bottom: 1px solid #e2e8f0;">
1466 1832 <div>
1467 1833 <span style="font-weight: 500;"><?php echo esc_html($field['label']); ?></span>
1468 - <span style="color: var(--mxch-text-muted); font-size: 12px; margin-left: 8px;">(<?php echo esc_html($field_name); ?>)</span>
1834 + <span style="color: var(--mxch-text-muted); font-size: 12px; margin-left: 8px;">(<?php echo esc_html($field['name']); ?>)</span>
1469 1835 <span style="color: var(--mxch-text-muted); font-size: 11px; margin-left: 8px; background: #e2e8f0; padding: 2px 6px; border-radius: 4px;"><?php echo esc_html($field['type']); ?></span>
1470 1836 </div>
1471 1837 <label class="mxchat-toggle-switch">
1472 1838 <input type="checkbox"
1473 - name="mxchat_acf_field_<?php echo esc_attr($field_name); ?>"
1839 + name="mxchat_acf_field_<?php echo esc_attr($field['key']); ?>"
1474 1840 class="mxchat-autosave-field"
1475 1841 value="on"
1476 1842 data-nonce="<?php echo wp_create_nonce('mxchat_prompts_setting_nonce'); ?>"
1477 1843 <?php checked($is_enabled, true); ?>>
@@ -1508,8 +1874,28 @@
1508 1874 <svg class="mxch-notice-icon" xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="10"/><line x1="12" y1="16" x2="12" y2="12"/><line x1="12" y1="8" x2="12.01" y2="8"/></svg>
1509 1875 <span><?php esc_html_e('Enter post meta keys to include in embeddings. This is useful for OptionTree fields, theme meta boxes, or any custom post meta that is not managed by ACF.', 'mxchat'); ?></span>
1510 1876 </div>
1511 1877
1878 + <!-- Meta-key discovery scanner (plan-mxchat-20260709-fe8e4e): mirror the ACF picker's
1879 + discover-for-you UX for non-ACF meta, so owners click keys instead of typing them blind. -->
1880 + <div class="mxch-field mxchat-meta-scan">
1881 + <label class="mxch-field-label"><?php esc_html_e('Discover meta keys', 'mxchat'); ?></label>
1882 + <p class="mxch-field-description" style="margin-top: 0;">
1883 + <?php esc_html_e('Scan your published content for custom meta keys, then click any you want to include. This gives non-ACF meta the same discover-and-click experience as the ACF picker.', 'mxchat'); ?>
1884 + </p>
1885 + <div class="mxchat-meta-scan-controls">
1886 + <button type="button" id="mxchat-scan-meta-btn" class="mxch-btn mxch-btn-secondary" data-nonce="<?php echo esc_attr(wp_create_nonce('mxchat_prompts_setting_nonce')); ?>">
1887 + <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="11" cy="11" r="8"/><line x1="21" y1="21" x2="16.65" y2="16.65"/></svg>
1888 + <span class="mxchat-scan-label"><?php esc_html_e('Scan my content for meta keys', 'mxchat'); ?></span>
1889 + </button>
1890 + <label class="mxchat-meta-scan-internal">
1891 + <input type="checkbox" id="mxchat-scan-internal">
1892 + <?php esc_html_e('Include internal keys (underscore-prefixed)', 'mxchat'); ?>
1893 + </label>
1894 + </div>
1895 + <div id="mxchat-meta-scan-results" class="mxchat-meta-scan-results" aria-live="polite"></div>
1896 + </div>
1897 +
1512 1898 <div class="mxch-field">
1513 1899 <label class="mxch-field-label" for="mxchat_custom_meta_whitelist">
1514 1900 <?php esc_html_e('Meta Key Whitelist', 'mxchat'); ?>
1515 1901 </label>
@@ -1522,9 +1908,9 @@
1522 1908 data-nonce="<?php echo wp_create_nonce('mxchat_prompts_setting_nonce'); ?>"
1523 1909 style="font-family: monospace;"
1524 1910 ><?php echo esc_textarea($whitelist); ?></textarea>
1525 1911 <p class="mxch-field-description">
1526 - <?php esc_html_e('Enter one meta key per line. These fields will be appended to the content during embedding. Only string values are included.', 'mxchat'); ?>
1912 + <?php esc_html_e('Enter one meta key per line. These fields will be appended to the content during embedding. Text values are added as-is; array or repeater values are flattened into a comma-separated list. Empty values are skipped.', 'mxchat'); ?>
1527 1913 </p>
1528 1914 </div>
1529 1915
1530 1916 <div style="margin-top: 20px; padding: 16px; background: #f8fafc; border-radius: var(--mxch-radius-md);">
@@ -1531,9 +1917,9 @@
1531 1917 <h4 style="margin: 0 0 12px 0; font-size: 14px;"><?php esc_html_e('How to find meta keys:', 'mxchat'); ?></h4>
1532 1918 <ul style="margin: 0; padding-left: 20px; color: var(--mxch-text-secondary); font-size: 13px;">
1533 1919 <li><?php esc_html_e('Check your theme documentation for meta key names', 'mxchat'); ?></li>
1534 1920 <li><?php esc_html_e('Look in the wp_postmeta database table', 'mxchat'); ?></li>
1535 - <li><?php esc_html_e('Use a plugin like "Show Post Meta" to view meta keys on any post', 'mxchat'); ?></li>
1921 + <li><?php esc_html_e('Use the Scan my content for meta keys button above to discover the keys on your published content automatically', 'mxchat'); ?></li>
1536 1922 <li><?php esc_html_e('Meta keys starting with underscore (_) are usually hidden/internal', 'mxchat'); ?></li>
1537 1923 </ul>
1538 1924 </div>
1539 1925 </div>
@@ -1593,8 +1979,59 @@
1593 1979 <a href="https://app.pinecone.io/" target="_blank"><?php esc_html_e('Open Pinecone Dashboard', 'mxchat'); ?></a>
1594 1980 </p>
1595 1981 </div>
1596 1982
1983 + <?php
1984 + // Index type (plan 362c31): the classic vector index (default) or a
1985 + // document index with full-text search. Same key, host and namespace.
1986 + $pc_index_type = (($pinecone_options['mxchat_pinecone_index_type'] ?? 'vector') === 'document') ? 'document' : 'vector';
1987 + $pc_docs_cloud = $pinecone_options['mxchat_pinecone_docs_cloud'] ?? 'aws';
1988 + $pc_docs_region = $pinecone_options['mxchat_pinecone_docs_region'] ?? 'us-east-1';
1989 + $pc_docs_lang = $pinecone_options['mxchat_pinecone_docs_language'] ?? 'en';
1990 + $pc_verified = $pinecone_options['mxchat_pinecone_docs_verified_host'] ?? '';
1991 + $pc_vector_host = $pinecone_options['mxchat_pinecone_vector_host'] ?? '';
1992 + $pc_current_host = $pinecone_options['mxchat_pinecone_host'] ?? '';
1993 + $pc_docs_class = class_exists('MxChat_Pinecone_Documents');
1994 + $pc_expected_dim = $pc_docs_class ? MxChat_Pinecone_Documents::expected_dimension() : 1536;
1995 + $pc_migration = $pc_docs_class ? MxChat_Pinecone_Documents::migration_get() : array();
1996 + $pc_host_verified = ($pc_current_host !== '' && strtolower(trim($pc_current_host, '/')) === strtolower($pc_verified));
1997 + $pc_clouds = $pc_docs_class ? MxChat_Pinecone_Documents::clouds() : array('aws' => 'AWS');
1998 + $pc_languages = $pc_docs_class ? MxChat_Pinecone_Documents::languages() : array('en' => 'English');
1999 + ?>
2000 + <div class="mxch-field" id="mxchat-pinecone-index-type-field">
2001 + <span class="mxch-field-label"><?php esc_html_e('Index type', 'mxchat'); ?></span>
2002 + <div style="display: flex; flex-direction: column; gap: 6px; margin-top: 8px;">
2003 + <label style="display: flex; align-items: baseline; gap: 8px; cursor: pointer;">
2004 + <input type="radio" name="mxchat_pinecone_addon_options[mxchat_pinecone_index_type]" class="mxchat-pinecone-index-type" value="vector" <?php checked($pc_index_type, 'vector'); ?>>
2005 + <span>
2006 + <strong><?php esc_html_e('Vector index (current)', 'mxchat'); ?></strong>
2007 + <span class="mxch-field-description" style="display: block; margin: 2px 0 0;"><?php esc_html_e('The classic Pinecone index. Nothing changes for existing setups.', 'mxchat'); ?></span>
2008 + </span>
2009 + </label>
2010 + <label style="display: flex; align-items: baseline; gap: 8px; cursor: pointer;">
2011 + <input type="radio" name="mxchat_pinecone_addon_options[mxchat_pinecone_index_type]" class="mxchat-pinecone-index-type" value="document" <?php checked($pc_index_type, 'document'); ?>>
2012 + <span>
2013 + <strong><?php esc_html_e('Document index with full-text search (new)', 'mxchat'); ?></strong>
2014 + <span class="mxch-field-description" style="display: block; margin: 2px 0 0;"><?php esc_html_e('A Pinecone document index keeps a keyword index of your content next to the vectors, so questions with part numbers, SKUs and codes find the exact record. It is a new index: create one below and copy your existing index into it, no re-embedding needed. Turn on the Hybrid keyword boost under Retrieval to use it.', 'mxchat'); ?></span>
2015 + </span>
2016 + </label>
2017 + </div>
2018 + </div>
2019 + <script type="application/json" id="mxchat-pinecone-docs-state"><?php echo wp_json_encode(array(
2020 + 'verified_host' => $pc_verified,
2021 + 'expected_dimension' => (int) $pc_expected_dim,
2022 + // 47c61f: the status notice's two texts, so the page can
2023 + // keep it in step with the host typed in the field.
2024 + 'status_checked' => __('Document index checked: %1$s (%2$d dimensions).', 'mxchat'),
2025 + 'status_unchecked' => __('Not checked yet. Create a document index below, or enter its host above and click Check index. The index type only saves once the host has been checked.', 'mxchat'),
2026 + 'migration' => $pc_migration,
2027 + // 3e83e4: what the LIVE chatbot is on right now, so the
2028 + // page can tell a copy-in-progress from a switch.
2029 + 'index_type' => $pc_index_type,
2030 + 'stored_host' => strtolower(trim((string) $pc_current_host, '/')),
2031 + 'stored_index' => (string) ($pinecone_options['mxchat_pinecone_index'] ?? ''),
2032 + )); ?></script>
2033 +
1597 2034 <div class="mxch-field">
1598 2035 <label class="mxch-field-label" for="mxchat_pinecone_environment"><?php esc_html_e('Region', 'mxchat'); ?></label>
1599 2036 <input type="text" id="mxchat_pinecone_environment" name="mxchat_pinecone_addon_options[mxchat_pinecone_environment]" value="<?php echo esc_attr($pinecone_options['mxchat_pinecone_environment'] ?? ''); ?>" class="mxch-input" placeholder="e.g., gcp-starter">
1600 2037 <p class="mxch-field-description"><?php esc_html_e('Your Pinecone environment/region (e.g., gcp-starter, us-west1-gcp)', 'mxchat'); ?></p>
@@ -1614,8 +2051,90 @@
1614 2051 </label>
1615 2052 <input type="text" id="mxchat_pinecone_host" name="mxchat_pinecone_addon_options[mxchat_pinecone_host]" value="<?php echo esc_attr($pinecone_options['mxchat_pinecone_host'] ?? ''); ?>" class="mxch-input" placeholder="e.g., my-index-xyz123.svc.pinecone.io">
1616 2053 <p class="mxch-field-description"><?php esc_html_e('The hostname from your Pinecone index URL (exclude https://). Found in index details.', 'mxchat'); ?></p>
1617 2054 </div>
2055 +
2056 + <div class="mxchat-pinecone-docs-settings" <?php echo $pc_index_type === 'document' ? '' : 'style="display: none;"'; ?>>
2057 + <div class="mxch-notice <?php echo $pc_host_verified ? 'mxch-notice-success' : 'mxch-notice-warning'; ?>" id="mxchat-pinecone-docs-status" style="margin-bottom: 20px;">
2058 + <svg class="mxch-notice-icon" xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="10"/><line x1="12" y1="16" x2="12" y2="12"/><line x1="12" y1="8" x2="12.01" y2="8"/></svg>
2059 + <span id="mxchat-pinecone-docs-status-text"><?php
2060 + if ($pc_host_verified) {
2061 + printf(esc_html__('Document index checked: %1$s (%2$d dimensions).', 'mxchat'), esc_html($pc_verified), (int) $pc_expected_dim);
2062 + } else {
2063 + esc_html_e('Not checked yet. Create a document index below, or enter its host above and click Check index. The index type only saves once the host has been checked.', 'mxchat');
2064 + }
2065 + ?></span>
2066 + </div>
2067 +
2068 + <div class="mxch-field">
2069 + <label class="mxch-field-label" for="mxchat_pinecone_docs_cloud"><?php esc_html_e('Cloud and region for a new index', 'mxchat'); ?></label>
2070 + <div style="display: flex; gap: 8px; flex-wrap: wrap;">
2071 + <select id="mxchat_pinecone_docs_cloud" name="mxchat_pinecone_addon_options[mxchat_pinecone_docs_cloud]" class="mxch-select" style="max-width: 160px;">
2072 + <?php foreach ($pc_clouds as $pc_cloud_key => $pc_cloud_label) : ?>
2073 + <option value="<?php echo esc_attr($pc_cloud_key); ?>" <?php selected($pc_docs_cloud, $pc_cloud_key); ?>><?php echo esc_html($pc_cloud_label); ?></option>
2074 + <?php endforeach; ?>
2075 + </select>
2076 + <input type="text" id="mxchat_pinecone_docs_region" name="mxchat_pinecone_addon_options[mxchat_pinecone_docs_region]" value="<?php echo esc_attr($pc_docs_region); ?>" class="mxch-input" style="max-width: 220px;" placeholder="us-east-1">
2077 + <select id="mxchat_pinecone_docs_language" name="mxchat_pinecone_addon_options[mxchat_pinecone_docs_language]" class="mxch-select" style="max-width: 200px;">
2078 + <?php foreach ($pc_languages as $pc_lang_key => $pc_lang_label) : ?>
2079 + <option value="<?php echo esc_attr($pc_lang_key); ?>" <?php selected($pc_docs_lang, $pc_lang_key); ?>><?php echo esc_html($pc_lang_label); ?></option>
2080 + <?php endforeach; ?>
2081 + </select>
2082 + </div>
2083 + <p class="mxch-field-description"><?php printf(esc_html__('Create index for me makes a new document index named after the Index Name field (a free name ending in -docs is suggested when you switch to this type), sized for your embedding model (%d dimensions, cosine), with full-text search on the content in the chosen language, then fills in the host. Check index confirms the host above points at a document index MxChat can use. Neither moves your chatbot — that happens when you save.', 'mxchat'), (int) $pc_expected_dim); ?></p>
2084 + </div>
2085 +
2086 + <div class="mxch-field" style="display: flex; gap: 8px; flex-wrap: wrap;">
2087 + <button type="button" class="mxch-btn mxch-btn-secondary" id="mxchat-pinecone-docs-create"><?php esc_html_e('Create index for me', 'mxchat'); ?></button>
2088 + <button type="button" class="mxch-btn mxch-btn-secondary" id="mxchat-pinecone-docs-check"><?php esc_html_e('Check index', 'mxchat'); ?></button>
2089 + </div>
2090 + <div id="mxchat-pinecone-docs-result" style="display: none;"></div>
2091 + <p class="mxch-field-hint" id="mxchat-pinecone-docs-gate" style="display: none;"><?php esc_html_e('Check the document index host before saving.', 'mxchat'); ?></p>
2092 + <div class="mxch-field" id="mxchat-pinecone-docs-switch-gate" style="display: none;">
2093 + <p class="mxch-field-hint" id="mxchat-pinecone-docs-switch-gate-text"></p>
2094 + <label class="mxch-field-hint" style="display: flex; align-items: center; gap: 8px; cursor: pointer;">
2095 + <input type="checkbox" id="mxchat_pinecone_docs_switch_anyway" name="mxchat_pinecone_addon_options[mxchat_pinecone_docs_switch_anyway]" value="1">
2096 + <span><?php esc_html_e('Switch anyway — point the chatbot at the document index now and copy the rest afterwards', 'mxchat'); ?></span>
2097 + </label>
2098 + </div>
2099 +
2100 + <div class="mxch-field" style="margin-top: 20px;">
2101 + <label class="mxch-field-label" for="mxchat_pinecone_vector_host"><?php esc_html_e('Copy from vector index host', 'mxchat'); ?></label>
2102 + <input type="text" id="mxchat_pinecone_vector_host" name="mxchat_pinecone_addon_options[mxchat_pinecone_vector_host]" value="<?php echo esc_attr($pc_vector_host); ?>" class="mxch-input" placeholder="my-index-xyz123.svc.pinecone.io">
2103 + <p class="mxch-field-description"><?php esc_html_e('Migrate copies every record of that index into the document index above — text, vector and metadata, same ids — with no embedding calls. It runs while your chatbot keeps answering from the vector index; save the Pinecone settings afterwards to switch. Safe to run again: records already copied are simply replaced, and an interrupted copy continues where it stopped. Both indexes must use the same embedding dimension.', 'mxchat'); ?></p>
2104 + </div>
2105 + <div class="mxch-field" style="display: flex; gap: 12px; align-items: center; flex-wrap: wrap;">
2106 + <button type="button" class="mxch-btn mxch-btn-secondary" id="mxchat-pinecone-docs-migrate"><?php esc_html_e('Migrate', 'mxchat'); ?></button>
2107 + <?php /* e50d2e: offered only when the source index holds records in more than one namespace (the JS shows it from the start response). No name attribute — it is not a saved setting. */ ?>
2108 + <label class="mxch-toggle" id="mxchat-pinecone-docs-all-namespaces" style="display: none;" title="<?php esc_attr_e('Copy the records of every namespace of the vector index, each into the same-named namespace of the document index, in one run.', 'mxchat'); ?>">
2109 + <input type="checkbox" class="mxch-toggle-input" id="mxchat_pinecone_docs_all_namespaces" value="1">
2110 + <span class="mxch-toggle-switch"></span>
2111 + <span class="mxch-toggle-label"><?php esc_html_e('Copy every namespace', 'mxchat'); ?></span>
2112 + </label>
2113 + <span id="mxchat-pinecone-docs-migrate-counts" class="mxch-field-description"></span>
2114 + </div>
2115 + <div id="mxchat-pinecone-docs-migrate-progress" style="display: none; margin-bottom: 16px;">
2116 + <div class="mxch-progress-bar"><div class="mxch-progress-bar-fill" style="width: 0%;"></div></div>
2117 + <div class="mxch-progress-label"></div>
2118 + </div>
2119 +
2120 + <div class="mxch-field" id="mxchat-pinecone-docs-delete-old" style="display: none;">
2121 + <label class="mxch-field-label" for="mxchat_pinecone_docs_delete_confirm"><?php esc_html_e('Delete old index', 'mxchat'); ?></label>
2122 + <p class="mxch-field-description"><?php esc_html_e('Available once the copy count matches. Type the old index name to confirm. This deletes the whole vector index at Pinecone and cannot be undone.', 'mxchat'); ?></p>
2123 + <div style="display: flex; gap: 8px; flex-wrap: wrap;">
2124 + <input type="text" id="mxchat_pinecone_docs_delete_confirm" class="mxch-input" style="max-width: 320px;" placeholder="<?php esc_attr_e('old index name', 'mxchat'); ?>" autocomplete="off">
2125 + <button type="button" class="mxch-btn mxch-btn-danger" id="mxchat-pinecone-docs-delete-old-btn"><?php esc_html_e('Delete old index', 'mxchat'); ?></button>
2126 + </div>
2127 + </div>
2128 + </div>
2129 +
2130 + <div class="mxch-field">
2131 + <label class="mxch-field-label" for="mxchat_pinecone_top_k">
2132 + <?php esc_html_e('Results Per Query (topK)', 'mxchat'); ?>
2133 + </label>
2134 + <input type="number" id="mxchat_pinecone_top_k" name="mxchat_pinecone_addon_options[mxchat_pinecone_top_k]" value="<?php echo esc_attr($pinecone_options['mxchat_pinecone_top_k'] ?? '50'); ?>" class="mxch-input" min="1" max="1000" step="1" placeholder="50">
2135 + <p class="mxch-field-description"><?php esc_html_e('How many candidate matches each Pinecone query requests (1-1000, default 50). Higher values improve grouping of chunked content at the cost of slightly larger responses.', 'mxchat'); ?></p>
2136 + </div>
1618 2137 </div>
1619 2138
1620 2139 <?php submit_button(__('Save Pinecone Settings', 'mxchat'), 'primary', 'submit', true, array('class' => 'mxch-btn mxch-btn-primary')); ?>
1621 2140 </form>
@@ -1632,12 +2151,16 @@
1632 2151 $vectorstore_options = get_option('mxchat_openai_vectorstore_options', array());
1633 2152 $use_vectorstore = $vectorstore_options['mxchat_use_openai_vectorstore'] ?? '0';
1634 2153 $vectorstore_ids = $vectorstore_options['mxchat_vectorstore_ids'] ?? '';
1635 2154 $max_results = $vectorstore_options['mxchat_vectorstore_max_results'] ?? 5;
2155 + $sync_enabled = $vectorstore_options['mxchat_vectorstore_sync_enabled'] ?? '0';
2156 + $sync_store_id = $vectorstore_options['mxchat_vectorstore_sync_store_id'] ?? '';
2157 + $sync_config = class_exists('MxChat_Vectorstore_Manager') ? MxChat_Vectorstore_Manager::get_sync_config('default') : array('enabled' => false, 'store_id' => '');
2158 + $mapped_count = class_exists('MxChat_Vectorstore_Manager') ? MxChat_Vectorstore_Manager::mapped_file_count() : 0;
1636 2159
1637 2160 // Get current chat model to check compatibility
1638 2161 $mxchat_options = get_option('mxchat_options', array());
1639 - $current_model = $mxchat_options['model'] ?? 'gpt-5.1-chat-latest';
2162 + $current_model = $mxchat_options['model'] ?? 'gpt-5.6-sol';
1640 2163 $is_openai_model = preg_match('/^(gpt-|o1-|o3-)/', $current_model);
1641 2164 ?>
1642 2165 <div id="openai-vectorstore" class="mxch-section">
1643 2166 <div class="mxch-content-header">
@@ -1648,9 +2171,9 @@
1648 2171 <div class="mxch-card">
1649 2172 <div class="mxch-card-body">
1650 2173 <div class="mxch-notice mxch-notice-info" style="margin-bottom: 20px;">
1651 2174 <svg class="mxch-notice-icon" xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="10"/><line x1="12" y1="16" x2="12" y2="12"/><line x1="12" y1="8" x2="12.01" y2="8"/></svg>
1652 - <span><strong><?php esc_html_e('Requires OpenAI Chat Model.', 'mxchat'); ?></strong> <?php esc_html_e('Vector Store search only works with OpenAI models (gpt-5.1-chat-latest, gpt-5-mini, etc.). Create Vector Stores in your OpenAI Dashboard.', 'mxchat'); ?></span>
2175 + <span><strong><?php esc_html_e('Requires OpenAI Chat Model.', 'mxchat'); ?></strong> <?php esc_html_e('Vector Store search only works with OpenAI models (gpt-5.6-sol, gpt-5.6-terra, etc.). Create Vector Stores in your OpenAI Dashboard.', 'mxchat'); ?></span>
1653 2176 </div>
1654 2177
1655 2178 <?php if (!$is_openai_model && $use_vectorstore === '1'): ?>
1656 2179 <div class="mxch-notice mxch-notice-warning" style="margin-bottom: 20px;">
@@ -1703,10 +2226,143 @@
1703 2226 <p class="mxch-field-description"><?php esc_html_e('Maximum number of content chunks to retrieve from the Vector Store.', 'mxchat'); ?></p>
1704 2227 </div>
1705 2228 </div>
1706 2229
2230 + <div class="mxch-field" style="border-top: 1px solid var(--mxch-border, #e2e4e7); padding-top: 20px; margin-top: 4px;">
2231 + <div style="display: flex; align-items: center; gap: 12px; margin-bottom: 8px;">
2232 + <label class="mxchat-toggle-switch">
2233 + <input type="checkbox" name="mxchat_openai_vectorstore_options[mxchat_vectorstore_sync_enabled]" value="1" <?php checked($sync_enabled, '1'); ?> id="mxchat_vectorstore_sync_enabled">
2234 + <span class="mxchat-toggle-slider"></span>
2235 + </label>
2236 + <span style="font-weight: 500;"><?php esc_html_e('Sync Knowledge Base to Vector Store', 'mxchat'); ?></span>
2237 + </div>
2238 + <p class="mxch-field-description" style="margin-bottom: 16px;">
2239 + <?php esc_html_e('Keeps your Vector Store up to date automatically: knowledge base additions, edits, and deletions are mirrored to the store (one file per entry, replaced on change). Without this, the store is frozen at whatever you uploaded manually. Role-restricted entries are never uploaded — OpenAI file search cannot filter by user role.', 'mxchat'); ?>
2240 + </p>
2241 +
2242 + <label class="mxch-field-label" for="mxchat_vectorstore_sync_store_id">
2243 + <?php esc_html_e('Sync Target Vector Store ID', 'mxchat'); ?>
2244 + </label>
2245 + <input type="text" id="mxchat_vectorstore_sync_store_id" name="mxchat_openai_vectorstore_options[mxchat_vectorstore_sync_store_id]" value="<?php echo esc_attr($sync_store_id); ?>" class="mxch-input" placeholder="<?php echo esc_attr($sync_config['store_id'] ?: 'vs_abc123xyz'); ?>">
2246 + <p class="mxch-field-description">
2247 + <?php esc_html_e('Leave blank to use the first Vector Store ID above. Syncing writes to exactly one store.', 'mxchat'); ?>
2248 + </p>
2249 + </div>
2250 +
1707 2251 <?php submit_button(__('Save Vector Store Settings', 'mxchat'), 'primary', 'submit', true, array('class' => 'mxch-btn mxch-btn-primary')); ?>
1708 2252 </form>
2253 +
2254 + <?php if ($sync_config['enabled']): ?>
2255 + <div class="mxch-field" id="mxchat-vs-import" style="border-top: 1px solid var(--mxch-border, #e2e4e7); padding-top: 20px;"
2256 + data-nonce="<?php echo esc_attr(wp_create_nonce('mxchat_admin_nonce')); ?>">
2257 + <label class="mxch-field-label"><?php esc_html_e('Import Existing Knowledge Base', 'mxchat'); ?></label>
2258 + <p class="mxch-field-description">
2259 + <?php printf(esc_html__('One-time (re-runnable) import of every knowledge base entry into the sync target store. Runs in the background via WP-Cron; safe to interrupt and resume — already-imported, unchanged entries are skipped. Currently mirrored: %s files.', 'mxchat'), '<strong id="mxchat-vs-mapped">' . esc_html(number_format_i18n($mapped_count)) . '</strong>'); ?>
2260 + </p>
2261 + <div style="display: flex; align-items: center; gap: 8px; margin: 10px 0;">
2262 + <button type="button" class="mxch-btn mxch-btn-secondary" id="mxchat-vs-import-start"><?php esc_html_e('Import Knowledge Base to Vector Store', 'mxchat'); ?></button>
2263 + <button type="button" class="mxch-btn" id="mxchat-vs-import-resume" style="display:none;"><?php esc_html_e('Resume Import', 'mxchat'); ?></button>
2264 + <button type="button" class="mxch-btn" id="mxchat-vs-import-cancel" style="display:none;"><?php esc_html_e('Cancel', 'mxchat'); ?></button>
2265 + </div>
2266 + <div id="mxchat-vs-import-bar" style="display:none; height: 8px; background: var(--mxch-border, #e2e4e7); border-radius: 4px; overflow: hidden; max-width: 420px;">
2267 + <div id="mxchat-vs-import-fill" style="height: 100%; width: 0%; background: #2271b1; transition: width .4s;"></div>
2268 + </div>
2269 + <p class="mxch-field-description" id="mxchat-vs-import-status" style="margin-top: 8px;"></p>
2270 + </div>
2271 +
2272 + <script>
2273 + (function() {
2274 + var wrap = document.getElementById('mxchat-vs-import');
2275 + if (!wrap) { return; }
2276 + var nonce = wrap.getAttribute('data-nonce');
2277 + var startBtn = document.getElementById('mxchat-vs-import-start');
2278 + var resumeBtn = document.getElementById('mxchat-vs-import-resume');
2279 + var cancelBtn = document.getElementById('mxchat-vs-import-cancel');
2280 + var bar = document.getElementById('mxchat-vs-import-bar');
2281 + var fill = document.getElementById('mxchat-vs-import-fill');
2282 + var statusEl = document.getElementById('mxchat-vs-import-status');
2283 + var mappedEl = document.getElementById('mxchat-vs-mapped');
2284 + var pollTimer = null;
2285 +
2286 + function post(action, done) {
2287 + var body = 'action=' + encodeURIComponent(action) + '&nonce=' + encodeURIComponent(nonce);
2288 + fetch(ajaxurl, {
2289 + method: 'POST',
2290 + credentials: 'same-origin',
2291 + headers: {'Content-Type': 'application/x-www-form-urlencoded'},
2292 + body: body
2293 + }).then(function(r) { return r.json(); }).then(done).catch(function() {
2294 + statusEl.textContent = '<?php echo esc_js(__('Request failed — check the browser console.', 'mxchat')); ?>';
2295 + });
2296 + }
2297 +
2298 + function render(state, mapped) {
2299 + if (typeof mapped === 'number' && mappedEl) { mappedEl.textContent = mapped.toLocaleString(); }
2300 + var running = state.status === 'running';
2301 + startBtn.style.display = running ? 'none' : '';
2302 + cancelBtn.style.display = running ? '' : 'none';
2303 + resumeBtn.style.display = (running && state.stalled) ? '' : 'none';
2304 + bar.style.display = (running || state.status === 'done') ? '' : 'none';
2305 + var pct = state.total > 0 ? Math.min(100, Math.round(state.processed / state.total * 100)) : 0;
2306 + if (state.status === 'done') { pct = 100; }
2307 + fill.style.width = pct + '%';
2308 +
2309 + var bits = [];
2310 + if (state.status === 'running') { bits.push(state.stalled ? '<?php echo esc_js(__('Import stalled (cron missed) — click Resume.', 'mxchat')); ?>' : '<?php echo esc_js(__('Importing…', 'mxchat')); ?>'); }
2311 + if (state.status === 'done') { bits.push('<?php echo esc_js(__('Import complete.', 'mxchat')); ?>'); }
2312 + if (state.status === 'cancelled') { bits.push('<?php echo esc_js(__('Import cancelled.', 'mxchat')); ?>'); }
2313 + if (state.status === 'error') { bits.push('<?php echo esc_js(__('Import error:', 'mxchat')); ?> ' + state.last_error); }
2314 + if (state.status !== 'idle') {
2315 + bits.push(state.processed + '/' + state.total
2316 + + ' — ' + state.imported + ' <?php echo esc_js(__('uploaded', 'mxchat')); ?>'
2317 + + ', ' + state.unchanged + ' <?php echo esc_js(__('unchanged', 'mxchat')); ?>'
2318 + + ', ' + state.skipped_restricted + ' <?php echo esc_js(__('skipped (role-restricted)', 'mxchat')); ?>'
2319 + + ', ' + state.failed + ' <?php echo esc_js(__('failed', 'mxchat')); ?>');
2320 + if (state.failed > 0 && state.last_error && state.status !== 'error') {
2321 + bits.push('<?php echo esc_js(__('Last error:', 'mxchat')); ?> ' + state.last_error);
2322 + }
2323 + }
2324 + statusEl.textContent = bits.join(' ');
2325 +
2326 + if (running && !pollTimer) {
2327 + pollTimer = setInterval(function() {
2328 + post('mxchat_vectorstore_import_status', function(res) {
2329 + if (res && res.success) { render(res.data.state, res.data.mapped); }
2330 + });
2331 + }, 3000);
2332 + } else if (!running && pollTimer) {
2333 + clearInterval(pollTimer);
2334 + pollTimer = null;
2335 + }
2336 + }
2337 +
2338 + startBtn.addEventListener('click', function() {
2339 + startBtn.disabled = true;
2340 + statusEl.textContent = '<?php echo esc_js(__('Starting…', 'mxchat')); ?>';
2341 + post('mxchat_vectorstore_import_start', function(res) {
2342 + startBtn.disabled = false;
2343 + if (res && res.success) { render(res.data.state); }
2344 + else { statusEl.textContent = (res && res.data && res.data.message) ? res.data.message : '<?php echo esc_js(__('Could not start the import.', 'mxchat')); ?>'; }
2345 + });
2346 + });
2347 + resumeBtn.addEventListener('click', function() {
2348 + post('mxchat_vectorstore_import_resume', function(res) {
2349 + if (res && res.success) { render(res.data.state); }
2350 + });
2351 + });
2352 + cancelBtn.addEventListener('click', function() {
2353 + post('mxchat_vectorstore_import_cancel', function(res) {
2354 + if (res && res.success) { render(res.data.state); }
2355 + });
2356 + });
2357 +
2358 + // Pick up an import already in flight when the page loads.
2359 + post('mxchat_vectorstore_import_status', function(res) {
2360 + if (res && res.success && res.data.state.status !== 'idle') { render(res.data.state, res.data.mapped); }
2361 + });
2362 + })();
2363 + </script>
2364 + <?php endif; ?>
1709 2365 </div>
1710 2366 </div>
1711 2367 </div>
1712 2368 <?php
@@ -1755,8 +2411,20 @@
1755 2411 <option value="unprocessed"><?php esc_html_e('Not In Knowledge Base', 'mxchat'); ?></option>
1756 2412 </select>
1757 2413 </div>
1758 2414 </div>
2415 + <?php
2416 + // Shown only while Media is the selected type (plan 01010a). Media lists
2417 + // just the files whose text MxChat can read; saying so here is clearer
2418 + // than listing images and audio as rows that cannot be selected.
2419 + ?>
2420 + <div class="mxchat-kb-filter-note" id="mxchat-kb-media-note" hidden>
2421 + <svg class="mxchat-kb-filter-note-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
2422 + <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"></path>
2423 + <path d="M14 2v6h6"></path>
2424 + </svg>
2425 + <span><?php esc_html_e('Media lists PDF, Word, text and Markdown files — the types MxChat can read text from. Images, audio and video are not shown.', 'mxchat'); ?></span>
2426 + </div>
1759 2427 <div class="mxchat-kb-content-selection">
1760 2428 <div class="mxchat-kb-selection-header">
1761 2429 <label>
1762 2430 <input type="checkbox" id="mxchat-kb-select-all">
@@ -1776,15 +2444,8 @@
1776 2444 </div>
1777 2445 </div>
1778 2446 <div class="mxchat-kb-modal-footer">
1779 2447 <div class="mxchat-kb-pagination"></div>
1780 - <div class="mxchat-kb-acf-pdf-option" style="display:flex; align-items:flex-start; gap:8px; padding:8px 0; font-size:12px; color: var(--mxch-text-secondary, #64748b);">
1781 - <input type="checkbox" id="mxchat-kb-acf-pdf-extract" style="margin-top:2px;">
1782 - <label for="mxchat-kb-acf-pdf-extract" style="cursor:pointer; line-height:1.4;">
1783 - <strong style="color: var(--mxch-text-primary, #1a1a2e);"><?php esc_html_e('Also extract text from PDFs linked in ACF File/Image fields', 'mxchat'); ?></strong><br>
1784 - <span><?php esc_html_e('Adds 200-500ms per post and ~30 KB to each KB entry. Recommended only if your ACF setup uses PDF attachments for primary content.', 'mxchat'); ?></span>
1785 - </label>
1786 - </div>
1787 2448 <div class="mxchat-kb-footer-actions">
1788 2449 <button type="button" id="mxchat-kb-process-selected" class="mxchat-kb-button-primary" disabled>
1789 2450 <?php esc_html_e('Process Selected Content', 'mxchat'); ?>
1790 2451 <span class="mxchat-kb-selected-count">(0)</span>
@@ -1838,93 +2499,235 @@
1838 2499 <?php
1839 2500 }
1840 2501
1841 2502 /**
1842 - * Render Knowledge Page Navigation Scripts
2503 + * Render the read-only Knowledge Inspector modal (plan-mxchat-20260628-d8cb4b).
2504 + * Shows exactly what was indexed for an entry: the per-chunk stored text + lengths
2505 + * and (for Pinecone) the stored metadata fields, rendered with the Testing tab's
2506 + * own card components so the two surfaces feel like one system. Self-contained
2507 + * markup + JS so it doesn't entangle the edit-modal init.
1843 2508 */
1844 -function mxchat_render_knowledge_page_scripts() {
2509 +function mxchat_render_inspect_entry_modal() {
1845 2510 ?>
2511 + <div id="mxchat-kb-inspect-modal" class="mxchat-kb-modal">
2512 + <div class="mxchat-kb-modal-content mxchat-kb-inspect-modal-content">
2513 + <div class="mxchat-kb-modal-header">
2514 + <h3 id="mxchat-kb-inspect-title"><?php esc_html_e('Indexed Content', 'mxchat'); ?></h3>
2515 + <span class="mxchat-kb-modal-close" id="mxchat-kb-inspect-close">&times;</span>
2516 + </div>
2517 + <div class="mxchat-kb-inspect-body">
2518 + <div class="mxchat-kb-edit-source" id="mxchat-kb-inspect-source"></div>
2519 + <div class="mxch-testing-results" id="mxchat-kb-inspect-results">
2520 + <div class="mxch-testing-no-data"><?php esc_html_e('Loading indexed content…', 'mxchat'); ?></div>
2521 + </div>
2522 + </div>
2523 + <div class="mxchat-kb-edit-footer">
2524 + <div class="mxchat-kb-edit-notice" id="mxchat-kb-inspect-notice"></div>
2525 + <div class="mxchat-kb-edit-actions">
2526 + <button type="button" id="mxchat-kb-inspect-close-btn" class="mxch-btn mxch-btn-primary">
2527 + <?php esc_html_e('Close', 'mxchat'); ?>
2528 + </button>
2529 + </div>
2530 + </div>
2531 + </div>
2532 + </div>
1846 2533 <script>
1847 2534 (function() {
1848 2535 'use strict';
1849 -
1850 - // Wait for DOM
1851 2536 document.addEventListener('DOMContentLoaded', function() {
1852 - initKnowledgeNavigation();
1853 - initMobileMenu();
1854 - initImportOptions();
1855 - initCustomPostTypesToggle();
1856 - // Sitemap detection is now initialized when user clicks the Sitemap Import option
1857 - });
2537 + var modal = document.getElementById('mxchat-kb-inspect-modal');
2538 + if (!modal) return;
2539 + var closeX = document.getElementById('mxchat-kb-inspect-close');
2540 + var closeBtn = document.getElementById('mxchat-kb-inspect-close-btn');
2541 + var sourceEl = document.getElementById('mxchat-kb-inspect-source');
2542 + var resultsEl= document.getElementById('mxchat-kb-inspect-results');
2543 + var titleEl = document.getElementById('mxchat-kb-inspect-title');
2544 + var noticeEl = document.getElementById('mxchat-kb-inspect-notice');
1858 2545
1859 - function initKnowledgeNavigation() {
1860 - const navLinks = document.querySelectorAll('.mxch-nav-link[data-target], .mxch-mobile-nav-link[data-target]');
1861 - const sections = document.querySelectorAll('.mxch-section');
2546 + var I18N = {
2547 + title: <?php echo wp_json_encode( esc_html__('Indexed Content', 'mxchat') ); ?>,
2548 + loading: <?php echo wp_json_encode( esc_html__('Loading indexed content…', 'mxchat') ); ?>,
2549 + manual: <?php echo wp_json_encode( esc_html__('Manual Content', 'mxchat') ); ?>,
2550 + source: <?php echo wp_json_encode( esc_html__('Source', 'mxchat') ); ?>,
2551 + store: <?php echo wp_json_encode( esc_html__('Storage', 'mxchat') ); ?>,
2552 + type: <?php echo wp_json_encode( esc_html__('Content type', 'mxchat') ); ?>,
2553 + chunksLbl:<?php echo wp_json_encode( esc_html__('Chunks', 'mxchat') ); ?>,
2554 + totalLen: <?php echo wp_json_encode( esc_html__('Total indexed length', 'mxchat') ); ?>,
2555 + chunk: <?php echo wp_json_encode( esc_html__('Chunk', 'mxchat') ); ?>,
2556 + indexed: <?php echo wp_json_encode( esc_html__('Indexed', 'mxchat') ); ?>,
2557 + chars: <?php echo wp_json_encode( esc_html__('chars', 'mxchat') ); ?>,
2558 + showText: <?php echo wp_json_encode( esc_html__('Show indexed text', 'mxchat') ); ?>,
2559 + hideText: <?php echo wp_json_encode( esc_html__('Hide indexed text', 'mxchat') ); ?>,
2560 + wpStore: <?php echo wp_json_encode( esc_html__('Local WordPress database', 'mxchat') ); ?>,
2561 + pcStore: <?php echo wp_json_encode( esc_html__('Pinecone', 'mxchat') ); ?>,
2562 + meta: <?php echo wp_json_encode( esc_html__('Vector metadata', 'mxchat') ); ?>,
2563 + loadFail: <?php echo wp_json_encode( esc_html__('Failed to load indexed content.', 'mxchat') ); ?>,
2564 + netErr: <?php echo wp_json_encode( esc_html__('Network error: ', 'mxchat') ); ?>
2565 + };
1862 2566
1863 - function showSection(targetId) {
1864 - // Hide all sections
1865 - sections.forEach(section => section.classList.remove('active'));
1866 - // Show target section
1867 - const target = document.getElementById(targetId);
1868 - if (target) {
1869 - target.classList.add('active');
1870 - }
1871 - // Update nav links
1872 - navLinks.forEach(link => {
1873 - link.classList.toggle('active', link.dataset.target === targetId);
1874 - });
1875 - // Update URL hash
1876 - history.replaceState(null, null, '#' + targetId);
2567 + function esc(str) {
2568 + var d = document.createElement('div');
2569 + d.textContent = (str === null || str === undefined) ? '' : String(str);
2570 + return d.innerHTML;
1877 2571 }
2572 + function fmt(n) { try { return Number(n).toLocaleString(); } catch (e) { return n; } }
1878 2573
1879 - navLinks.forEach(link => {
1880 - link.addEventListener('click', function(e) {
1881 - e.preventDefault();
1882 - const targetId = this.dataset.target;
1883 - showSection(targetId);
1884 - // Close mobile menu if open
1885 - const mobileMenu = document.querySelector('.mxch-mobile-menu');
1886 - const overlay = document.querySelector('.mxch-mobile-overlay');
1887 - if (mobileMenu) mobileMenu.classList.remove('open');
1888 - if (overlay) overlay.classList.remove('open');
1889 - });
2574 + document.addEventListener('click', function(e) {
2575 + var btn = e.target.closest('.mxchat-inspect-entry-btn');
2576 + if (btn) { e.preventDefault(); open(btn); }
1890 2577 });
2578 + if (closeX) closeX.addEventListener('click', close);
2579 + if (closeBtn) closeBtn.addEventListener('click', close);
2580 + // Overlay click closes, but only when the whole gesture happened on the
2581 + // overlay — otherwise selecting indexed text and releasing past the
2582 + // dialog edge dispatches the click on the overlay and closes it.
2583 + var downOnOverlay = false;
2584 + modal.addEventListener('mousedown', function(e) { downOnOverlay = (e.target === modal); });
2585 + modal.addEventListener('click', function(e) {
2586 + var overlayGesture = downOnOverlay;
2587 + downOnOverlay = false;
2588 + if (e.target === modal && overlayGesture) close();
2589 + });
2590 + document.addEventListener('keydown', function(e) {
2591 + if (e.key === 'Escape' && modal.classList.contains('active')) close();
2592 + });
1891 2593
1892 - // Handle initial hash
1893 - const hash = window.location.hash.substring(1);
1894 - if (hash && document.getElementById(hash)) {
1895 - showSection(hash);
2594 + function close() { modal.classList.remove('active'); }
2595 +
2596 + function open(btn) {
2597 + var entry = {
2598 + sourceUrl: btn.getAttribute('data-source-url') || '',
2599 + entryId: btn.getAttribute('data-entry-id') || '',
2600 + dataSource: btn.getAttribute('data-data-source') || 'wordpress',
2601 + botId: btn.getAttribute('data-bot-id') || 'default',
2602 + nonce: btn.getAttribute('data-nonce') || ''
2603 + };
2604 +
2605 + titleEl.textContent = I18N.title;
2606 + noticeEl.textContent = '';
2607 + noticeEl.className = 'mxchat-kb-edit-notice';
2608 + resultsEl.innerHTML = '<div class="mxch-testing-no-data">' + esc(I18N.loading) + '</div>';
2609 +
2610 + if (entry.sourceUrl && entry.sourceUrl.indexOf('mxchat://') !== 0 && entry.sourceUrl.indexOf('_ungrouped_') !== 0) {
2611 + sourceEl.innerHTML = esc(I18N.source) + ': <a href="' + esc(entry.sourceUrl) + '" target="_blank" rel="noopener">' + esc(entry.sourceUrl) + '</a>';
2612 + } else {
2613 + sourceEl.textContent = I18N.manual;
2614 + }
2615 +
2616 + modal.classList.add('active');
2617 +
2618 + var fd = new FormData();
2619 + fd.append('action', 'mxchat_inspect_entry');
2620 + fd.append('nonce', entry.nonce);
2621 + fd.append('source_url', entry.sourceUrl);
2622 + fd.append('entry_id', entry.entryId);
2623 + fd.append('data_source', entry.dataSource);
2624 + fd.append('bot_id', entry.botId);
2625 +
2626 + fetch(ajaxurl, { method: 'POST', body: fd })
2627 + .then(function(r) { return r.json(); })
2628 + .then(function(resp) {
2629 + if (resp && resp.success) {
2630 + render(resp.data);
2631 + } else {
2632 + var msg = (resp && resp.data && resp.data.message) || I18N.loadFail;
2633 + resultsEl.innerHTML = '';
2634 + showNotice(msg, 'error');
2635 + }
2636 + })
2637 + .catch(function(err) {
2638 + resultsEl.innerHTML = '';
2639 + showNotice(I18N.netErr + err.message, 'error');
2640 + });
1896 2641 }
1897 - }
1898 2642
1899 - function initMobileMenu() {
1900 - const menuBtn = document.querySelector('.mxch-mobile-menu-btn');
1901 - const closeBtn = document.querySelector('.mxch-mobile-menu-close');
1902 - const overlay = document.querySelector('.mxch-mobile-overlay');
1903 - const menu = document.querySelector('.mxch-mobile-menu');
2643 + function render(data) {
2644 + var storeLabel = data.store === 'pinecone' ? I18N.pcStore : I18N.wpStore;
2645 + var html = '';
1904 2646
1905 - if (menuBtn && menu) {
1906 - menuBtn.addEventListener('click', function() {
1907 - menu.classList.add('open');
1908 - if (overlay) overlay.classList.add('open');
2647 + // Summary card — what this entry is + how much was indexed.
2648 + html += '<div class="match-card above-threshold">' +
2649 + '<div class="match-header">' +
2650 + '<div class="match-title"><span class="status-icon">&#128230;</span> ' + esc(data.chunk_count) + ' ' + esc(I18N.chunksLbl.toLowerCase()) + '</div>' +
2651 + '<span class="context-label">' + esc(storeLabel) + '</span>' +
2652 + '</div>' +
2653 + '<div class="mxch-testing-field"><label>' + esc(I18N.type) + '</label><code>' + esc(data.content_type || '—') + '</code> ' +
2654 + '&nbsp; <label style="display:inline; text-transform:none; letter-spacing:0; font-weight:600;">' + esc(I18N.totalLen) + ':</label> ' + esc(fmt(data.assembled_length)) + ' ' + esc(I18N.chars) + '</div>';
2655 + if (data.metadata_note) {
2656 + html += '<div class="match-source"><span class="source-icon">&#8505;&#65039;</span> ' + esc(data.metadata_note) + '</div>';
2657 + }
2658 + html += '</div>';
2659 +
2660 + // One card per stored chunk — the actual embedded text.
2661 + var chunks = data.chunks || [];
2662 + chunks.forEach(function(chunk, i) {
2663 + var num = (chunk.index !== null && chunk.index !== undefined) ? (chunk.index + 1) : (i + 1);
2664 + var metaRows = '';
2665 + if (chunk.metadata && typeof chunk.metadata === 'object') {
2666 + var keys = Object.keys(chunk.metadata);
2667 + if (keys.length) {
2668 + metaRows += '<div class="chunk-detail-row chunk-used" style="display:block;"><span class="chunk-detail-num">' + esc(I18N.meta) + '</span></div>';
2669 + keys.forEach(function(k) {
2670 + metaRows += '<div class="chunk-detail-row"><span class="chunk-detail-num">' + esc(k) + '</span><span class="chunk-detail-score">' + esc(chunk.metadata[k]) + '</span></div>';
2671 + });
2672 + }
2673 + }
2674 + html += '<div class="match-card above-threshold">' +
2675 + '<div class="match-header">' +
2676 + '<div class="match-title"><span class="status-icon">&#10003;</span> ' + esc(I18N.chunk) + ' ' + esc(num) +
2677 + '<span class="chunk-summary">' + esc(fmt(chunk.length)) + ' ' + esc(I18N.chars) + '</span>' +
2678 + '</div>' +
2679 + '<span class="context-label">' + esc(I18N.indexed) + '</span>' +
2680 + '</div>' +
2681 + '<span class="chunk-expand-toggle" data-chunk="' + i + '">&#9654; ' + esc(I18N.showText) + '</span>' +
2682 + '<div class="chunk-details" data-chunk="' + i + '">' +
2683 + '<pre class="mxch-kb-inspect-chunk-text">' + esc(chunk.text) + '</pre>' +
2684 + metaRows +
2685 + '</div>' +
2686 + '</div>';
1909 2687 });
1910 - }
1911 2688
1912 - if (closeBtn && menu) {
1913 - closeBtn.addEventListener('click', function() {
1914 - menu.classList.remove('open');
1915 - if (overlay) overlay.classList.remove('open');
2689 + resultsEl.innerHTML = html;
2690 +
2691 + resultsEl.querySelectorAll('.chunk-expand-toggle').forEach(function(toggle) {
2692 + toggle.addEventListener('click', function() {
2693 + var id = this.getAttribute('data-chunk');
2694 + var details = resultsEl.querySelector('.chunk-details[data-chunk="' + id + '"]');
2695 + if (!details) return;
2696 + var expanded = details.classList.toggle('expanded');
2697 + this.innerHTML = (expanded ? '&#9660; ' + esc(I18N.hideText) : '&#9654; ' + esc(I18N.showText));
2698 + });
1916 2699 });
1917 2700 }
1918 2701
1919 - if (overlay && menu) {
1920 - overlay.addEventListener('click', function() {
1921 - menu.classList.remove('open');
1922 - overlay.classList.remove('open');
1923 - });
2702 + function showNotice(msg, type) {
2703 + noticeEl.textContent = msg;
2704 + noticeEl.className = 'mxchat-kb-edit-notice' + (type ? ' ' + type : '');
1924 2705 }
1925 - }
2706 + });
2707 + })();
2708 + </script>
2709 + <?php
2710 +}
1926 2711
2712 +/**
2713 + * Render Knowledge Page Navigation Scripts
2714 + */
2715 +function mxchat_render_knowledge_page_scripts() {
2716 + ?>
2717 + <script>
2718 + (function() {
2719 + 'use strict';
2720 +
2721 + // Wait for DOM
2722 + document.addEventListener('DOMContentLoaded', function() {
2723 + // Tab navigation + mobile menu live in the shared shell script
2724 + // (js/admin-sidebar.js), enqueued for this page by plan c192a4.
2725 + initImportOptions();
2726 + initCustomPostTypesToggle();
2727 + // Sitemap detection is now initialized when user clicks the Sitemap Import option
2728 + });
2729 +
1927 2730 function initImportOptions() {
1928 2731 const importBoxes = document.querySelectorAll('.mxchat-import-box');
1929 2732 const urlInputArea = document.getElementById('mxchat-url-input-area');
1930 2733 const contentInputArea = document.getElementById('mxchat-content-input-area');
@@ -2035,9 +2838,14 @@
2035 2838
2036 2839 if (!modal) return;
2037 2840
2038 2841 var currentEntry = {};
2842 + var loadedContent = '';
2039 2843
2844 + var EDIT_I18N = {
2845 + discard: <?php echo wp_json_encode( __('Discard your unsaved changes to this entry?', 'mxchat') ); ?>
2846 + };
2847 +
2040 2848 // Bind edit buttons (delegated)
2041 2849 document.addEventListener('click', function(e) {
2042 2850 var btn = e.target.closest('.mxchat-edit-entry-btn');
2043 2851 if (btn) {
@@ -2045,13 +2853,16 @@
2045 2853 openEditModal(btn);
2046 2854 }
2047 2855 });
2048 2856
2049 - // Close handlers
2050 - if (closeBtn) closeBtn.addEventListener('click', closeModal);
2051 - if (cancelBtn) cancelBtn.addEventListener('click', closeModal);
2052 - modal.addEventListener('click', function(e) {
2053 - if (e.target === modal) closeModal();
2857 + // Close handlers. The overlay deliberately has no click-to-close: a click
2858 + // fires on the common ancestor of its mousedown and mouseup, so releasing
2859 + // a text-selection drag past the dialog edge targets the overlay and would
2860 + // discard the edit. Closing is explicit only, and confirms when dirty.
2861 + if (closeBtn) closeBtn.addEventListener('click', requestClose);
2862 + if (cancelBtn) cancelBtn.addEventListener('click', requestClose);
2863 + document.addEventListener('keydown', function(e) {
2864 + if (e.key === 'Escape' && modal.classList.contains('active')) requestClose();
2054 2865 });
2055 2866
2056 2867 // Character count
2057 2868 if (textarea) {
@@ -2073,8 +2884,9 @@
2073 2884 };
2074 2885
2075 2886 // Reset state
2076 2887 textarea.value = '';
2888 + loadedContent = '';
2077 2889 textarea.placeholder = 'Loading content...';
2078 2890 textarea.disabled = true;
2079 2891 saveBtn.disabled = true;
2080 2892 notice.textContent = '';
@@ -2105,8 +2917,9 @@
2105 2917 .then(function(r) { return r.json(); })
2106 2918 .then(function(resp) {
2107 2919 if (resp.success) {
2108 2920 textarea.value = resp.data.content || '';
2921 + loadedContent = textarea.value;
2109 2922 textarea.disabled = false;
2110 2923 textarea.placeholder = 'Edit your content here...';
2111 2924 saveBtn.disabled = false;
2112 2925 currentEntry.contentType = resp.data.content_type || 'content';
@@ -2161,13 +2974,23 @@
2161 2974 if (saveSpin) saveSpin.style.display = 'none';
2162 2975 saveBtn.disabled = false;
2163 2976
2164 2977 if (resp.success) {
2165 - showNotice('Saved successfully!', 'success');
2166 - setTimeout(function() {
2167 - closeModal();
2168 - window.location.reload();
2169 - }, 1000);
2978 + if (currentEntry.dataSource === 'pinecone') {
2979 + // Pinecone list reads are eventually consistent — the reloaded
2980 + // table may show the old text for up to ~60 seconds.
2981 + showNotice('Saved! Pinecone changes may take up to 60 seconds to appear — use "Refresh Entries" if the list still shows the old text.', 'success');
2982 + setTimeout(function() {
2983 + closeModal();
2984 + window.location.reload();
2985 + }, 2500);
2986 + } else {
2987 + showNotice('Saved successfully!', 'success');
2988 + setTimeout(function() {
2989 + closeModal();
2990 + window.location.reload();
2991 + }, 1000);
2992 + }
2170 2993 } else {
2171 2994 showNotice((resp.data && resp.data.message) || 'Save failed.', 'error');
2172 2995 }
2173 2996 })
@@ -2176,8 +2999,17 @@
2176 2999 if (saveSpin) saveSpin.style.display = 'none';
2177 3000 saveBtn.disabled = false;
2178 3001 showNotice('Network error: ' + err.message, 'error');
2179 3002 });
3003 + }
3004 +
3005 + function isDirty() {
3006 + return !textarea.disabled && textarea.value !== loadedContent;
3007 + }
3008 +
3009 + function requestClose() {
3010 + if (isDirty() && !window.confirm(EDIT_I18N.discard)) return;
3011 + closeModal();
2180 3012 }
2181 3013
2182 3014 function closeModal() {
2183 3015 modal.classList.remove('active');