Skip to content

Conversation

sapayth
Copy link
Member

@sapayth sapayth commented Sep 1, 2025

fixes #1086

Introduces a new 'AI Settings' section in the settings options, allowing selection of AI provider, model, and API key. Adds dynamic filtering of AI models in the admin UI based on the selected provider. Removes unnecessary debug console logs from admin posting scripts and makes a minor formatting fix in the frontend render form.

Summary by CodeRabbit

  • New Features
    • Added AI Settings in admin to configure provider, model, and API key.
    • Model dropdown now auto-filters based on the selected provider, preserves valid existing choices, and selects a provider-specific default when needed.
    • Settings support extensible model lists for future additions.
  • Chores
    • Removed debug console logs from admin metabox scripts to reduce noise.

Introduces a new 'AI Settings' section in the settings options, allowing selection of AI provider, model, and API key. Adds dynamic filtering of AI models in the admin UI based on the selected provider. Removes unnecessary debug console logs from admin posting scripts and makes a minor formatting fix in the frontend render form.
Copy link

coderabbitai bot commented Sep 1, 2025

Walkthrough

Introduces an AI Settings section to admin settings with provider, model, and API key fields; adds client-side filtering of AI models based on selected provider; removes debug logs in admin posting scripts; and applies a minor whitespace formatting change in frontend form rendering.

Changes

Cohort / File(s) Summary
Admin Settings: AI Configuration
includes/functions/settings-options.php
Adds wpuf_ai settings section with fields: ai_provider (select), ai_model (select with provider-grouped options via filter), and ai_api_key (text).
Admin JS: AI Model Filtering
assets/js/wpuf-admin.js
Implements dynamic filtering of AI model options when AI provider changes; initializes on load; preserves valid selections; applies provider-specific default model mapping.
Admin Metabox: Log Cleanup
includes/Admin/Posting.php
Removes console log statements around WPUF_Field_Initializer checks; retains existing init call and control flow.
Formatting Cleanup
includes/class-frontend-render-form.php
Whitespace-only change in render_featured_field sprintf call.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Assessment against linked issues

Objective Addressed Explanation
gmap required doesn’t work when multiple maps are on same form (#1086) No changes to gmap fields, validation, or multi-map handling present.

Assessment against linked issues: Out-of-scope changes

Code Change Explanation
Add AI Settings section and fields (includes/functions/settings-options.php) Introduces AI configuration; unrelated to gmap required validation or multiple map instances.
Dynamic filtering of AI models by provider (assets/js/wpuf-admin.js) Client-side AI model handling; not connected to gmap input validation.
Remove admin metabox console logs (includes/Admin/Posting.php) Logging cleanup; does not affect gmap required behavior.

Poem

I twitch my ears at toggled skies, 🐇
New knobs for brains and model pies,
Drop-down fields that dance in sync,
Quiet logs—no more clatter or clink,
I hop through settings, swift and spry—
Click, select, and off I fly! ✨

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

Other keywords and placeholders

  • Add @coderabbitai ignore or @coderabbit ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (4)
assets/js/wpuf-admin.js (2)

239-257: Avoid filtering by provider via display text; add a provider attribute.

Relying on option text containing “(OpenAI)/(Anthropic)/...” is brittle (customizations, filters, localization). Prefer a data attribute (e.g., data-provider) or a value prefix to classify options.

Example minimal client-side indexing (no PHP changes), then filter on the indexed attribute:

-        // Filter and add relevant options based on provider
-        aiModelSelect.data('all-options').each(function() {
+        // Index provider once from trailing "(Provider)" if not already set
+        if (!aiModelSelect.data('provider-indexed')) {
+            aiModelSelect.data('all-options').each(function () {
+                var $opt = $(this);
+                var m = $opt.text().match(/\(([^)]+)\)\s*$/);
+                if (m) { $opt.attr('data-provider', m[1].toLowerCase()); }
+            });
+            aiModelSelect.data('provider-indexed', true);
+        }
+        // Filter and add relevant options based on provider
+        aiModelSelect.data('all-options').each(function() {
             var option = $(this);
-            var optionText = option.text();
-            var optionValue = option.val();
+            var optionValue = option.val();
             // Skip empty value option
             if (!optionValue) return;
-            // Check if option belongs to selected provider
-            if (selectedProvider === 'openai' && optionText.includes('(OpenAI)')) {
-                aiModelSelect.append(option.clone());
-            } else if (selectedProvider === 'anthropic' && optionText.includes('(Anthropic)')) {
-                aiModelSelect.append(option.clone());
-            } else if (selectedProvider === 'google' && optionText.includes('(Google)')) {
-                aiModelSelect.append(option.clone());
-            } else if (selectedProvider === 'others' && optionText.includes('(Others)')) {
-                aiModelSelect.append(option.clone());
-            }
+            if (option.attr('data-provider') === selectedProvider) {
+                aiModelSelect.append(option.clone());
+            }
         });

263-276: Guard defaults and prefer localized placeholder text.

  • Ensure the default model exists before selecting; otherwise pick the first real option.
  • “Select AI Model” should be localized (use wp_localize_script or wp.i18n).

Apply:

-        aiModelSelect.append('<option value="">Select AI Model</option>');
+        aiModelSelect.append('<option value="">' + (window.wpuf_admin_i18n?.select_ai_model || 'Select AI Model') + '</option>');
@@
-        } else if (defaultModels[selectedProvider]) {
-            // Fall back to default model for the provider
-            aiModelSelect.val(defaultModels[selectedProvider]);
+        } else if (defaultModels[selectedProvider] && aiModelSelect.find('option[value="' + defaultModels[selectedProvider] + '"]').length) {
+            aiModelSelect.val(defaultModels[selectedProvider]);
+        } else {
+            // Fallback: select first available provider-specific model if present
+            var $first = aiModelSelect.find('option[value!=""]').first();
+            if ($first.length) { aiModelSelect.val($first.val()); }
         }

(Expose wpuf_admin_i18n.select_ai_model via wp_localize_script where this file is enqueued.)

includes/functions/settings-options.php (2)

640-707: Use password field for API key and consider stronger storage/handling.

Displaying/storing API keys in plain text is risky in shared-admin contexts. Use a password-type field to mask input, and (optionally) avoid echoing the saved value back verbatim.

-            [
-                'name'    => 'ai_api_key',
-                'label'   => __( 'API Key', 'wp-user-frontend' ),
-                'desc'    => __( 'Enter your AI service API key. Keep this secure and never share it publicly.', 'wp-user-frontend' ),
-                'type'    => 'text',
-                'default' => '',
-            ],
+            [
+                'name'    => 'ai_api_key',
+                'label'   => __( 'API Key', 'wp-user-frontend' ),
+                'desc'    => __( 'Enter your AI service API key. Keep this secure and never share it publicly.', 'wp-user-frontend' ),
+                'type'    => 'password',
+                'default' => '',
+            ],

If feasible, add a sanitize callback to trim and store, and render a placeholder (e.g., ••••) when a key exists.


656-704: Facilitate robust provider filtering from JS.

Since the admin JS needs to filter models by provider, expose a machine-readable provider key per option (e.g., value prefix openai:gpt-4o or data-provider attribute rendered by the settings API). This avoids parsing human labels.

If altering values is acceptable:

- 'gpt-4o' => 'GPT-4o (OpenAI)',
+ 'openai:gpt-4o' => 'GPT-4o (OpenAI)',

Then update JS to split on : and match provider reliably.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between aab3cf7 and f91ca2e.

📒 Files selected for processing (4)
  • assets/js/wpuf-admin.js (1 hunks)
  • includes/Admin/Posting.php (1 hunks)
  • includes/class-frontend-render-form.php (1 hunks)
  • includes/functions/settings-options.php (2 hunks)
🔇 Additional comments (4)
includes/Admin/Posting.php (2)

688-695: Good removal of noisy console log.

Swapping the console.log for a comment keeps admin console clean while preserving the initializer guard.


688-695: Confirm gmap “required” fix is actually in the PR.

The PR description says it fixes issue #1086 (“gmap required” with multiple maps), but this file only removes a log. Please point to the commit/file that implements the validation fix, or add it to this PR.

includes/functions/settings-options.php (2)

52-56: AI Settings section inclusion looks good.

Section id, title, and icon are consistent with existing sections.


656-704: Verify model identifiers and future-proof the list.

Some slugs look hypothetical or umbrella (e.g., gpt-5, gpt-4.5, embeddings, tts). Please confirm identifiers you intend to support, and consider sourcing this list via a provider API or filter-only to avoid drift.

Would you like a small adapter that maps providers to models via a filterable registry, so the UI auto-populates from a single source?

Comment on lines 932 to 936
<input type="checkbox" class="wpuf_is_featured" name="is_featured_item" value="1" <?php echo $is_featured ? 'checked' : ''; ?> >
<span class="wpuf-items-table-containermessage-box" id="remaining-feature-item"> <?php echo sprintf(
<span class="wpuf-items-table-containermessage-box" id="remaining-feature-item"> <?php echo sprintf(
// translators: %1$s is Post type and %2$s is total feature item
wp_kses_post(__( 'Mark the %1$s as featured (remaining %2$d)', 'wp-user-frontend' ), esc_html ($this->form_settings['post_type'] ), esc_html( $user_sub['total_feature_item'] ) )); ?></span>
</label>
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Fix fatal sprintf/escaping misuse and broken selector for counter.

  • wp_kses_post() is called with extra args (PHP ArgumentCountError). Also, sprintf args are passed to wp_kses_post instead of sprintf.
  • The counter selector in JS looks for .wpuf-message-box, but the span has class="wpuf-items-table-containermessage-box" → the live counter won’t update.

Apply this diff to fix both issues and harden types:

-                         <span class="wpuf-items-table-containermessage-box" id="remaining-feature-item"> <?php echo sprintf(
-                            // translators: %1$s is Post type and %2$s is total feature item
-                            wp_kses_post(__( 'Mark the %1$s as featured (remaining %2$d)', 'wp-user-frontend' ), esc_html ($this->form_settings['post_type'] ), esc_html( $user_sub['total_feature_item'] ) )); ?></span>
+                         <span class="wpuf-message-box" id="remaining-feature-item">
+                             <?php
+                             // translators: %1$s is Post type and %2$d is total feature item
+                             printf(
+                                 esc_html__( 'Mark the %1$s as featured (remaining %2$d)', 'wp-user-frontend' ),
+                                 esc_html( $this->form_settings['post_type'] ),
+                                 absint( $user_sub['total_feature_item'] )
+                             );
+                             ?>
+                         </span>
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
<input type="checkbox" class="wpuf_is_featured" name="is_featured_item" value="1" <?php echo $is_featured ? 'checked' : ''; ?> >
<span class="wpuf-items-table-containermessage-box" id="remaining-feature-item"> <?php echo sprintf(
<span class="wpuf-items-table-containermessage-box" id="remaining-feature-item"> <?php echo sprintf(
// translators: %1$s is Post type and %2$s is total feature item
wp_kses_post(__( 'Mark the %1$s as featured (remaining %2$d)', 'wp-user-frontend' ), esc_html ($this->form_settings['post_type'] ), esc_html( $user_sub['total_feature_item'] ) )); ?></span>
</label>
<input
type="checkbox"
class="wpuf_is_featured"
name="is_featured_item"
value="1"
<?php echo $is_featured ? 'checked' : ''; ?>
>
<span class="wpuf-message-box" id="remaining-feature-item">
<?php
// translators: %1$s is Post type and %2$d is total feature item
printf(
esc_html__( 'Mark the %1$s as featured (remaining %2$d)', 'wp-user-frontend' ),
esc_html( $this->form_settings['post_type'] ),
absint( $user_sub['total_feature_item'] )
);
?>
</span>
</label>

@Rubaiyat-E-Mohammad Rubaiyat-E-Mohammad added QA Approved This PR is approved by the QA team and removed needs: testing labels Sep 3, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
QA Approved This PR is approved by the QA team
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants