Skip to content

feat: add integration and initialization scripts for website (Fortress PR #190-C)#202

Merged
uelkerd merged 8 commits into
mainfrom
feat/website-js-integration
Sep 27, 2025
Merged

feat: add integration and initialization scripts for website (Fortress PR #190-C)#202
uelkerd merged 8 commits into
mainfrom
feat/website-js-integration

Conversation

@uelkerd
Copy link
Copy Markdown
Owner

@uelkerd uelkerd commented Sep 27, 2025

Summary

🏰 Fortress-Compliant Split (2/9 files) - Integration & Initialization

This is the final of three fortress-compliant PRs splitting the original PR #190. This PR focuses specifically on integration and initialization scripts that bring together all website functionality into a cohesive user experience.

Files in this PR (2 files):

  • website/js/comprehensive-demo.js - Complete demo page functionality with user interactions and API integration
  • website/js/demo-initialization.js - Application startup and module coordination for seamless initialization

Key Features:

Fortress Strategy:

This is PR #190-C (final) of a three-part fortress split:

Testing Checklist:

  • Demo page loads and initializes all components correctly
  • API integration works with live endpoints
  • User interactions (voice recording, text analysis) function properly
  • Error handling provides appropriate user feedback
  • Mobile and desktop responsive functionality
  • Cross-browser compatibility verification

Dependencies:

Technical Achievements:

  • Total Project Lines: 3,054 lines across all three fortress PRs
  • Modular Architecture: Clean separation enabling independent review
  • Error Handling: Comprehensive error management and user feedback
  • Performance: Optimized initialization and resource loading

Integration Notes:

When all three PRs are merged in sequence, they provide:

  1. Foundation (PR Website JavaScript Modules from PR #169 (Part 2/2) #190-A): HTML structure and configuration
  2. Core Logic (PR Website JavaScript Modules from PR #169 (Part 2/2) #190-B): Reusable JavaScript modules
  3. User Experience (PR Website JavaScript Modules from PR #169 (Part 2/2) #190-C): Complete interactive functionality

⚠️ Code Review Required: This PR requires thorough code review before merging as per fortress methodology.

🎯 Final PR: This completes the fortress-compliant split of original PR #190.

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features
    • In-browser demo now supports voice transcription, text summarization, and emotion detection in a single workflow.
    • Resilient demo experience with realistic mock results when APIs are unavailable.
    • UI enhancements: progress console, inline success/error messages, emotion chart, sample text generation, and API key management.
  • Improvements
    • Robust request handling with retries, timeouts, and cold-start detection for smoother interactions.
    • Streamlined initialization: buttons wired for Process/Generate/API Key/Clear, safe state resets, and detailed console tracing.
    • Optional debug mode via URL flag and Bootstrap tooltip initialization when available.

- Add comprehensive-demo.js for complete demo page functionality and user interactions
- Add demo-initialization.js for application startup and module coordination

These integration scripts bring together the core modules from PR #190-B
to create the complete interactive website experience. Handles user workflows,
API integration, and coordinated initialization of all website features.

Fortress-compliant PR #190-C (2 files) - Integration & Initialization
Final part of fortress split from original PR #190 for better review compliance.

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>
Copilot AI review requested due to automatic review settings September 27, 2025 19:29
Copy link
Copy Markdown
Contributor

@sourcery-ai sourcery-ai Bot left a comment

Choose a reason for hiding this comment

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

Sorry @uelkerd, you have reached your weekly rate limit of 500000 diff characters.

Please try again later or upgrade to continue using Sourcery

@gemini-code-assist
Copy link
Copy Markdown
Contributor

Summary of Changes

Hello @uelkerd, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request finalizes the development of the website's AI platform demo by integrating all previously separated components. It establishes the client-side logic for interacting with the SAMO API, managing user input, generating AI-powered content, and presenting analytical results. The changes ensure a cohesive, interactive, and production-ready user experience, complete with robust error handling and initialization sequences.

Highlights

  • Final Integration Phase: This pull request marks the completion of the three-part "fortress-compliant split" for the website, specifically focusing on integrating and initializing all components to create a cohesive user experience.
  • SAMOAPIClient Implementation: A robust SAMOAPIClient has been introduced to handle all API requests, featuring configurable base URLs and endpoints, API key management, retry logic with exponential backoff for network and server errors, cold start optimization, and mock data fallbacks for summarization and emotion detection.
  • Comprehensive Demo Functionality: Core demo logic has been added, including AI-powered sample text generation (with OpenAI API integration and fallback to curated texts), text processing for emotion detection and summarization, and dynamic display of results with an emotion chart and a detailed progress console.
  • Enhanced User Experience & Initialization: The PR implements smooth scrolling for navigation, inline message display for user feedback, and a dedicated demo-initialization.js script to manage DOM ready events, button listeners (Process, Generate, API Key, Clear), and overall layout initialization, including Bootstrap tooltips.
  • Robust Error Handling & State Management: Comprehensive error handling for API calls, network issues, and timeouts has been incorporated, alongside functions for clearing results and resetting the demo to its initial state, often coordinating with a LayoutManager (if available).
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Sep 27, 2025

Note

Other AI code review bot(s) detected

CodeRabbit has detected other AI code review bot(s) in this pull request and will avoid duplicating their findings in the review comments. This may lead to a less comprehensive review.

Walkthrough

Adds a browser-based AI demo client (SAMOAPIClient) with unified request/retry/timeout handling for transcription, summarization, and emotion detection, plus mock fallbacks and UI helpers. Introduces a demo initialization script that wires UI events, state management, optional LayoutManager hooks, Bootstrap tooltip setup, and debug toggling on DOMContentLoaded.

Changes

Cohort / File(s) Summary
Comprehensive Demo Client and Helpers
website/js/comprehensive-demo.js
New SAMOAPIClient with centralized config, API key retrieval, resilient fetch with retries/backoff/timeouts, cold-start handling, and AbortController. Implements transcribe/summarize/emotion flows, mock generators, a combined workflow, UI helper functions, progress console, and global exports/initialization.
Demo Initialization and UI Wiring
website/js/demo-initialization.js
New DOMContentLoaded initializer wiring buttons (Process/Generate/API Key/Clear), optional LayoutManager state functions, debug toggle via URL, Bootstrap tooltip init, and verbose logging with error handling.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  actor U as User
  participant UI as Demo UI (Buttons/DOM)
  participant C as SAMOAPIClient
  participant V as VOICE_JOURNAL API
  participant S as SUMMARIZE API
  participant E as EMOTION API

  U->>UI: Click Process
  UI->>C: processCompleteWorkflow(audioFile, text)
  alt Audio provided
    C->>V: POST /voice_journal (FormData)
    V-->>C: Transcription JSON
    note over C: On failure or timeout → mock transcription
  else No audio
    note over C: Use provided text
  end
  C->>S: POST /summarize (JSON)
  S-->>C: Summary JSON
  note over C: On failure → mock summary
  C->>E: POST /emotion (JSON)
  E-->>C: Emotions JSON
  note over C: On failure → mock emotions
  C-->>UI: Aggregated results
  UI-->>U: Render transcript, summary, emotions
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

Suggested reviewers

  • sourcery-ai

Poem

A rabbit taps keys with a rhythmic delight,
Stitching requests through morning to night.
If APIs nap, no need to despair—
Mock carrots appear from thin air.
Transcribe, summarize, emotions in tow,
Hop, hop, hooray—see the demo glow! 🥕✨

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 60.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check name Status Explanation
Title Check ✅ Passed The title clearly reflects the addition of integration and initialization scripts for the website, matches the changeset, and uses a concise conventional commit style without listing file names or unnecessary details.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
✨ Finishing touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch feat/website-js-integration

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

Comment @coderabbitai help to get the list of available commands and usage tips.

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 completes the fortress-compliant split of PR #190 by adding integration and initialization scripts that bring together all website functionality into a cohesive user experience. It introduces a comprehensive AI platform demo with voice transcription, text summarization, emotion detection, and API key management capabilities.

  • Complete demo page functionality with API client, error handling, and user interactions
  • Application startup and module coordination for seamless initialization
  • Integration with SAMO API endpoints including emotion analysis, summarization, and transcription

Reviewed Changes

Copilot reviewed 2 out of 2 changed files in this pull request and generated 1 comment.

File Description
website/js/demo-initialization.js Handles DOM ready events, button listeners, and component initialization
website/js/comprehensive-demo.js Main demo functionality with SAMO API client, processing workflows, and UI management

Tip: Customize your code reviews with copilot-instructions.md. Create the file or learn how to get started.

Comment thread website/js/demo-initialization.js Outdated
@deepsource-io
Copy link
Copy Markdown
Contributor

deepsource-io Bot commented Sep 27, 2025

Here's the code health analysis summary for commits af71436..8fd6874. View details on DeepSource ↗.

Analysis Summary

AnalyzerStatusSummaryLink
DeepSource Test coverage LogoTest coverage⚠️ Artifact not reportedTimed out: Artifact was never reportedView Check ↗
DeepSource Python LogoPython✅ SuccessView Check ↗
DeepSource Terraform LogoTerraform✅ SuccessView Check ↗
DeepSource Secrets LogoSecrets✅ SuccessView Check ↗
DeepSource Shell LogoShell✅ SuccessView Check ↗
DeepSource Docker LogoDocker✅ SuccessView Check ↗

💡 If you’re a repository administrator, you can configure the quality gates from the settings.

Copy link
Copy Markdown
Contributor

@gemini-code-assist gemini-code-assist Bot left a comment

Choose a reason for hiding this comment

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

Code Review

This pull request introduces the core JavaScript logic for the comprehensive demo page and its initialization. The code is well-structured, particularly the SAMOAPIClient class which includes robust features like request retries with exponential backoff and timeout handling. The separation of the main demo logic from the initialization script is also a good practice.

My review focuses on improving maintainability, robustness, and user experience. Key suggestions include:

  • Consolidating API client instances to avoid redundancy.
  • Namespacing global functions to prevent polluting the global scope.
  • Improving user feedback mechanisms during error states.
  • Refactoring initialization logic for better clarity.

Overall, this is a solid contribution that lays the foundation for the website's interactive demo. The changes are substantial and well-implemented.

Comment on lines +426 to +459
document.addEventListener('DOMContentLoaded', function() {
console.log('✅ DOM loaded, initializing demo...');
console.log('🔧 Using simple-demo-functions.js for chart implementation');

// Initialize global API client
try {
window.apiClient = new SAMOAPIClient();
console.log('✅ Global API client initialized');
} catch (error) {
console.error('❌ Failed to initialize API client:', error);
}
});

// Smooth scrolling for in-page navigation links
// Only applies to anchors within the main navigation to avoid interfering with external or footer anchors
document.addEventListener('DOMContentLoaded', () => {
document.querySelectorAll('nav a[href^="#"], .navbar a[href^="#"], #main-nav a[href^="#"]').forEach(anchor => {
anchor.addEventListener('click', function (e) {
// Only handle if the link is for the current page
if (location.pathname === anchor.pathname && location.hostname === anchor.hostname) {
e.preventDefault();
const href = this.getAttribute('href');
if (!href) return;
const target = document.querySelector(href);
if (target) {
target.scrollIntoView({
behavior: 'smooth',
block: 'start'
});
}
}
});
});
});
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

medium

This file contains two separate DOMContentLoaded event listeners. While this works, it can make the initialization flow harder to follow and manage. Combining them into a single listener would improve code clarity and ensure a predictable execution order for all initialization logic within this file.

document.addEventListener('DOMContentLoaded', function() {
    console.log('✅ DOM loaded, initializing demo...');
    console.log('🔧 Using simple-demo-functions.js for chart implementation');

    // Initialize global API client
    try {
        window.apiClient = new SAMOAPIClient();
        console.log('✅ Global API client initialized');
    } catch (error) {
        console.error('❌ Failed to initialize API client:', error);
    }

    // Smooth scrolling for in-page navigation links
    document.querySelectorAll('nav a[href^="#"], .navbar a[href^="#"], #main-nav a[href^="#"]').forEach(anchor => {
        anchor.addEventListener('click', function (e) {
            // Only handle if the link is for the current page
            if (location.pathname === anchor.pathname && location.hostname === anchor.hostname) {
                e.preventDefault();
                const href = this.getAttribute('href');
                if (!href) return;
                const target = document.querySelector(href);
                if (target) {
                    target.scrollIntoView({
                        behavior: 'smooth',
                        block: 'start'
                    });
                }
            }
        });
    });
});

Comment thread website/js/comprehensive-demo.js Outdated
Comment thread website/js/comprehensive-demo.js Outdated
Comment thread website/js/comprehensive-demo.js Outdated
Comment thread website/js/comprehensive-demo.js Outdated
Comment on lines +28 to +30
} else {
console.error('❌ processText function not available');
}
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

medium

When a required function like processText is not available, the error is only logged to the console. This provides no feedback to the user, who will just see a non-functional button. It would be a better user experience to display a visible error message on the page. This applies to the other error-handling cases in this file as well.

            } else {
                console.error('❌ processText function not available');
                alert('Error: Core demo functionality is missing. Please reload the page.');
            }

Copy link
Copy Markdown

@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: 3

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
website/js/comprehensive-demo.js (1)

1-1317: Ensure presence of LayoutManager, state-management helpers, Bootstrap, and SAMO_CONFIG

  • LayoutManager is used extensively (e.g. addActiveRequest, showProcessingState, resetToInitialState) but no implementation or import was found; define or import it before use.
  • In website/js/demo-initialization.js, processTextWithStateManagement, clearAllWithStateManagement, and updateApiKeyButtonStatus are referenced yet not defined; add their definitions or remove these fallbacks.
  • No Bootstrap assets or data-bs-toggle="tooltip" attributes were detected in any HTML—ensure Bootstrap CSS/JS is loaded for UI components.
  • window.SAMO_CONFIG is referenced in JS but not provisioned anywhere in HTML/JS/JSON; inject it or supply a fallback configuration to avoid runtime warnings.
🧹 Nitpick comments (10)
website/js/demo-initialization.js (4)

20-31: Reference optional globals via window to be module-safe

Accessing undeclared identifiers works with typeof but subsequent calls can fail under modules/strict mode. Prefer window.* for both checks and invocations.

-            if (typeof processTextWithStateManagement === 'function') {
-                processTextWithStateManagement();
+            if (typeof window.processTextWithStateManagement === 'function') {
+                window.processTextWithStateManagement();
             } else if (typeof window.processText === 'function') {
-            if (typeof clearAllWithStateManagement === 'function') {
-                clearAllWithStateManagement();
+            if (typeof window.clearAllWithStateManagement === 'function') {
+                window.clearAllWithStateManagement();
             } else if (typeof window.clearAll === 'function') {
-        if (typeof updateApiKeyButtonStatus === 'function') {
-            updateApiKeyButtonStatus();
+        if (typeof window.updateApiKeyButtonStatus === 'function') {
+            window.updateApiKeyButtonStatus();
         }

Also applies to: 85-96, 71-73


49-51: Avoid enumerating window for logging

Object.keys(window) can be huge and noisy. Log capability, not inventory.

-                console.log('🔍 Available functions:', Object.keys(window).filter(key => key.includes('generate')));
+                console.log('🔍 generateSampleText present:', typeof window.generateSampleText === 'function');

7-9: Make initialization idempotent to prevent duplicate listeners

If the script is loaded twice, this avoids double-binding.

-document.addEventListener('DOMContentLoaded', function() {
+document.addEventListener('DOMContentLoaded', function() {
+    if (window.__demoInitDone) return;
+    window.__demoInitDone = true;

118-126: Minor: remove unused tooltipList variable

It’s scoped only for logging length; no need to predeclare outside the block.

-    let tooltipList = [];
     if (window.bootstrap) {
         const tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
-        tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) {
+        const tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) {
             return new bootstrap.Tooltip(tooltipTriggerEl);
         });
         console.log('✅ Bootstrap tooltips initialized:', tooltipList.length);
website/js/comprehensive-demo.js (6)

888-895: Likewise for summarization: reuse global client and call summarizeText()

Ensures consistent timeout/retry behavior and mock fallback on 401/5xx.

-        // Create API client instance for proper timeout and error handling
-        const apiClient = new SAMOAPIClient();
-        console.log('📝 API Base URL:', apiClient.baseURL);
-        console.log('📝 Summarization endpoint:', apiClient.endpoints.SUMMARIZE);
-        console.log('📝 Full API URL:', `${apiClient.baseURL}${apiClient.endpoints.SUMMARIZE}`);
-
-        const data = await apiClient.makeRequest(apiClient.endpoints.SUMMARIZE, { text: text }, 'POST');
+        const apiClient = window.apiClient || (window.apiClient = new SAMOAPIClient());
+        const data = await apiClient.summarizeText(text);

175-186: Broaden network error detection to retry on “Failed to fetch”

Fetch often throws TypeError: Failed to fetch; current check may skip retry.

-            if ((error.name === 'AbortError' || abortReason === 'timeout' || error.message.includes('timeout') || error.message.includes('network')) && attemptsLeft > 1) {
+            const msg = String(error?.message || '').toLowerCase();
+            if ((error.name === 'AbortError' || abortReason === 'timeout' || msg.includes('timeout') || msg.includes('network') || msg.includes('failed to fetch')) && attemptsLeft > 1) {

77-81: Set Accept header for all requests

Some APIs require explicit Accept header on POST.

         const config = {
             method,
-            headers: {}
+            headers: { 'Accept': 'application/json' }
         };

247-248: Remove unused variable or consistently use it

summaryLength is computed but unused. Simplify.

-        const words = text.split(' ');
-        const summaryLength = Math.max(15, Math.floor(words.length * 0.4));
+        const words = text.split(' ');

Also applies to: 258-264


641-671: Optionally add updateApiKeyButtonStatus helper to sync button UI

demo-initialization.js calls updateApiKeyButtonStatus() if present. Provide it here and export.

 function manageApiKey() {
@@
-        alert('✅ API Key saved successfully');
+        alert('✅ API Key saved successfully');
+        if (typeof updateApiKeyButtonStatus === 'function') updateApiKeyButtonStatus();
@@
     }
 }
+
+// Reflect API key state on the button, if present
+function updateApiKeyButtonStatus() {
+    const btn = document.getElementById('apiKeyBtn');
+    if (!btn) return;
+    const hasKey = !!(sessionStorage.getItem('openai_api_key') || localStorage.getItem('openai_api_key'));
+    btn.textContent = hasKey ? 'Change API Key' : 'Manage API Key';
+    btn.classList.toggle('btn-success', hasKey);
+    btn.classList.toggle('btn-outline-secondary', !hasKey);
+}
+window.updateApiKeyButtonStatus = updateApiKeyButtonStatus;

426-437: Minor: don’t overwrite an existing global client

Avoid replacing an already-created client if scripts re-fire.

-        window.apiClient = new SAMOAPIClient();
-        console.log('✅ Global API client initialized');
+        if (!window.apiClient) {
+            window.apiClient = new SAMOAPIClient();
+            console.log('✅ Global API client initialized');
+        } else {
+            console.log('ℹ️ Global API client already initialized');
+        }
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 0828128 and 93e87ab.

📒 Files selected for processing (2)
  • website/js/comprehensive-demo.js (1 hunks)
  • website/js/demo-initialization.js (1 hunks)

Comment thread website/js/comprehensive-demo.js Outdated
Comment thread website/js/comprehensive-demo.js Outdated
Comment thread website/js/demo-initialization.js
@uelkerd uelkerd self-assigned this Sep 27, 2025
- Combine multiple DOMContentLoaded listeners into single listener for clarity
- Remove redundant setTimeout loading messages (already handled by addToProgressConsole)
- Use global API client instance instead of creating new instances
- Namespace functions under window.SamoDemo to avoid global pollution
- Add user-visible error alerts when core functions are unavailable
demo-initialization.js:
- Reference optional globals via window for module safety
- Avoid enumerating window object for cleaner logging
- Make initialization idempotent to prevent duplicate listeners
- Remove unused tooltipList variable declaration

comprehensive-demo.js:
- Reuse global API client for summarization calls
- Broaden network error detection to include 'Failed to fetch'
- Add Accept header to all API requests
- Remove unused summaryLength variable and inline calculation
- Add updateApiKeyButtonStatus helper function
- Prevent overwriting existing global API client
@uelkerd uelkerd merged commit 0e49d4c into main Sep 27, 2025
12 of 14 checks passed
@uelkerd uelkerd deleted the feat/website-js-integration branch September 27, 2025 21:57
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.

2 participants