Skip to content

refactor(chatbot): modularize assistant engine and harden moderation …#828

Merged
alienx5499 merged 6 commits intomainfrom
refactor/assistant-engine-modularize
Apr 14, 2026
Merged

refactor(chatbot): modularize assistant engine and harden moderation …#828
alienx5499 merged 6 commits intomainfrom
refactor/assistant-engine-modularize

Conversation

@alienx5499
Copy link
Copy Markdown
Owner

This Pull Request refactors SortVision’s chatbot system into smaller focused modules, fully migrates chat API usage to /api/chatbot, and hardens moderation/language behavior while preserving the overall chat UX.

It changes the following:

  • Chatbot architecture: Split monolithic assistantEngine.js into modular units under src/components/chatbot/assistantEngine/ (constants, intentHandlers, responseTemplates, contextResponses, core/state, resolvers, templates, moderation) so orchestration stays in assistantEngine.js.
  • API migration: Remove legacy src/app/api/gemini/route.js and standardize on src/app/api/chatbot/route.js with robust NVIDIA/OpenAI-compatible request handling and fallback model support.
  • Moderation/security: Replace hardcoded blocked-term matching with package-based profanity detection, add server-side abuse tracking/threshold lockout, and enforce local fallback when abuse policy is triggered.
  • Language behavior: Pass website-selected UI language into chat context, improve multilingual greeting recognition (including non-English greetings), and ensure remote responses follow selected language.
  • Reliability: Improve local/remote routing and error fallback behavior, plus tighten endpoint/client integration (server/index.js, aiClient.js, env examples).

Testing

  • cd SortVision && pnpm run lint && pnpm run test:unit && pnpm run build
  • Manual API verification with curl:
    • normal response path (200)
    • abuse threshold lock path (403 with policy: abuse_block)
    • non-English response generation (Chinese query)

@alienx5499 alienx5499 requested a review from Copilot April 14, 2026 06:37
@vercel
Copy link
Copy Markdown

vercel Bot commented Apr 14, 2026

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
sortvision Ready Ready Preview, Comment Apr 14, 2026 7:41am

Comment thread SortVision/src/app/api/chatbot/route.js Fixed
Comment thread SortVision/src/app/api/chatbot/route.js Fixed
@github-actions
Copy link
Copy Markdown

github-actions Bot commented Apr 14, 2026

QA suite report

Metric Value
Total tests 659
Passed 659
Failed 0
Warnings 0
Pass rate 100.0%
Grade S+
Duration 4.50s

Result: passed.

View workflow run

QA vs main (last successful CI on base branch)

Baseline: last green Continuous integration on main @ 9652d58 (same test:ci suite).

Base This PR Δ passed
Passed 659 659 0
Failed 0 0
Total 659 659

Fixed (failed on base, passing on this PR)

None

New failures (failed on this PR; were not failing on base)

None

Still failing (failed on base and still failing on this PR)

None

Copy link
Copy Markdown
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull request overview

This PR refactors SortVision’s chatbot into a modular assistant engine, migrates remote chat to /api/chatbot, and adds moderation + multilingual behavior improvements while preserving the chat UX.

Changes:

  • Split the monolithic assistantEngine.js into focused modules (constants, intents, templates, resolvers, state, moderation).
  • Standardized remote chat handling via a new /api/chatbot route (OpenAI-compatible NVIDIA upstream + model fallbacks).
  • Added profanity-based moderation and abuse lockout handling, plus UI-language-aware prompting and localized help/welcome content.

Reviewed changes

Copilot reviewed 19 out of 20 changed files in this pull request and generated 10 comments.

Show a summary per file
File Description
SortVision/src/components/chatbot/assistantEngine/templates/localizedHelp.js Adds localized help snippets used when UI language isn’t English.
SortVision/src/components/chatbot/assistantEngine/responseTemplates.js Introduces centralized HTML response builders (code, help, algorithm info, etc.).
SortVision/src/components/chatbot/assistantEngine/resolvers/remoteResponse.js Remote response resolver using chatApiClient, with error-specific fallbacks and suggestions.
SortVision/src/components/chatbot/assistantEngine/resolvers/localResponse.js Local resolver for algorithm knowledge + suggestion injection.
SortVision/src/components/chatbot/assistantEngine/moderation.js Adds bad-words profanity detection and a shared abuse threshold.
SortVision/src/components/chatbot/assistantEngine/intentHandlers.js Adds intent scoring, algorithm extraction, and keyword matching helpers.
SortVision/src/components/chatbot/assistantEngine/core/state.js Centralizes message history, conversation context, and response cache.
SortVision/src/components/chatbot/assistantEngine/contextResponses.js Adds contextual/follow-up/reset/fallback response generation.
SortVision/src/components/chatbot/assistantEngine/constants.js Consolidates assistant constants (keywords, patterns, algorithm data, instant responses).
SortVision/src/components/chatbot/assistantEngine/aiClient.js Migrates client to /api/chatbot and injects UI-language steering into prompts.
SortVision/src/components/chatbot/assistantEngine.js New orchestration layer wiring moderation, local/remote routing, caching, and localization.
SortVision/src/components/chatbot/ChatButton.jsx Minor UI tweak (removed robot icon span content).
SortVision/src/components/chatbot/ChatAssistant.jsx Passes selected UI language into assistant context and localizes welcome message.
SortVision/src/app/api/gemini/route.js Removes legacy Gemini route.
SortVision/src/app/api/chatbot/route.js Adds new OpenAI-compatible chat endpoint with abuse tracking and model fallback.
SortVision/server/index.js Updates proxy server to /api/chatbot and adds abuse tracking.
SortVision/package.json Adds bad-words and openai dependencies.
SortVision/pnpm-lock.yaml Locks new dependencies.
SortVision/.env.example Updates environment examples for the new chat provider configuration.
Files not reviewed (1)
  • SortVision/pnpm-lock.yaml: Language not supported

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread SortVision/src/components/chatbot/assistantEngine/resolvers/localResponse.js Outdated
Comment thread SortVision/src/app/api/chatbot/route.js Outdated
Comment thread SortVision/server/index.js
Comment thread SortVision/src/components/chatbot/assistantEngine/responseTemplates.js Outdated
Comment thread SortVision/src/components/chatbot/ChatButton.jsx Outdated
Comment thread SortVision/src/components/chatbot/assistantEngine/templates/localizedHelp.js Outdated
Comment thread SortVision/src/components/chatbot/assistantEngine/intentHandlers.js
Comment thread SortVision/src/components/chatbot/assistantEngine/contextResponses.js Outdated
Comment thread SortVision/src/components/chatbot/ChatAssistant.jsx Outdated
Comment thread SortVision/server/index.js Outdated
@github-actions
Copy link
Copy Markdown

github-actions Bot commented Apr 14, 2026

Lighthouse (CI)

View workflow run

Lighthouse vs main (last green CI on base)

Lighthouse (mobile)

Δ = change vs last successful Continuous integration on main (same URLs).

URL Perf Δ A11y Δ Best Δ SEO Δ
http://localhost:3000/ 61 -6 96 93 100
http://localhost:3000/algorithms/config/bubble 78 +2 96 93 100
http://localhost:3000/es 68 -9 96 93 100
http://localhost:3000/contributions/overview 67 96 96 100

Lighthouse (desktop)

Δ = change vs last successful Continuous integration on main (same URLs).

URL Perf Δ A11y Δ Best Δ SEO Δ
http://localhost:3000/ 97 -1 96 96 100
http://localhost:3000/algorithms/config/bubble 98 96 96 100
http://localhost:3000/es 98 96 96 100
http://localhost:3000/contributions/overview 98 96 96 100

Copy link
Copy Markdown
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull request overview

Copilot reviewed 19 out of 20 changed files in this pull request and generated 11 comments.

Files not reviewed (1)
  • SortVision/pnpm-lock.yaml: Language not supported

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread SortVision/src/app/api/chatbot/route.js Outdated
Comment thread SortVision/src/app/api/chatbot/route.js
Comment thread SortVision/src/app/api/chatbot/route.js
Comment thread SortVision/src/components/chatbot/ChatAssistant.jsx Outdated
Comment thread SortVision/src/components/chatbot/ChatAssistant.jsx Outdated
Comment thread SortVision/src/app/api/chatbot/route.js
Comment thread SortVision/src/components/chatbot/assistantEngine.js
Comment thread SortVision/.env.example
Comment thread SortVision/server/index.js Outdated
Comment thread SortVision/src/components/chatbot/assistantEngine.js Outdated
Copy link
Copy Markdown
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull request overview

Copilot reviewed 19 out of 20 changed files in this pull request and generated 2 comments.

Files not reviewed (1)
  • SortVision/pnpm-lock.yaml: Language not supported
Comments suppressed due to low confidence (1)

SortVision/src/components/chatbot/ChatAssistant.jsx:234

  • handleError calls setErrorCount(prev => prev + 1) but then decides between “Temporary” vs “Persistent” using the old errorCount value from the closure (errorCount > 2). This makes the threshold off-by-one and can show the wrong message.

Suggestion: compute nextCount inside the setErrorCount updater (or before updating state) and use that value to choose the message, so the UI reflects the incremented count consistently.

  const handleError = useCallback(
    error => {
      console.error('Error: Chat Error:', error);
      setErrorCount(prev => prev + 1);

      let errorMessage = '';

      if (error.message?.includes('TIMEOUT_ERROR')) {
        errorMessage = `
          <div class="animate-fade-in space-y-1 max-w-full">
            <p class="m-0 text-orange-400"> Request Timeout</p>
            <p class="m-0 text-sm">The request took too long to process. Let me help you with local knowledge instead!</p>
            <p class="m-0 text-xs text-blue-300">Tip: Try asking about specific algorithms!</p>
          </div>`;
      } else if (error.message?.includes('NETWORK_ERROR')) {
        errorMessage = `
          <div class="animate-fade-in space-y-1 max-w-full">
            <p class="m-0 text-yellow-400"> Connection Issue</p>
            <p class="m-0 text-sm">I'm having trouble connecting. Let me help you with local knowledge instead!</p>
            <p class="m-0 text-xs text-blue-300">Tip: Try asking about specific algorithms!</p>
          </div>`;
      } else if (error.message?.includes('RATE_LIMIT')) {
        errorMessage = `
          <div class="animate-fade-in space-y-1 max-w-full">
            <p class="m-0 text-orange-400"> Rate Limit Reached</p>
            <p class="m-0 text-sm">I'm getting too many requests. Please wait a moment and try again!</p>
            <p class="m-0 text-xs text-blue-300">Tip: In the meantime, try exploring the algorithms above!</p>
          </div>`;
      } else if (error.message?.includes('SERVER_ERROR')) {
        errorMessage = `
          <div class="animate-fade-in space-y-1 max-w-full">
            <p class="m-0 text-red-400"> Server Issue</p>
            <p class="m-0 text-sm">There's a temporary server issue. Let me help you with local knowledge instead!</p>
            <p class="m-0 text-xs text-blue-300">Tip: Try asking about specific algorithms!</p>
          </div>`;
      } else {
        errorMessage =
          errorCount > 2
            ? `
            <div class="animate-fade-in space-y-1 max-w-full">
              <p class="m-0 text-red-400"> Persistent Issue</p>
              <p class="m-0 text-sm">I'm having trouble connecting. Please try again later or refresh the page.</p>
              <p class="m-0 text-xs text-blue-300">Tip: In the meantime, explore the algorithms above!</p>
            </div>`
            : `
            <div class="animate-fade-in space-y-1 max-w-full">
              <p class="m-0 text-yellow-400"> Temporary Issue</p>
              <p class="m-0 text-sm">I encountered an error. Let me try to help you again.</p>
              <p class="m-0 text-xs text-blue-300">Tip: Try asking about specific algorithms!</p>
            </div>`;
      }

      setMessages(prev => [
        ...prev,
        {
          role: 'error',
          content: errorMessage,
        },
      ]);

      setIsTyping(false);
    },
    [errorCount]
  );

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread SortVision/src/components/chatbot/assistantEngine/resolvers/remoteResponse.js Outdated
Comment thread SortVision/server/index.js
Copy link
Copy Markdown
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull request overview

Copilot reviewed 19 out of 20 changed files in this pull request and generated 3 comments.

Files not reviewed (1)
  • SortVision/pnpm-lock.yaml: Language not supported

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread SortVision/src/components/chatbot/assistantEngine/moderation.js
Comment thread SortVision/src/components/chatbot/assistantEngine/aiClient.js Outdated
Comment thread SortVision/server/index.js Outdated
@alienx5499 alienx5499 merged commit d29983e into main Apr 14, 2026
19 checks passed
@alienx5499 alienx5499 deleted the refactor/assistant-engine-modularize branch May 3, 2026 14:01
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants