diff --git a/.env.example b/.env.example index 41d8a7ebb4319bbd89c16be09fb5936359e14ef4..c56d875694b48331939a8946dc1c8b956fca0e0d 100644 --- a/.env.example +++ b/.env.example @@ -5,10 +5,10 @@ ACCESS_KEYS="" ACCESS_KEY_TIMEOUT_HOURS="24" # The default model ID for WebLLM with F16 shaders. -WEBLLM_DEFAULT_F16_MODEL_ID="Qwen3-0.6B-q4f16_1-MLC" +WEBLLM_DEFAULT_F16_MODEL_ID="Qwen3-1.7B-q4f16_1-MLC" # The default model ID for WebLLM with F32 shaders. -WEBLLM_DEFAULT_F32_MODEL_ID="Qwen3-0.6B-q4f32_1-MLC" +WEBLLM_DEFAULT_F32_MODEL_ID="Qwen3-1.7B-q4f32_1-MLC" # The default model ID for Wllama. WLLAMA_DEFAULT_MODEL_ID="qwen-3-0.6b" diff --git a/.github/CODE_OF_CONDUCT.md b/.github/CODE_OF_CONDUCT.md deleted file mode 100644 index d8b74ecb7d9fc0bb8f7e0d0b1da260ff2938a903..0000000000000000000000000000000000000000 --- a/.github/CODE_OF_CONDUCT.md +++ /dev/null @@ -1,84 +0,0 @@ -# Contributor Code of Conduct - -## Our Pledge - -We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation. - -We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community. - -## Our Standards - -Examples of behavior that contributes to a positive environment for our community include: - -* Demonstrating empathy and kindness toward other people -* Being respectful of differing opinions, viewpoints, and experiences -* Giving and gracefully accepting constructive feedback -* Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience -* Focusing on what is best not just for us as individuals, but for the overall community - -Examples of unacceptable behavior include: - -* The use of sexualized language or imagery, and sexual attention or advances of any kind -* Trolling, insulting or derogatory comments, and personal or political attacks -* Public or private harassment -* Publishing others' private information, such as a physical or email address, without their explicit permission -* Other conduct which could reasonably be considered inappropriate in a professional setting - -## Enforcement Responsibilities - -Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful. - -Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate. - -## Scope - -This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. - -## Enforcement - -Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at: - -- GitHub: [@felladrin](https://github.com/felladrin) -- Email: (private contact can be provided upon request) - -All complaints will be reviewed and investigated promptly and fairly. - -All community leaders are obligated to respect the privacy and security of the reporter of any incident. - -## Enforcement Guidelines - -Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct: - -### 1. Correction - -**Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community. - -**Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested. - -### 2. Warning - -**Community Impact**: A violation through a single incident or series of actions. - -**Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban. - -### 3. Temporary Ban - -**Community Impact**: A serious violation of community standards, including sustained inappropriate behavior. - -**Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban. - -### 4. Permanent Ban - -**Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals. - -**Consequence**: A permanent ban from any sort of public interaction within the community. - -## Attribution - -This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.0, available at https://www.contributor-covenant.org/version/2/0/code_of_conduct.html. - -Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder](https://github.com/mozilla/diversity). - -[homepage]: https://www.contributor-covenant.org - -For answers to common questions about this code of conduct, see https://www.contributor-covenant.org/faq. Translations are available at https://www.contributor-covenant.org/translations. diff --git a/.github/CONTRIBUTING.md b/.github/CONTRIBUTING.md deleted file mode 100644 index 109ab1a04357c17ad77a4e723e81eaf42b56c8e0..0000000000000000000000000000000000000000 --- a/.github/CONTRIBUTING.md +++ /dev/null @@ -1,130 +0,0 @@ -# Contributing to MiniSearch - -First off, thank you for considering contributing to MiniSearch! It's people like you that make MiniSearch such a great tool. - -## How to Contribute - -### Reporting Bugs - -- Use the [GitHub issue tracker](https://github.com/felladrin/MiniSearch/issues) to report bugs -- Check if the issue has already been reported before creating a new one -- Provide clear steps to reproduce the issue -- Include your environment details (OS, browser, Docker version if applicable) -- Add screenshots if the issue is UI-related - -### Suggesting Features - -- Use the [GitHub issue tracker](https://github.com/felladrin/MiniSearch/issues) for feature suggestions -- Clearly describe the feature and why it would be useful -- Consider if it fits with the project's minimalist philosophy -- Provide examples of how you envision the feature working - -### Development Setup - -1. Fork the repository and clone it locally -2. Make sure you have [Docker](https://docs.docker.com/get-docker/) installed -3. Start the development server: - ```bash - docker compose up - ``` -4. The application will be available at http://localhost:7860 -5. Make your changes -6. Test your changes thoroughly -7. Push to your fork and create a pull request - -### Running Tests - -```bash -docker compose exec development-server npm run test -``` - -For coverage: -```bash -docker compose exec development-server npm run test:coverage -``` - -### Code Quality - -Before submitting a pull request, please run: -```bash -docker compose exec development-server npm run lint -``` - -This runs: -- Biome (formatting/linting) -- TypeScript (type checking) -- ts-prune (dead code detection) -- jscpd (copy-paste detection) -- dpdm (circular dependency detection) -- Custom architectural linter - -## Contribution Guidelines - -### Types of Contributions We're Looking For - -- **Bug fixes**: Always welcome! -- **Documentation improvements**: Better docs help everyone -- **Performance optimizations**: Especially for search and AI features -- **UI/UX improvements**: Keeping the minimalist yet intuitive design -- **New AI model integrations**: Following existing patterns -- **Security enhancements**: Following security best practices - -### Project Vision - -MiniSearch aims to be a minimalist, privacy-focused web search application with AI assistance. We prioritize: -- Privacy and security -- Simplicity and ease of use -- Cross-platform compatibility -- Efficient resource usage - -### Getting in Touch - -- For questions about contributions: Use GitHub discussions -- For security issues: See [SECURITY.md](SECURITY.md) -- For general questions: Use GitHub issues - -## Pull Request Process - -1. Fork the repository -2. Create a feature branch (`git checkout -b feature/amazing-feature`) -3. Make your changes -4. Add tests if applicable -5. Ensure all tests pass and linting succeeds -6. Commit your changes (`git commit -m 'Add some amazing feature'`) -7. Push to the branch (`git push origin feature/amazing-feature`) -8. Open a Pull Request - -### Pull Request Guidelines - -- Keep PRs focused on a single feature or fix -- Write clear commit messages -- Update documentation if needed -- Ensure your code follows the existing style -- Be responsive to feedback and reviews - -## Development Commands - -```bash -# Start development server -docker compose up - -# Run tests -docker compose exec development-server npm run test - -# Run linting -docker compose exec development-server npm run lint - -# Build for production -docker compose -f docker-compose.production.yml build - -# View test coverage -docker compose exec development-server npm run test:coverage -``` - -## Questions? - -Don't hesitate to ask questions! We're here to help you contribute successfully. - ---- - -Thanks again for your interest in contributing to MiniSearch! πŸŽ‰ diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md deleted file mode 100644 index a537f6c1f52ff96ab8c44717fa72bcaa1fd05ddc..0000000000000000000000000000000000000000 --- a/.github/ISSUE_TEMPLATE/bug_report.md +++ /dev/null @@ -1,123 +0,0 @@ ---- -name: Bug report -description: Create a report to help us improve -title: "[BUG] " -labels: ["bug"] -assignees: [] -body: - - type: markdown - attributes: - value: | - Thanks for taking the time to fill out this bug report! Please provide as much detail as possible. - - - type: textarea - id: bug-description - attributes: - label: Describe the bug - description: A clear and concise description of what the bug is - placeholder: What happened? What did you expect to happen? - validations: - required: true - - - type: textarea - id: steps-to-reproduce - attributes: - label: Steps to reproduce - description: Please provide detailed steps to reproduce the issue - placeholder: | - 1. Go to '...' - 2. Click on '....' - 3. Scroll down to '....' - 4. See error - validations: - required: true - - - type: textarea - id: expected-behavior - attributes: - label: Expected behavior - description: A clear and concise description of what you expected to happen - validations: - required: true - - - type: textarea - id: screenshots - attributes: - label: Screenshots - description: If applicable, add screenshots to help explain your problem - placeholder: Drag and drop images here or paste them - - - type: dropdown - id: os - attributes: - label: Operating System - description: What operating system are you using? - options: - - Windows 11 - - Windows 10 - - macOS 15.x - - macOS 14.x - - macOS 13.x - - Ubuntu 22.04 - - Ubuntu 20.04 - - Other Linux - - Other - validations: - required: true - - - type: dropdown - id: browser - attributes: - label: Browser - description: What browser are you using? - options: - - Chrome - - Firefox - - Safari - - Edge - - Other - validations: - required: true - - - type: input - id: version - attributes: - label: MiniSearch version - description: What version of MiniSearch are you using? - placeholder: latest, v1.0.0, etc. - validations: - required: true - - - type: input - id: docker-version - attributes: - label: Docker version (if applicable) - description: What Docker version are you using? - placeholder: e.g., 24.0.7 - - - type: textarea - id: additional-context - attributes: - label: Additional context - description: Add any other context about the problem here - - - type: dropdown - id: deployment-type - attributes: - label: Deployment type - description: How are you running MiniSearch? - options: - - Docker image - - Building from source - - Development server - - Other - validations: - required: true - - - type: textarea - id: custom-config - attributes: - label: Custom configuration (if applicable) - description: Any custom configuration you're using - placeholder: Environment variables, custom settings, etc. ---- diff --git a/.github/ISSUE_TEMPLATE/feature_request.md b/.github/ISSUE_TEMPLATE/feature_request.md deleted file mode 100644 index 3c7173ac945df19485fd6743ecc1d20c76e64627..0000000000000000000000000000000000000000 --- a/.github/ISSUE_TEMPLATE/feature_request.md +++ /dev/null @@ -1,73 +0,0 @@ ---- -name: Feature request -description: Suggest an idea for this project -title: "[FEATURE] " -labels: ["enhancement"] -assignees: [] -body: - - type: markdown - attributes: - value: | - Thanks for suggesting a new feature! Please provide as much detail as possible to help us understand your vision. - - - type: textarea - id: problem-description - attributes: - label: Is your feature request related to a problem? - description: A clear and concise description of what the problem is - placeholder: I'm always frustrated when [...] - validations: - required: true - - - type: textarea - id: solution-description - attributes: - label: Describe the solution you'd like - description: A clear and concise description of what you want to happen - validations: - required: true - - - type: textarea - id: alternatives - attributes: - label: Describe alternatives you've considered - description: A clear and concise description of any alternative solutions or features you've considered - - - type: textarea - id: additional-context - attributes: - label: Additional context - description: Add any other context or screenshots about the feature request here - - - type: dropdown - id: alignment - attributes: - label: Alignment with MiniSearch's goals - description: How does this feature align with MiniSearch's minimalist, privacy-focused philosophy? - options: - - "Strongly aligns - enhances privacy/minimalism" - - "Moderately aligns - useful but adds complexity" - - "Needs consideration - potential trade-offs" - - "Not sure - need discussion" - validations: - required: true - - - type: textarea - id: implementation-ideas - attributes: - label: Implementation ideas (optional) - description: Do you have any ideas about how this could be implemented? - placeholder: Technical thoughts, potential approaches, etc. - - - type: dropdown - id: priority - attributes: - label: Priority (your assessment) - description: How important is this feature to you? - options: - - "High - would significantly improve my experience" - - "Medium - nice to have" - - "Low - minor improvement" - validations: - required: true ---- diff --git a/.github/ISSUE_TEMPLATE/security_vulnerability.md b/.github/ISSUE_TEMPLATE/security_vulnerability.md deleted file mode 100644 index e464b0b43e7e8b09b78344df959e01ad3b49fa00..0000000000000000000000000000000000000000 --- a/.github/ISSUE_TEMPLATE/security_vulnerability.md +++ /dev/null @@ -1,98 +0,0 @@ ---- -name: Security Vulnerability -description: Report a security vulnerability (PRIVATE - will be converted to private report) -title: "[SECURITY] " -labels: ["security"] -assignees: [] -body: - - type: markdown - attributes: - value: | - # ⚠️ IMPORTANT: SECURITY VULNERABILITIES SHOULD NOT BE REPORTED PUBLICLY ⚠️ - - This template will create a public issue, but for security vulnerabilities, please use one of these private reporting methods: - - 1. **Preferred**: Use GitHub's [Private Vulnerability Reporting](https://docs.github.com/en/code-security/security-advisories/guidance-on-reporting-and-writing/privately-reporting-a-security-vulnerability) - 2. **Alternative**: Email the maintainer privately - - If you accidentally created a public issue, please close it and report privately instead. - - - type: checkboxes - id: confirmation - attributes: - label: Confirmation - description: Please confirm you understand the security reporting process - options: - - label: I understand this should be reported privately and will use the methods above - required: true - - - type: dropdown - id: vulnerability-type - attributes: - label: Vulnerability Type - description: What type of security vulnerability is this? - options: - - Cross-site Scripting (XSS) - - Authentication/Authorization Bypass - - Information Disclosure - - Remote Code Execution - - Denial of Service - - Configuration Issue - - Other - validations: - required: true - - - type: dropdown - id: severity - attributes: - label: Severity - description: How severe is this vulnerability? - options: - - Critical - - High - - Medium - - Low - validations: - required: true - - - type: textarea - id: description - attributes: - label: Description - description: A clear description of the security vulnerability - validations: - required: true - - - type: textarea - id: steps-to-reproduce - attributes: - label: Steps to Reproduce - description: Detailed steps to reproduce the vulnerability - validations: - required: true - - - type: textarea - id: impact - attributes: - label: Impact - description: Describe the potential impact of this vulnerability - validations: - required: true - - - type: textarea - id: mitigation - attributes: - label: Mitigation (if known) - description: Any known workarounds or mitigations - - - type: textarea - id: additional-information - attributes: - label: Additional Information - description: Any additional context or information about the vulnerability - - - type: markdown - attributes: - value: | - ## 🚨 PLEASE DO NOT SUBMIT THIS PUBLICLY - USE PRIVATE REPORTING METHODS ABOVE 🚨 ---- diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md deleted file mode 100644 index ee5c4672847a3085276032800064fce726cb31b9..0000000000000000000000000000000000000000 --- a/.github/PULL_REQUEST_TEMPLATE.md +++ /dev/null @@ -1,44 +0,0 @@ -## Description -Brief description of what this PR changes. - -## Type of Change -- [ ] Bug fix (non-breaking change that fixes an issue) -- [ ] New feature (non-breaking change that adds functionality) -- [ ] Breaking change (fix or feature that would cause existing functionality to not work as expected) -- [ ] Documentation update -- [ ] Security fix -- [ ] Performance improvement -- [ ] Code quality improvement - -## Testing -- [ ] I have tested this change locally -- [ ] I have added tests for this change -- [ ] All existing tests pass -- [ ] I have run the linter and it passes (`npm run lint`) - -## Checklist -- [ ] My code follows the project's coding conventions -- [ ] I have reviewed my own code -- [ ] I have made corresponding changes to the documentation -- [ ] My changes generate no new warnings -- [ ] I have added tests that prove my fix is effective or that my feature works -- [ ] New and existing unit tests pass locally with my changes -- [ ] Any dependent changes have been merged and published in downstream modules - -## Screenshots (if applicable) -Add screenshots to help explain your changes, especially for UI modifications. - -## Additional Context -Add any other context about the problem here. - -## Security Considerations -- [ ] This change does not introduce any security vulnerabilities -- [ ] I have considered the security implications of this change -- [ ] If this change handles user input, it has been properly sanitized/validated - -## Performance Impact -- [ ] This change does not negatively impact performance -- [ ] I have tested the performance impact of this change - -## Breaking Changes -If this PR introduces breaking changes, please describe them here and how users should migrate. diff --git a/.github/SECURITY.md b/.github/SECURITY.md deleted file mode 100644 index 92f5a23f42e2f6912e119552ab3b12d2ade34103..0000000000000000000000000000000000000000 --- a/.github/SECURITY.md +++ /dev/null @@ -1,135 +0,0 @@ -# Security Policy - -## Supported Versions - -Only the latest version of MiniSearch receives security updates. - -| Version | Supported | -|---------|------------| -| Latest | βœ… | -| Older | ❌ | - -## Reporting a Vulnerability - -### Private Vulnerability Reporting - -We strongly encourage using GitHub's [Private Vulnerability Reporting](https://docs.github.com/en/code-security/security-advisories/guidance-on-reporting-and-writing/privately-reporting-a-security-vulnerability) feature to report security vulnerabilities. - -**Do not report security vulnerabilities through public issues.** - -### How to Report - -1. **Preferred**: Use GitHub's Private Vulnerability Reporting -2. **Alternative**: Email the maintainer privately at: (contact can be provided upon request) - -When reporting a vulnerability, please include: -- A clear description of the vulnerability -- Steps to reproduce the issue -- Potential impact of the vulnerability -- Any suggested mitigations (if known) - -### What to Expect - -- We will acknowledge receipt of your report within 48 hours -- We will provide a detailed response within 7 days -- We will work with you to understand and validate the report -- We will coordinate disclosure timing to minimize user risk - -## Security Scope - -### In Scope - -- Vulnerabilities in the MiniSearch web application -- Security issues in the Docker container configuration -- Authentication and authorization bypasses -- Cross-site scripting (XSS) vulnerabilities -- Information disclosure issues -- Remote code execution vulnerabilities -- Privilege escalation in the application context - -### Out of Scope - -- Issues in third-party dependencies (report to respective projects) -- Vulnerabilities in the underlying browser or Node.js runtime -- Physical attacks on infrastructure -- Social engineering attacks -- Denial of service attacks that don't indicate a vulnerability -- Issues requiring physical access to user devices - -## Threat Model - -### MiniSearch's Security Boundaries - -MiniSearch is designed as a privacy-focused search application with the following security assumptions: - -**Trust Boundaries:** -- **Browser Environment**: The application runs entirely in the user's browser -- **Server Component**: Optional backend for search and AI processing -- **AI Models**: Local or remote AI processing with configurable endpoints - -**Data Flow:** -- User queries are sent to SearXNG instances (configurable) -- AI processing can be local (WebLLM/Wllama) or remote (API endpoints) -- Search history is stored locally in the browser -- No tracking or analytics by default - -**Security Controls:** -- Optional access key protection for deployment -- Configurable AI endpoints for privacy -- Local-first data storage -- No third-party tracking or analytics - -**Potential Risks:** -- Malicious SearXNG instances could log queries -- Remote AI endpoints could access user queries -- Browser extensions could interfere with the application -- Man-in-the-middle attacks without HTTPS - -## Security Best Practices - -### For Users - -- Always use HTTPS when accessing MiniSearch instances -- Configure trusted SearXNG instances -- Use local AI models for maximum privacy -- Set access keys for deployed instances -- Keep browsers updated - -### For Deployers - -- Use the official Docker image -- Configure environment variables securely -- Set up proper access controls -- Use HTTPS in production -- Regularly update dependencies -- Monitor for security advisories - -## Security Features - -- **Access Key Protection**: Optional password-based access control -- **Configurable Endpoints**: Users control search and AI providers -- **Local Processing**: AI models can run entirely in the browser -- **No Tracking**: Built without analytics or tracking -- **HTTPS Ready**: Designed for secure deployment - -## Security Updates - -Security updates will be: -- Released as new versions -- Announced in release notes -- Coordinated with dependency updates when applicable - -## Security Team - -The MiniSearch security team is currently the project maintainer: -- [@felladrin](https://github.com/felladrin) - Project Maintainer - -## Acknowledgments - -We thank security researchers who help us keep MiniSearch secure. All valid security reports will be acknowledged in our release notes (with reporter permission). - -## Related Resources - -- [GitHub Security Advisories](https://docs.github.com/en/code-security/security-advisories) -- [OWASP Web Security Testing Guide](https://owasp.org/www-project-web-security-testing-guide/) -- [Mozilla Security Guidelines](https://infosec.mozilla.org/guidelines) diff --git a/.github/hf-space-config.yml b/.github/hf-space-config.yml deleted file mode 100644 index 6d9d5b00160bb6ad09b8a92ab74ab6cd0a360b3b..0000000000000000000000000000000000000000 --- a/.github/hf-space-config.yml +++ /dev/null @@ -1,11 +0,0 @@ -title: MiniSearch -emoji: πŸ‘ŒπŸ” -colorFrom: yellow -colorTo: yellow -sdk: docker -short_description: Minimalist web-searching app with browser-based AI assistant -pinned: true -custom_headers: - cross-origin-embedder-policy: require-corp - cross-origin-opener-policy: same-origin - cross-origin-resource-policy: cross-origin diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml deleted file mode 100644 index 53e17edab1e210515659c02d92d4d1d768b9740f..0000000000000000000000000000000000000000 --- a/.github/workflows/ci.yml +++ /dev/null @@ -1,33 +0,0 @@ -name: CI - -on: - push: - branches: [main, master] - pull_request: - branches: [main, master] - -jobs: - build-test: - runs-on: ubuntu-latest - - steps: - - name: Checkout repository - uses: actions/checkout@v6 - - - name: Set up Node.js - uses: actions/setup-node@v6 - with: - node-version: lts/* - cache: npm - - - name: Install dependencies - run: npm ci - - - name: Run lint - run: npm run lint - - - name: Check formatting - run: npm run format - - - name: Run tests - run: npm test diff --git a/.github/workflows/deploy-to-hugging-face.yml b/.github/workflows/deploy-to-hugging-face.yml deleted file mode 100644 index 7a5988fc6cc78c2f3b50489d0481ffc754202600..0000000000000000000000000000000000000000 --- a/.github/workflows/deploy-to-hugging-face.yml +++ /dev/null @@ -1,18 +0,0 @@ -name: Deploy to Hugging Face - -on: - workflow_dispatch: - -jobs: - sync-to-hf: - name: Sync to Hugging Face Spaces - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v6 - - uses: JacobLinCool/huggingface-sync@v1 - with: - github: ${{ secrets.GITHUB_TOKEN }} - user: ${{ vars.HF_SPACE_OWNER }} - space: ${{ vars.HF_SPACE_NAME }} - token: ${{ secrets.HF_TOKEN }} - configuration: ".github/hf-space-config.yml" diff --git a/.github/workflows/on-pull-request-to-main.yml b/.github/workflows/on-pull-request-to-main.yml deleted file mode 100644 index 6eae98e615c1c1f2c899a9a5f1d785dd3883ff62..0000000000000000000000000000000000000000 --- a/.github/workflows/on-pull-request-to-main.yml +++ /dev/null @@ -1,9 +0,0 @@ -name: On Pull Request To Main -on: - pull_request: - types: [opened, synchronize, reopened] - branches: ["main"] -jobs: - test-lint-ping: - if: ${{ !contains(github.event.pull_request.labels.*.name, 'skip-test-lint-ping') }} - uses: ./.github/workflows/reusable-test-lint-ping.yml diff --git a/.github/workflows/on-push-to-main.yml b/.github/workflows/on-push-to-main.yml deleted file mode 100644 index 8ce693215c4351bab8b54ccac302345e1202ba03..0000000000000000000000000000000000000000 --- a/.github/workflows/on-push-to-main.yml +++ /dev/null @@ -1,7 +0,0 @@ -name: On Push To Main -on: - push: - branches: ["main"] -jobs: - test-lint-ping: - uses: ./.github/workflows/reusable-test-lint-ping.yml diff --git a/.github/workflows/publish-docker-image.yml b/.github/workflows/publish-docker-image.yml deleted file mode 100644 index 4b9e34829cd96dd1f29d6e82ffe2b3b456771792..0000000000000000000000000000000000000000 --- a/.github/workflows/publish-docker-image.yml +++ /dev/null @@ -1,39 +0,0 @@ -name: Publish Docker Image - -on: - workflow_dispatch: - -jobs: - build-and-push-image: - name: Publish Docker Image to GitHub Packages - runs-on: ubuntu-latest - env: - REGISTRY: ghcr.io - IMAGE_NAME: ${{ github.repository }} - permissions: - contents: read - packages: write - steps: - - name: Checkout repository - uses: actions/checkout@v6 - - name: Log in to the Container registry - uses: docker/login-action@v4 - with: - registry: ${{ env.REGISTRY }} - username: ${{ github.actor }} - password: ${{ secrets.GITHUB_TOKEN }} - - name: Extract metadata (tags, labels) for Docker - id: meta - uses: docker/metadata-action@v6 - with: - images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }} - - name: Set up Docker Buildx - uses: docker/setup-buildx-action@v4 - - name: Build and push Docker Image - uses: docker/build-push-action@v7 - with: - context: . - push: true - tags: ${{ steps.meta.outputs.tags }} - labels: ${{ steps.meta.outputs.labels }} - platforms: linux/amd64,linux/arm64 diff --git a/.github/workflows/reusable-test-lint-ping.yml b/.github/workflows/reusable-test-lint-ping.yml deleted file mode 100644 index 56cb03bfd06cd195c45dc1e5c276125b2bb5e861..0000000000000000000000000000000000000000 --- a/.github/workflows/reusable-test-lint-ping.yml +++ /dev/null @@ -1,25 +0,0 @@ -on: - workflow_call: -jobs: - check-code-quality: - name: Check Code Quality - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v6 - - uses: actions/setup-node@v6 - with: - node-version: "lts/*" - cache: "npm" - - run: npm ci --ignore-scripts - - run: npm run lint - check-docker-container: - needs: [check-code-quality] - name: Check Docker Container - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v6 - - run: docker compose -f docker-compose.production.yml up -d - - name: Check if main page is available - run: until curl -s -o /dev/null -w "%{http_code}" localhost:7860 | grep 200; do sleep 1; done - timeout-minutes: 1 - - run: docker compose -f docker-compose.production.yml down diff --git a/.gitignore b/.gitignore index b3f08f9a965c93dd56cd3f7608b1a31595000fa1..f1b26f1ea73cad18af0078381a02bbc532714a0a 100644 --- a/.gitignore +++ b/.gitignore @@ -5,5 +5,3 @@ node_modules .vscode /vite-build-stats.html .env -/coverage -.playwright-cli diff --git a/.husky/pre-commit b/.husky/pre-commit index 440d481080cb92c40bf4bb436e3c4b3064065026..2312dc587f61186ccf0d627d678d851b9eef7b82 100644 --- a/.husky/pre-commit +++ b/.husky/pre-commit @@ -1,2 +1 @@ -#!/usr/bin/env sh -npm install --no-save @biomejs/biome && npx @biomejs/biome check --write --staged --no-errors-on-unmatched && git diff --name-only --cached | while read -r file; do git add "$file"; done +npx lint-staged diff --git a/Dockerfile b/Dockerfile index 9cede968af905f548a6faee9fc175750fe371a10..bc736b4098848a063a966af24b48a04b93b5f18e 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,6 +1,6 @@ FROM node:lts AS llama-builder -ARG LLAMA_CPP_RELEASE_TAG="b6604" +ARG LLAMA_CPP_RELEASE_TAG="b5595" RUN apt-get update && apt-get install -y \ build-essential \ @@ -55,8 +55,7 @@ RUN cp searx/settings.yml $SEARXNG_SETTINGS_PATH && \ chmod 644 $SEARXNG_SETTINGS_PATH && \ sed -i 's/ultrasecretkey/'$(openssl rand -hex 32)'/g' $SEARXNG_SETTINGS_PATH && \ sed -i 's/- html/- json/' $SEARXNG_SETTINGS_PATH && \ - /usr/local/searxng/searxng-venv/bin/pip install -r requirements.txt && \ - /usr/local/searxng/searxng-venv/bin/pip install --no-build-isolation -e . + /usr/local/searxng/searxng-venv/bin/pip install -e . COPY --from=llama-builder /tmp/llama.cpp/build/bin/llama-server /usr/local/bin/ COPY --from=llama-builder /usr/local/lib/llama/* /usr/local/lib/ @@ -93,4 +92,4 @@ HEALTHCHECK --interval=5m CMD curl -f http://localhost:7860/status || exit 1 ENTRYPOINT [ "/bin/sh", "-c" ] -CMD ["(cd /usr/local/searxng/searxng-src && /usr/local/searxng/searxng-venv/bin/python -m searx.webapp > /dev/null 2>&1) & npm start -- --host"] +CMD ["(cd /usr/local/searxng/searxng-src && /usr/local/searxng/searxng-venv/bin/python -m searx.webapp > /dev/null 2>&1) & (npx pm2 start ecosystem.config.cjs && npx pm2 logs)" ] diff --git a/README.md b/README.md index 4baa14c0e12c3ea44be05fc58d7ef8a9729e4ff4..ac717fad69617c9d3f443a1d035bfea6d574c18e 100644 --- a/README.md +++ b/README.md @@ -64,7 +64,7 @@ docker compose -f docker-compose.production.yml up --build Once the container is running, open http://localhost:7860 in your browser and start searching! -## Frequently asked questions [![Ask DeepWiki](https://deepwiki.com/badge.svg)](https://deepwiki.com/felladrin/MiniSearch) +## Frequently asked questions
How do I search via the browser's address bar? @@ -121,23 +121,7 @@ Once the container is running, open http://localhost:7860 in your browser and st
How can I contribute to the development of this tool? -

We welcome contributions! Please read our Contributing Guidelines for detailed information on how to get started.

-

Quick start:

-
    -
  1. Fork this repository and clone it
  2. -
  3. Start the development server: docker compose up
  4. -
  5. Make your changes and test them
  6. -
  7. Push to your fork and open a pull request
  8. -
-

All contributions are welcome! πŸŽ‰

-
- -
- Where can I find more information? - +

Fork this repository and clone it. Then, start the development server by running the following command:

+

docker compose up

+

Make your changes, push them to your fork, and open a pull request! All contributions are welcome!

diff --git a/agents.md b/agents.md deleted file mode 100644 index 04503fbb31dbbeca08ef2dd385f436b44b1cdb4a..0000000000000000000000000000000000000000 --- a/agents.md +++ /dev/null @@ -1,176 +0,0 @@ -# MiniSearch Agent Guidelines - -This is your navigation hub. Start here, follow the links, and return when you need orientation. - -## Before You Start - -**New to this codebase?** Read in this order: -1. `docs/quick-start.md` - Get it running -2. `docs/overview.md` - Understand the system -3. `docs/project-structure.md` - Navigate the code - -**Making changes?** Check: -- `docs/coding-conventions.md` - Code style -- `docs/development-commands.md` - Available commands -- `docs/pull-requests.md` - How to submit - -## Repository Map - -### Getting Started -- **`docs/quick-start.md`** - Installation, first run, verification -- **`docs/overview.md`** - System architecture and data flow -- **`docs/project-structure.md`** - Directory layout and component organization - -### Configuration & Setup -- **`docs/configuration.md`** - Environment variables and settings reference -- **`docs/security.md`** - Access control, privacy, and security model - -### Core Functionality -- **`docs/ai-integration.md`** - AI inference types (WebLLM, Wllama, OpenAI, AI Horde, Internal) -- **`docs/ui-components.md`** - Component architecture and PubSub patterns -- **`docs/search-history.md`** - History database schema and management -- **`docs/conversation-memory.md`** - Token budgeting and rolling summaries - -### Development -- **`docs/development-commands.md`** - Docker, npm, and testing commands -- **`docs/coding-conventions.md`** - Style guide and patterns -- **`docs/pull-requests.md`** - PR process and merge philosophy -- **`docs/core-technologies.md`** - Technology stack and dependencies -- **`docs/design.md`** - UI/UX design principles - -## Agent Decision Tree - -``` -Need to: -β”œβ”€β”€ Add a feature? -β”‚ β”œβ”€β”€ UI component β†’ docs/ui-components.md -β”‚ β”œβ”€β”€ AI integration β†’ docs/ai-integration.md -β”‚ β”œβ”€β”€ Search functionality β†’ client/modules/search.ts -β”‚ └── Settings option β†’ docs/configuration.md -β”œβ”€β”€ Fix a bug? -β”‚ β”œβ”€β”€ UI issue β†’ Check component + PubSub channels -β”‚ β”œβ”€β”€ AI not working β†’ docs/ai-integration.md + browser console -β”‚ β”œβ”€β”€ Search failing β†’ Check SearXNG + server hooks -β”‚ └── Build error β†’ docs/development-commands.md -β”œβ”€β”€ Configure deployment? -β”‚ β”œβ”€β”€ Environment variables β†’ docs/configuration.md -β”‚ β”œβ”€β”€ Access control β†’ docs/security.md -β”‚ └── Docker setup β†’ docs/overview.md -└── Understand data flow? - β”œβ”€β”€ Search flow β†’ client/modules/search.ts - β”œβ”€β”€ AI generation β†’ client/modules/textGeneration.ts - β”œβ”€β”€ State management β†’ docs/ui-components.md - └── History/Chat β†’ docs/search-history.md + docs/conversation-memory.md -``` - -## Key Files Reference - -### Entry Points -- `client/index.tsx` - React app initialization -- `vite.config.ts` - Vite dev server with hooks -- `Dockerfile` - Multi-stage container build - -### Business Logic Modules -- `client/modules/search.ts` - Search orchestration and caching -- `client/modules/textGeneration.ts` - AI response flow -- `client/modules/pubSub.ts` - All PubSub channels -- `client/modules/settings.ts` - Settings management -- `client/modules/history.ts` - Search history database - -### Server-Side Modules -- `server/searchEndpointServerHook.ts` - `/search` endpoints -- `server/internalApiEndpointServerHook.ts` - `/inference` proxy -- `server/webSearchService.ts` - SearXNG integration -- `server/rerankerService.ts` - Local result reranking - -### Key Components -- `client/components/App/` - Application shell -- `client/components/Search/Form/` - Search input -- `client/components/Search/Results/` - Results display -- `client/components/AiResponse/` - AI response + chat -- `client/components/Pages/Main/Menu/` - Settings drawers -- `client/modules/webGpu.ts` - Detects WebGPU availability and F16 shader support for WebLLM -- `client/modules/querySuggestions.ts` - Provides search suggestion UI, stored in IndexedDB -- `client/modules/relatedSearchQuery.ts` - Generates related search queries -- `client/modules/followUpQuestions.ts` - Generates suggested follow-up questions, uses `followUpQuestionPubSub` -- `client/modules/accessKey.ts` - Validates and stores access keys, uses `accessKeyValidatedPubSub` -- `client/modules/parentWindow.ts` - PostMessage API for embedding in parent windows -- `client/hooks/` - Reusable React hooks -- `server/searchToken.ts` - Generates CSRF protection tokens for search requests -- `server/downloadFileFromHuggingFaceRepository.ts` - Downloads GGUF models from HuggingFace using `@huggingface/hub` package - -## Common Tasks Quick Reference - -### Add a new AI model -1. Add to `client/modules/wllama.ts` or WebLLM registry -2. Update `docs/ai-integration.md` -3. Update `docs/configuration.md` defaults - -### Add a new setting -1. Add to `client/modules/settings.ts` default object -2. Add UI in `client/components/Pages/Main/Menu/` -3. Update `docs/configuration.md` settings table - -### Modify search behavior -1. Edit `client/modules/search.ts` -2. Update `server/webSearchService.ts` if server-side changes needed -3. Check `server/rerankerService.ts` if reranking affected - -### Fix UI state issues -1. Check PubSub channels in `client/modules/pubSub.ts` -2. Verify component subscriptions in `docs/ui-components.md` -3. Ensure proper state updates in business logic modules - -### Analyze test coverage -1. Run `npm run test:coverage` to generate reports -2. Check `coverage/coverage-summary.json` for quick metrics -3. See `docs/development-commands.md` for full coverage analysis guide - -## Quality Gates - -Before any change: -```bash -docker compose exec development-server npm run lint -``` - -This runs: -- Biome (formatting/linting) -- TypeScript (type checking) -- ts-prune (dead code detection) -- jscpd (copy-paste detection) -- dpdm (circular dependency detection) -- Custom architectural linter - -## Agent-First Principles - -**Repository as System of Record:** -- All knowledge lives in versioned docs/ structure -- This file is your entry point - start here -- Follow links, don't assume - verify in code - -**Context Efficiency:** -- Use this map to navigate quickly -- Return to this file when context drifts -- Follow the decision tree for common tasks - -**Architecture & Boundaries:** -- Respect PubSub boundaries - don't cross concerns -- Client vs server - keep them separate -- Feature-based organization - one folder per feature - -**Documentation Maintenance:** -- Update these docs when you learn something new -- Add cross-references when linking concepts -- Keep examples current with actual code - -## Technology Stack - -React + TypeScript + Mantine UI v8, with privacy-first architecture. -See `docs/core-technologies.md` for complete dependency list and selection criteria. - -## Need Help? - -1. Check relevant doc in `docs/` -2. Read the module code in `client/modules/` or `server/` -3. Look at similar existing implementations -4. Run `npm run lint` to validate changes diff --git a/biome.json b/biome.json index dbdd0b33769e0e57f2164a86835a24b19f7bd505..b5afc2926ca9cd15a6face957349605f13f8a6a5 100644 --- a/biome.json +++ b/biome.json @@ -1,9 +1,9 @@ { "$schema": "https://biomejs.dev/schemas/latest/schema.json", "vcs": { - "enabled": true, + "enabled": false, "clientKind": "git", - "useIgnoreFile": true + "useIgnoreFile": false }, "files": { "ignoreUnknown": false diff --git a/client/components/AiResponse/AiModelDownloadAllowanceContent.tsx b/client/components/AiResponse/AiModelDownloadAllowanceContent.tsx index 48fbb9ce81045bc0cd3ba2e5f99b66cfb7e30c5c..227cec2d8152fb4ddcb9a4e91e4c8e3034b0feba 100644 --- a/client/components/AiResponse/AiModelDownloadAllowanceContent.tsx +++ b/client/components/AiResponse/AiModelDownloadAllowanceContent.tsx @@ -2,8 +2,8 @@ import { Alert, Button, Group, Text } from "@mantine/core"; import { IconCheck, IconInfoCircle, IconX } from "@tabler/icons-react"; import { usePubSub } from "create-pubsub/react"; import { useState } from "react"; -import { addLogEntry } from "@/modules/logEntries"; -import { settingsPubSub } from "@/modules/pubSub"; +import { addLogEntry } from "../../modules/logEntries"; +import { settingsPubSub } from "../../modules/pubSub"; export default function AiModelDownloadAllowanceContent() { const [settings, setSettings] = usePubSub(settingsPubSub); diff --git a/client/components/AiResponse/AiResponseContent.tsx b/client/components/AiResponse/AiResponseContent.tsx index e0805a44314e74b1665d93f6249baaa10a27644a..af7e85daeb7990016d0613d923600b7c246fac7f 100644 --- a/client/components/AiResponse/AiResponseContent.tsx +++ b/client/components/AiResponse/AiResponseContent.tsx @@ -20,9 +20,9 @@ import { import type { PublishFunction } from "create-pubsub"; import { usePubSub } from "create-pubsub/react"; import { type ReactNode, useMemo, useState } from "react"; -import { addLogEntry } from "@/modules/logEntries"; -import { settingsPubSub } from "@/modules/pubSub"; -import { searchAndRespond } from "@/modules/textGeneration"; +import { addLogEntry } from "../../modules/logEntries"; +import { settingsPubSub } from "../../modules/pubSub"; +import { searchAndRespond } from "../../modules/textGeneration"; import CopyIconButton from "./CopyIconButton"; import FormattedMarkdown from "./FormattedMarkdown"; @@ -51,12 +51,7 @@ export default function AiResponseContent({ () => ({ children }: { children: ReactNode }) => { return settings.enableAiResponseScrolling ? ( - + {children} ) : ( diff --git a/client/components/AiResponse/AiResponseSection.tsx b/client/components/AiResponse/AiResponseSection.tsx index 3b4dc3db5bc63b63729d801dbb33826c790c34ae..e4b96743c62c369b282ba08256d33848446a30f5 100644 --- a/client/components/AiResponse/AiResponseSection.tsx +++ b/client/components/AiResponse/AiResponseSection.tsx @@ -2,16 +2,14 @@ import { CodeHighlightAdapterProvider } from "@mantine/code-highlight"; import { usePubSub } from "create-pubsub/react"; import { useMemo } from "react"; import { - chatMessagesPubSub, - isRestoringFromHistoryPubSub, modelLoadingProgressPubSub, modelSizeInMegabytesPubSub, queryPubSub, responsePubSub, settingsPubSub, textGenerationStatePubSub, -} from "@/modules/pubSub"; -import { shikiAdapter } from "@/modules/shiki"; +} from "../../modules/pubSub"; +import { shikiAdapter } from "../../modules/shiki"; import "@mantine/code-highlight/styles.css"; import AiModelDownloadAllowanceContent from "./AiModelDownloadAllowanceContent"; import AiResponseContent from "./AiResponseContent"; @@ -28,8 +26,6 @@ export default function AiResponseSection() { const [modelLoadingProgress] = usePubSub(modelLoadingProgressPubSub); const [settings] = usePubSub(settingsPubSub); const [modelSizeInMegabytes] = usePubSub(modelSizeInMegabytesPubSub); - const [chatMessages] = usePubSub(chatMessagesPubSub); - const [isRestoringFromHistory] = usePubSub(isRestoringFromHistoryPubSub); return useMemo(() => { if (!settings.enableAiResponse || textGenerationState === "idle") { @@ -52,14 +48,7 @@ export default function AiResponseSection() { /> {textGenerationState === "completed" && ( - 0 ? chatMessages : undefined - } - suppressInitialFollowUp={isRestoringFromHistory} - /> + )} ); @@ -92,10 +81,8 @@ export default function AiResponseSection() { textGenerationState, response, query, - chatMessages, modelLoadingProgress, modelSizeInMegabytes, setTextGenerationState, - isRestoringFromHistory, ]); } diff --git a/client/components/AiResponse/ChatHeader.tsx b/client/components/AiResponse/ChatHeader.tsx index f62bc98185cb401cd8db79b7f2368ad9c1ef42a5..4f1564976554881ed71921438afc5d8c5b1a631a 100644 --- a/client/components/AiResponse/ChatHeader.tsx +++ b/client/components/AiResponse/ChatHeader.tsx @@ -1,5 +1,5 @@ import { Group, Text } from "@mantine/core"; -import type { ChatMessage } from "@/modules/types"; +import type { ChatMessage } from "gpt-tokenizer/GptEncoding"; import CopyIconButton from "./CopyIconButton"; interface ChatHeaderProps { diff --git a/client/components/AiResponse/ChatInputArea.tsx b/client/components/AiResponse/ChatInputArea.tsx index 25ff4e20ce45e529ceb708d9e56dbc70e1b81d1b..e5fbc455e32772b4ccf6b56e5cdaea5052b34c10 100644 --- a/client/components/AiResponse/ChatInputArea.tsx +++ b/client/components/AiResponse/ChatInputArea.tsx @@ -5,9 +5,7 @@ import { chatGenerationStatePubSub, chatInputPubSub, followUpQuestionPubSub, - isRestoringFromHistoryPubSub, - suppressNextFollowUpPubSub, -} from "@/modules/pubSub"; +} from "../../modules/pubSub"; interface ChatInputAreaProps { onKeyDown: (event: React.KeyboardEvent) => void; @@ -18,18 +16,13 @@ function ChatInputArea({ onKeyDown, handleSend }: ChatInputAreaProps) { const [input, setInput] = usePubSub(chatInputPubSub); const [generationState] = usePubSub(chatGenerationStatePubSub); const [followUpQuestion] = usePubSub(followUpQuestionPubSub); - const [isRestoringFromHistory] = usePubSub(isRestoringFromHistoryPubSub); - const [suppressNextFollowUp] = usePubSub(suppressNextFollowUpPubSub); const isGenerating = generationState.isGeneratingResponse && !generationState.isGeneratingFollowUpQuestion; - const defaultPlaceholder = "Anything else you would like to know?"; const placeholder = - isRestoringFromHistory || suppressNextFollowUp - ? defaultPlaceholder - : followUpQuestion || defaultPlaceholder; + followUpQuestion || "Anything else you would like to know?"; const onChange = (event: React.ChangeEvent) => { setInput(event.target.value); @@ -37,12 +30,7 @@ function ChatInputArea({ onKeyDown, handleSend }: ChatInputAreaProps) { const handleKeyDownWithPlaceholder = ( event: React.KeyboardEvent, ) => { - if ( - input.trim() === "" && - followUpQuestion && - !isRestoringFromHistory && - !suppressNextFollowUp - ) { + if (input.trim() === "" && followUpQuestion) { if (event.key === "Enter" && !event.shiftKey) { event.preventDefault(); handleSend(followUpQuestion); @@ -54,12 +42,7 @@ function ChatInputArea({ onKeyDown, handleSend }: ChatInputAreaProps) { }; const handleSendWithPlaceholder = () => { - if ( - input.trim() === "" && - followUpQuestion && - !isRestoringFromHistory && - !suppressNextFollowUp - ) { + if (input.trim() === "" && followUpQuestion) { handleSend(followUpQuestion); } else { handleSend(); @@ -77,7 +60,7 @@ function ChatInputArea({ onKeyDown, handleSend }: ChatInputAreaProps) { onKeyDown={handleKeyDownWithPlaceholder} autosize minRows={1} - maxRows={8} + maxRows={4} style={{ flexGrow: 1, paddingRight: "50px" }} disabled={isGenerating} /> diff --git a/client/components/AiResponse/ChatInterface.tsx b/client/components/AiResponse/ChatInterface.tsx index 4610b0b01b5da9412dc9762e4d04762a61a36142..0699b24f0e6215132c3afd653c3c9ed0f45623eb 100644 --- a/client/components/AiResponse/ChatInterface.tsx +++ b/client/components/AiResponse/ChatInterface.tsx @@ -1,39 +1,25 @@ import { Card, Stack } from "@mantine/core"; import { usePubSub } from "create-pubsub/react"; -import { - type KeyboardEvent, - useCallback, - useEffect, - useRef, - useState, -} from "react"; +import type { ChatMessage } from "gpt-tokenizer/GptEncoding"; +import { type KeyboardEvent, useCallback, useEffect, useState } from "react"; import throttle from "throttleit"; -import { generateFollowUpQuestion } from "@/modules/followUpQuestions"; -import { - getCurrentSearchRunId, - saveChatMessageForQuery, - updateSearchResults, -} from "@/modules/history"; -import { handleEnterKeyDown } from "@/modules/keyboard"; -import { addLogEntry } from "@/modules/logEntries"; +import { generateFollowUpQuestion } from "../../modules/followUpQuestions"; +import { handleEnterKeyDown } from "../../modules/keyboard"; +import { addLogEntry } from "../../modules/logEntries"; import { chatGenerationStatePubSub, chatInputPubSub, followUpQuestionPubSub, - getSettings, - imageSearchResultsPubSub, - queryPubSub, + getImageSearchResults, + getTextSearchResults, settingsPubSub, - suppressNextFollowUpPubSub, - textSearchResultsPubSub, updateImageSearchResults, updateLlmTextSearchResults, updateTextSearchResults, -} from "@/modules/pubSub"; -import { generateRelatedSearchQuery } from "@/modules/relatedSearchQuery"; -import { searchImages, searchText } from "@/modules/search"; -import { generateChatResponse } from "@/modules/textGeneration"; -import type { ChatMessage } from "@/modules/types"; +} from "../../modules/pubSub"; +import { generateRelatedSearchQuery } from "../../modules/relatedSearchQuery"; +import { searchImages, searchText } from "../../modules/search"; +import { generateChatResponse } from "../../modules/textGeneration"; import ChatHeader from "./ChatHeader"; import ChatInputArea from "./ChatInputArea"; import MessageList from "./MessageList"; @@ -41,45 +27,23 @@ import MessageList from "./MessageList"; interface ChatInterfaceProps { initialQuery?: string; initialResponse?: string; - initialMessages?: ChatMessage[]; - suppressInitialFollowUp?: boolean; } export default function ChatInterface({ initialQuery, initialResponse, - initialMessages, - suppressInitialFollowUp, }: ChatInterfaceProps) { - const initialMessagesArray = - initialMessages && - initialMessages.length > 0 && - initialQuery && - initialResponse - ? [ - { role: "user" as const, content: initialQuery }, - { role: "assistant" as const, content: initialResponse }, - ...initialMessages, - ] - : initialMessages || []; - - const [messages, setMessages] = useState(initialMessagesArray); + const [messages, setMessages] = useState([]); const [input, setInput] = usePubSub(chatInputPubSub); const [generationState, setGenerationState] = usePubSub( chatGenerationStatePubSub, ); const [, setFollowUpQuestion] = usePubSub(followUpQuestionPubSub); - const [textSearchResults] = usePubSub(textSearchResultsPubSub); - const [imageSearchResults] = usePubSub(imageSearchResultsPubSub); - const [currentQuery] = usePubSub(queryPubSub); - const [suppressNextFollowUp] = usePubSub(suppressNextFollowUpPubSub); const [previousFollowUpQuestions, setPreviousFollowUpQuestions] = useState< string[] >([]); const [settings] = usePubSub(settingsPubSub); const [streamedResponse, setStreamedResponse] = useState(""); - const hasInitialized = useRef(false); - const prevInitialMessagesRef = useRef(undefined); const updateStreamedResponse = useCallback( throttle((response: string) => { setStreamedResponse(response); @@ -89,7 +53,6 @@ export default function ChatInterface({ const regenerateFollowUpQuestion = useCallback( async (currentQuery: string, currentResponse: string) => { - if (suppressNextFollowUp) return; if (!currentResponse || !currentQuery.trim()) return; try { @@ -120,298 +83,138 @@ export default function ChatInterface({ }); } }, - [ - setFollowUpQuestion, - setGenerationState, - previousFollowUpQuestions, - suppressNextFollowUp, - ], + [setFollowUpQuestion, setGenerationState, previousFollowUpQuestions], ); useEffect(() => { - const messagesChanged = - !prevInitialMessagesRef.current || - JSON.stringify(prevInitialMessagesRef.current) !== - JSON.stringify(initialMessages); - - if (!messagesChanged) return; - - prevInitialMessagesRef.current = initialMessages; - - const newInitialMessagesArray = - initialMessages && - initialMessages.length > 0 && - initialQuery && - initialResponse - ? [ - { role: "user" as const, content: initialQuery }, - { role: "assistant" as const, content: initialResponse }, - ...initialMessages, - ] - : initialMessages || []; - - if (newInitialMessagesArray.length > 0) { - setMessages(newInitialMessagesArray); - } else if (initialQuery && initialResponse) { + if (messages.length === 0 && initialQuery && initialResponse) { setMessages([ { role: "user", content: initialQuery }, { role: "assistant", content: initialResponse }, ]); - } - }, [initialQuery, initialResponse, initialMessages]); - - useEffect(() => { - if (suppressNextFollowUp) { - hasInitialized.current = true; - return; - } - if (suppressInitialFollowUp) return; - if (hasInitialized.current) return; - - if (initialMessages && initialMessages.length > 0) { - const lastAssistant = messages - .filter((m) => m.role === "assistant") - .pop(); - const lastUser = messages.filter((m) => m.role === "user").pop(); - if (lastUser && lastAssistant) { - regenerateFollowUpQuestion(lastUser.content, lastAssistant.content); - hasInitialized.current = true; - } - } else if (messages.length >= 2 && initialQuery && initialResponse) { regenerateFollowUpQuestion(initialQuery, initialResponse); - hasInitialized.current = true; } }, [ initialQuery, initialResponse, - initialMessages, - messages, + messages.length, regenerateFollowUpQuestion, - suppressInitialFollowUp, - suppressNextFollowUp, ]); - useEffect(() => { - return () => { - setFollowUpQuestion(""); - setPreviousFollowUpQuestions([]); - }; - }, [setFollowUpQuestion]); - - const handleEditMessage = useCallback( - (absoluteIndex: number) => { - const target = messages[absoluteIndex]; - if (!target || target.role !== "user") return; - setInput(target.content); - setMessages(messages.slice(0, absoluteIndex)); - setFollowUpQuestion(""); - }, - [messages, setInput, setFollowUpQuestion], - ); - - const handleRegenerateResponse = useCallback(async () => { - if ( - generationState.isGeneratingResponse || - messages.length < 3 || - messages[messages.length - 1].role !== "assistant" - ) + const handleSend = async (textToSend?: string) => { + const currentInput = textToSend ?? input; + if (currentInput.trim() === "" || generationState.isGeneratingResponse) return; - const history = messages.slice(0, -1); - const lastUser = history[history.length - 1]; + const userMessage: ChatMessage = { role: "user", content: currentInput }; + const newMessages: ChatMessage[] = [...messages, userMessage]; - setMessages(history); - setGenerationState({ ...generationState, isGeneratingResponse: true }); + if (messages.length === 0) { + setPreviousFollowUpQuestions([]); + } + + setMessages(newMessages); + setInput(textToSend ? input : ""); + setGenerationState({ + ...generationState, + isGeneratingResponse: true, + }); setFollowUpQuestion(""); setStreamedResponse(""); try { - const finalResponse = await generateChatResponse( - history, - updateStreamedResponse, - ); + const relatedQuery = await generateRelatedSearchQuery([...newMessages]); + const searchQuery = relatedQuery || currentInput; - setMessages((prev) => [ - ...prev, - { role: "assistant", content: finalResponse }, - ]); - - addLogEntry("AI response re-generated"); - - if (lastUser?.role === "user") { - await regenerateFollowUpQuestion(lastUser.content, finalResponse); - } - } catch (error) { - addLogEntry(`Error re-generating response: ${error}`); - } finally { - setGenerationState({ ...generationState, isGeneratingResponse: false }); - } - }, [ - generationState, - messages, - regenerateFollowUpQuestion, - setFollowUpQuestion, - setGenerationState, - updateStreamedResponse, - ]); - - const handleSend = useCallback( - async (textToSend?: string) => { - const currentInput = textToSend ?? input; - if (currentInput.trim() === "" || generationState.isGeneratingResponse) - return; - - const userMessage: ChatMessage = { role: "user", content: currentInput }; - const newMessages: ChatMessage[] = [...messages, userMessage]; - - setMessages(newMessages); - if (!textToSend) setInput(""); - setGenerationState({ - ...generationState, - isGeneratingResponse: true, - }); - setFollowUpQuestion(""); - setStreamedResponse(""); - - try { - const relatedQuery = await generateRelatedSearchQuery([...newMessages]); - const searchQuery = relatedQuery || currentInput; + if (settings.enableTextSearch) { + const freshResults = await searchText( + searchQuery, + settings.searchResultsLimit, + ); - if (settings.enableTextSearch) { - const freshResults = await searchText( - searchQuery, - settings.searchResultsLimit, + if (freshResults.length > 0) { + const existingUrls = new Set( + getTextSearchResults().map(([, , url]) => url), ); - if (freshResults.length > 0) { - const existingUrls = new Set( - textSearchResults.map(([, , url]) => url), - ); - - const uniqueFreshResults = freshResults.filter( - ([, , url]) => !existingUrls.has(url), - ); + const uniqueFreshResults = freshResults.filter( + ([, , url]) => !existingUrls.has(url), + ); + if (uniqueFreshResults.length > 0) { + updateTextSearchResults([ + ...getTextSearchResults(), + ...uniqueFreshResults, + ]); updateLlmTextSearchResults( - freshResults.slice(0, getSettings().searchResultsToConsider), + uniqueFreshResults.slice(0, settings.searchResultsToConsider), ); - - if (uniqueFreshResults.length > 0) { - const updatedResults = [ - ...textSearchResults, - ...uniqueFreshResults, - ]; - updateTextSearchResults(updatedResults); - - updateSearchResults(getCurrentSearchRunId(), { - type: "text", - items: updatedResults.map(([title, snippet, url]) => ({ - title, - url, - snippet, - })), - }); - } } } + } - if (settings.enableImageSearch) { - searchImages(searchQuery, settings.searchResultsLimit) - .then((imageResults) => { - if (imageResults.length > 0) { - const existingUrls = new Set( - imageSearchResults.map(([, url]) => url), - ); - - const uniqueFreshResults = imageResults.filter( - ([, url]) => !existingUrls.has(url), - ); - - if (uniqueFreshResults.length > 0) { - const updatedImageResults = [ - ...uniqueFreshResults, - ...imageSearchResults, - ]; - updateImageSearchResults(updatedImageResults); - - updateSearchResults(getCurrentSearchRunId(), { - type: "image", - items: updatedImageResults.map( - ([title, url, thumbnailUrl, sourceUrl]) => ({ - title, - url, - thumbnail: thumbnailUrl, - sourceUrl, - }), - ), - }); - } + if (settings.enableImageSearch) { + searchImages(searchQuery, settings.searchResultsLimit) + .then((imageResults) => { + if (imageResults.length > 0) { + const existingUrls = new Set( + getImageSearchResults().map(([, url]) => url), + ); + + const uniqueFreshResults = imageResults.filter( + ([, url]) => !existingUrls.has(url), + ); + + if (uniqueFreshResults.length > 0) { + updateImageSearchResults([ + ...uniqueFreshResults, + ...getImageSearchResults(), + ]); } - }) - .catch((error) => { - addLogEntry(`Error in follow-up image search: ${error}`); - }); - } - } catch (error) { - addLogEntry(`Error in follow-up search: ${error}`); + } + }) + .catch((error) => { + addLogEntry(`Error in follow-up image search: ${error}`); + }); } + } catch (error) { + addLogEntry(`Error in follow-up search: ${error}`); + } - try { - const finalResponse = await generateChatResponse( - newMessages, - updateStreamedResponse, - ); - - setMessages((prevMessages) => [ - ...prevMessages, - { role: "assistant", content: finalResponse }, - ]); + try { + const finalResponse = await generateChatResponse( + newMessages, + updateStreamedResponse, + ); - addLogEntry("AI response completed"); + setMessages((prevMessages) => [ + ...prevMessages, + { role: "assistant", content: finalResponse }, + ]); - await saveChatMessageForQuery(currentQuery, "user", currentInput); - await saveChatMessageForQuery(currentQuery, "assistant", finalResponse); + addLogEntry("AI response completed"); - await regenerateFollowUpQuestion(currentInput, finalResponse); - } catch (error) { - addLogEntry(`Error in chat response: ${error}`); - setMessages((prevMessages) => [ - ...prevMessages, - { - role: "assistant", - content: - "Sorry, I encountered an error while generating a response.", - }, - ]); - } finally { - setGenerationState({ - ...generationState, - isGeneratingResponse: false, - }); - } - }, - [ - generationState, - messages, - settings, - input, - regenerateFollowUpQuestion, - setFollowUpQuestion, - setGenerationState, - setInput, - updateStreamedResponse, - currentQuery, - textSearchResults, - imageSearchResults, - ], - ); + await regenerateFollowUpQuestion(currentInput, finalResponse); + } catch (error) { + addLogEntry(`Error in chat response: ${error}`); + setMessages((prevMessages) => [ + ...prevMessages, + { + role: "assistant", + content: "Sorry, I encountered an error while generating a response.", + }, + ]); + } finally { + setGenerationState({ + ...generationState, + isGeneratingResponse: false, + }); + } + }; - const handleKeyDown = useCallback( - (event: KeyboardEvent) => { - handleEnterKeyDown(event, settings, handleSend); - }, - [settings, handleSend], - ); + const handleKeyDown = (event: KeyboardEvent) => { + handleEnterKeyDown(event, settings, handleSend); + }; return ( @@ -425,9 +228,6 @@ export default function ChatInterface({ ? [...messages, { role: "assistant", content: streamedResponse }] : messages } - onEditMessage={handleEditMessage} - onRegenerate={handleRegenerateResponse} - isGenerating={generationState.isGeneratingResponse} /> diff --git a/client/components/AiResponse/EnableAiResponsePrompt.tsx b/client/components/AiResponse/EnableAiResponsePrompt.tsx index 07fad1766668effd48db99fb0280a4fbd7eaf794..1511af02b15e07b1345a6b9f99d6bee84114b054 100644 --- a/client/components/AiResponse/EnableAiResponsePrompt.tsx +++ b/client/components/AiResponse/EnableAiResponsePrompt.tsx @@ -2,7 +2,7 @@ import { ActionIcon, Alert, Button, - Grid, + Flex, Group, Popover, Stack, @@ -39,47 +39,42 @@ export default function EnableAiResponsePrompt({ return ( - - - - Enable AI Responses? - - - - - - - {helpContent} - - - - - - - - - - + + Enable AI Responses? + + + + + + + {helpContent} + +
+ + + + + ); } diff --git a/client/components/AiResponse/FormattedMarkdown.tsx b/client/components/AiResponse/FormattedMarkdown.tsx index 5fcdb58c6972dd63d17431f3c9ccdd778e7ee1e5..47c13489c5850832d585b90878eeab2005d689a4 100644 --- a/client/components/AiResponse/FormattedMarkdown.tsx +++ b/client/components/AiResponse/FormattedMarkdown.tsx @@ -17,7 +17,7 @@ export default function FormattedMarkdown({ const { reasoningContent, mainContent, isGenerating } = useReasoningContent(children); - if (!children && !reasoningContent) { + if (!children) { return null; } diff --git a/client/components/AiResponse/MarkdownRenderer.tsx b/client/components/AiResponse/MarkdownRenderer.tsx index b0ec794c66ce188ac28a8c019aa37ac7231e5871..8c84f70b9dee45cec9053800c7ba363dd4d44b84 100644 --- a/client/components/AiResponse/MarkdownRenderer.tsx +++ b/client/components/AiResponse/MarkdownRenderer.tsx @@ -1,5 +1,5 @@ import { CodeHighlight } from "@mantine/code-highlight"; -import { Blockquote, Box, Code, Divider, Text } from "@mantine/core"; +import { Box, Code, Divider } from "@mantine/core"; import React from "react"; import { ErrorBoundary } from "react-error-boundary"; import Markdown from "react-markdown"; @@ -22,15 +22,6 @@ export default function MarkdownRenderer({ return null; } - const unwrapParagraphs = (children: React.ReactNode) => { - return React.Children.map(children, (child) => { - if (React.isValidElement(child) && child.type === "p") { - return (child.props as { children: React.ReactNode }).children; - } - return child; - }); - }; - return ( {unwrapParagraphs(children)}; + const processedChildren = React.Children.map(children, (child) => { + if (React.isValidElement(child) && child.type === "p") { + return (child.props as { children: React.ReactNode }).children; + } + return child; + }); + return
  • {processedChildren}
  • ; }, hr() { return ; @@ -58,14 +55,6 @@ export default function MarkdownRenderer({ pre(props) { return <>{props.children}; }, - blockquote(props) { - const { children } = props; - return ( -
    - {unwrapParagraphs(children)} -
    - ); - }, code(props) { const { children, className, node } = props; const codeContent = children?.toString().replace(/\n$/, "") ?? ""; diff --git a/client/components/AiResponse/MessageList.tsx b/client/components/AiResponse/MessageList.tsx index 1b23440401e76659b1aef0fd7f3de2f2eab164db..de22df033f15d9ca3e33ca25eb004ea5bb03b450 100644 --- a/client/components/AiResponse/MessageList.tsx +++ b/client/components/AiResponse/MessageList.tsx @@ -1,101 +1,43 @@ -import { ActionIcon, Group, Paper, Stack, Tooltip } from "@mantine/core"; -import { IconPencil, IconRefresh } from "@tabler/icons-react"; +import { Paper, Stack } from "@mantine/core"; +import type { ChatMessage } from "gpt-tokenizer/GptEncoding"; import { memo } from "react"; -import type { ChatMessage } from "@/modules/types"; import FormattedMarkdown from "./FormattedMarkdown"; interface MessageListProps { messages: ChatMessage[]; - onEditMessage: (absoluteIndex: number) => void; - onRegenerate: () => void; - isGenerating: boolean; } interface MessageProps { message: ChatMessage; index: number; - absoluteIndex: number; - isLastAssistant: boolean; - isGenerating: boolean; - onEditMessage: (absoluteIndex: number) => void; - onRegenerate: () => void; } const Message = memo( - ({ - message, - index, - absoluteIndex, - isLastAssistant, - isGenerating, - onEditMessage, - onRegenerate, - }: MessageProps) => { - const canEdit = message.role === "user"; - const canRegenerate = isLastAssistant && message.role === "assistant"; - const iconSize = 16; - const iconVariant: "subtle" = "subtle"; - + function Message({ message, index }: MessageProps) { return ( - - {canEdit && ( - - onEditMessage(absoluteIndex)} - > - - - - )} - - - {message.content} - - - {canRegenerate && ( - - onRegenerate()} - > - - - - )} - + {message.content} + + ); + }, + (prevProps, nextProps) => { + return ( + prevProps.message.content === nextProps.message.content && + prevProps.message.role === nextProps.message.role ); }, ); -const MessageList = memo(function MessageList({ - messages, - onEditMessage, - onRegenerate, - isGenerating, -}: MessageListProps) { +const MessageList = memo(function MessageList({ messages }: MessageListProps) { if (messages.length <= 2) return null; return ( @@ -103,24 +45,13 @@ const MessageList = memo(function MessageList({ {messages .slice(2) .filter((message) => message.content.length > 0) - .map((message, index) => { - const absoluteIndex = index + 2; - const isLastAssistant = - absoluteIndex === messages.length - 1 && - message.role === "assistant"; - return ( - - ); - })} + .map((message, index) => ( + + ))} ); }); diff --git a/client/components/AiResponse/ReasoningSection.tsx b/client/components/AiResponse/ReasoningSection.tsx index e18ed63d03bda29dd4f58ce5ad59aa2171475f79..7d27a6e7d1ffbb0d1c09cfb15a107cdb23ec9292 100644 --- a/client/components/AiResponse/ReasoningSection.tsx +++ b/client/components/AiResponse/ReasoningSection.tsx @@ -8,7 +8,7 @@ import { UnstyledButton, } from "@mantine/core"; import { IconChevronDown, IconChevronRight } from "@tabler/icons-react"; -import { useEffect, useState } from "react"; +import { useState } from "react"; import MarkdownRenderer from "./MarkdownRenderer"; interface ReasoningSectionProps { @@ -20,15 +20,7 @@ export default function ReasoningSection({ content, isGenerating = false, }: ReasoningSectionProps) { - const [isOpen, setIsOpen] = useState(isGenerating); - - useEffect(() => { - if (isGenerating) { - setIsOpen(true); - } else { - setIsOpen(false); - } - }, [isGenerating]); + const [isOpen, setIsOpen] = useState(false); return ( diff --git a/client/components/AiResponse/WebLlmModelSelect.tsx b/client/components/AiResponse/WebLlmModelSelect.tsx index a377ec5ff10d6f97f5bfe41daac5b70ae94e55df..a967fef6e08b5c761c813adb57ae88a392c7df35 100644 --- a/client/components/AiResponse/WebLlmModelSelect.tsx +++ b/client/components/AiResponse/WebLlmModelSelect.tsx @@ -1,7 +1,7 @@ import { type ComboboxItem, Select } from "@mantine/core"; import { prebuiltAppConfig } from "@mlc-ai/web-llm"; import { useCallback, useEffect, useState } from "react"; -import { isF16Supported } from "@/modules/webGpu"; +import { isF16Supported } from "../../modules/webGpu"; export default function WebLlmModelSelect({ value, diff --git a/client/components/AiResponse/WllamaModelSelect.tsx b/client/components/AiResponse/WllamaModelSelect.tsx index 70e84535ebec091ddfb93658d8129a1c0d9c088c..6a63fcaa664cc28ddc563f7b068acdd7ecb16d7f 100644 --- a/client/components/AiResponse/WllamaModelSelect.tsx +++ b/client/components/AiResponse/WllamaModelSelect.tsx @@ -1,6 +1,6 @@ import { type ComboboxItem, Select } from "@mantine/core"; import { useEffect, useState } from "react"; -import { wllamaModels } from "@/modules/wllama"; +import { wllamaModels } from "../../modules/wllama"; export default function WllamaModelSelect({ value, diff --git a/client/components/AiResponse/hooks/useReasoningContent.test.ts b/client/components/AiResponse/hooks/useReasoningContent.test.ts deleted file mode 100644 index 69423c6963ee405c3aa912ddbefb2c541c0fbf00..0000000000000000000000000000000000000000 --- a/client/components/AiResponse/hooks/useReasoningContent.test.ts +++ /dev/null @@ -1,96 +0,0 @@ -import { renderHook } from "@testing-library/react"; -import { describe, expect, it } from "vitest"; -import { useReasoningContent } from "./useReasoningContent"; - -const expectEmptyState = (result: { - current: ReturnType; -}) => { - expect(result.current.reasoningContent).toBe(""); - expect(result.current.mainContent).toBe(""); - expect(result.current.isGenerating).toBe(false); -}; - -describe("useReasoningContent hook", () => { - describe("parsing reasoning content from markdown markers", () => { - it("should extract reasoning content between start and end markers", () => { - const { result } = renderHook(() => - useReasoningContent( - "Let me think about this\nHere is the answer.", - ), - ); - - expect(result.current.reasoningContent).toBe("Let me think about this"); - expect(result.current.mainContent).toBe("\nHere is the answer."); - expect(result.current.isGenerating).toBe(false); - }); - - it("should handle empty text", () => { - const { result } = renderHook(() => useReasoningContent("")); - expectEmptyState(result); - }); - - it("should return text as main content when no markers present", () => { - const { result } = renderHook(() => - useReasoningContent("This is a normal response."), - ); - - expect(result.current.reasoningContent).toBe(""); - expect(result.current.mainContent).toBe("This is a normal response."); - expect(result.current.isGenerating).toBe(false); - }); - - it("should detect generating state when end marker is missing", () => { - const { result } = renderHook(() => - useReasoningContent("I'm still thinking"), - ); - - expect(result.current.reasoningContent).toBe("I'm still thinking"); - expect(result.current.mainContent).toBe(""); - expect(result.current.isGenerating).toBe(true); - }); - - it("should handle whitespace-only content", () => { - const { result } = renderHook(() => useReasoningContent(" ")); - expectEmptyState(result); - }); - - it("should handle null/undefined content gracefully", () => { - const { result } = renderHook(() => - useReasoningContent(null as unknown as string), - ); - expectEmptyState(result); - }); - }); - - describe("UI state management for reasoning section", () => { - it("should provide correct isGenerating state for accordion title", () => { - const streamingState = renderHook(() => - useReasoningContent("Currently thinking..."), - ); - - expect(streamingState.result.current.isGenerating).toBe(true); - - const completedState = renderHook(() => - useReasoningContent( - "Thought process completed\nHere is the answer.", - ), - ); - - expect(completedState.result.current.isGenerating).toBe(false); - }); - - it("should handle transition from streaming to completed state", () => { - const initial = renderHook(() => - useReasoningContent("Building response..."), - ); - expect(initial.result.current.isGenerating).toBe(true); - - const transitioned = renderHook(() => - useReasoningContent( - "Response built.\nFinal answer here.", - ), - ); - expect(transitioned.result.current.isGenerating).toBe(false); - }); - }); -}); diff --git a/client/components/AiResponse/hooks/useReasoningContent.ts b/client/components/AiResponse/hooks/useReasoningContent.ts index 62b7290c59fba384359199e251b61191280a105c..4511ee1b57e2fd52ecc1422bc34c4173db2b6378 100644 --- a/client/components/AiResponse/hooks/useReasoningContent.ts +++ b/client/components/AiResponse/hooks/useReasoningContent.ts @@ -1,12 +1,7 @@ import { usePubSub } from "create-pubsub/react"; import { useCallback } from "react"; -import { settingsPubSub } from "@/modules/pubSub"; +import { settingsPubSub } from "../../../modules/pubSub"; -/** - * Hook for extracting reasoning content from AI responses - * @param text - The full text response from the AI - * @returns Object containing separated reasoning and main content - */ export function useReasoningContent(text: string) { const [settings] = usePubSub(settingsPubSub); @@ -15,50 +10,28 @@ export function useReasoningContent(text: string) { if (!text) return { reasoningContent: "", mainContent: "", isGenerating: false }; - const trimmedText = text.trim(); - - if (!trimmedText.startsWith(startMarker)) + if (!text.trim().startsWith(startMarker)) return { reasoningContent: "", mainContent: text, isGenerating: false }; - const startIndex = trimmedText.indexOf(startMarker); - const endIndex = trimmedText.indexOf(endMarker); + const endIndex = text.indexOf(endMarker); if (endIndex === -1) { return { - reasoningContent: trimmedText.slice(startIndex + startMarker.length), + reasoningContent: text.slice(startMarker.length), mainContent: "", isGenerating: true, }; } return { - reasoningContent: trimmedText.slice( - startIndex + startMarker.length, - endIndex, - ), - mainContent: trimmedText.slice(endIndex + endMarker.length), + reasoningContent: text.slice(startMarker.length, endIndex), + mainContent: text.slice(endIndex + endMarker.length), isGenerating: false, }; }, [], ); - if (text && text.trim() === "") { - return { - reasoningContent: "", - mainContent: "", - isGenerating: false, - }; - } - - if (!text) { - return { - reasoningContent: "", - mainContent: "", - isGenerating: false, - }; - } - const result = extractReasoningAndMainContent( text, settings.reasoningStartMarker, diff --git a/client/components/Analytics/SearchStats.tsx b/client/components/Analytics/SearchStats.tsx deleted file mode 100644 index e4ad14661e1d53f8cb229a8f5773706ee680d186..0000000000000000000000000000000000000000 --- a/client/components/Analytics/SearchStats.tsx +++ /dev/null @@ -1,313 +0,0 @@ -import { - Badge, - Card, - Center, - Group, - Progress, - SimpleGrid, - Stack, - Text, - ThemeIcon, - Title, -} from "@mantine/core"; -import { IconSearch } from "@tabler/icons-react"; -import { useMemo } from "react"; -import { useSearchHistory } from "@/hooks/useSearchHistory"; -import type { SearchEntry } from "@/modules/history"; -import { formatRelativeTime } from "@/modules/stringFormatters"; - -interface SearchStatsProps { - period?: "today" | "week" | "month" | "all"; - compact?: boolean; -} - -interface StatsData { - totalSearches: number; - avgPerDay: number; - mostActiveHour: number; - topSources: { source: string; count: number; percentage: number }[]; - recentActivity: SearchEntry[]; - searchTrends: { date: string; count: number }[]; -} - -export default function SearchStats({ - period = "week", - compact = false, -}: SearchStatsProps) { - const { recentSearches, isLoading } = useSearchHistory({ limit: 1000 }); - - const stats = useMemo((): StatsData => { - if (!recentSearches.length) { - return { - totalSearches: 0, - avgPerDay: 0, - mostActiveHour: 0, - topSources: [], - recentActivity: [], - searchTrends: [], - }; - } - - const now = new Date(); - const filterDate = new Date(); - - switch (period) { - case "today": - filterDate.setHours(0, 0, 0, 0); - break; - case "week": - filterDate.setDate(now.getDate() - 7); - break; - case "month": - filterDate.setDate(now.getDate() - 30); - break; - default: - filterDate.setFullYear(2000); - } - - const filteredSearches = recentSearches.filter( - (search) => search.timestamp >= filterDate.getTime(), - ); - - const totalSearches = filteredSearches.length; - - const dateCounts = new Map(); - filteredSearches.forEach((search) => { - const date = new Date(search.timestamp).toISOString().split("T")[0]; - dateCounts.set(date, (dateCounts.get(date) || 0) + 1); - }); - - const uniqueDays = dateCounts.size; - const avgPerDay = - uniqueDays > 0 ? Math.round(totalSearches / uniqueDays) : 0; - - const hourCounts = new Array(24).fill(0); - filteredSearches.forEach((search) => { - const hour = new Date(search.timestamp).getHours(); - hourCounts[hour]++; - }); - const mostActiveHour = hourCounts.indexOf(Math.max(...hourCounts)); - - const sourceCounts = filteredSearches.reduce( - (acc, search) => { - if (compact && search.source?.toLowerCase() === "user") { - return acc; - } - const source = search.source || "unknown"; - acc[source] = (acc[source] || 0) + 1; - return acc; - }, - {} as Record, - ); - - const sourcesTotal = Object.values(sourceCounts).reduce( - (sum, n) => sum + n, - 0, - ); - const topSources = Object.entries(sourceCounts) - .map(([source, count]) => ({ - source: source.charAt(0).toUpperCase() + source.slice(1), - count, - percentage: - sourcesTotal > 0 ? Math.round((count / sourcesTotal) * 100) : 0, - })) - .sort((a, b) => b.count - a.count); - - const recentActivity = filteredSearches - .sort((a, b) => b.timestamp - a.timestamp) - .slice(0, 10); - - const searchTrends = Array.from(dateCounts.entries()) - .map(([date, count]) => ({ date, count })) - .sort((a, b) => a.date.localeCompare(b.date)); - - return { - totalSearches, - avgPerDay, - mostActiveHour, - topSources, - recentActivity, - searchTrends, - }; - }, [recentSearches, period, compact]); - - const getSourceColor = (source: string) => { - const colors = { - User: "blue", - Followup: "green", - Suggestion: "orange", - Unknown: "gray", - }; - return colors[source as keyof typeof colors] || "gray"; - }; - - const formatHour = (hour: number) => { - const period = hour >= 12 ? "PM" : "AM"; - const displayHour = hour === 0 ? 12 : hour > 12 ? hour - 12 : hour; - return `${displayHour}:00 ${period}`; - }; - - if (isLoading) { - return ( - -
    - Loading analytics... -
    -
    - ); - } - - if (stats.totalSearches === 0) { - return ( - -
    - - - - - No search data available - - Start searching to see analytics - - -
    -
    - ); - } - - function MetricCard({ - title, - value, - }: { - title: string; - value: string | number; - }) { - return ( - - - - {title} - - - {value} - - - - ); - } - - return ( - - - - - - 0 - ? formatRelativeTime(stats.recentActivity[0].timestamp) - : "Never" - } - /> - - - - {!(compact && stats.topSources.length === 0) && ( - - - - Search Sources - - - {stats.topSources.length > 0 ? ( - - {stats.topSources.map((source) => ( - - - - {source.source} - - - {source.count} searches - - - - - - - {source.percentage}% - - - - ))} - - ) : ( - - No data available - - )} - - - )} - - - {stats.searchTrends.length > 1 && ( - - - - Recent activity - - - {stats.searchTrends.slice(-7).map((trend) => { - const maxCount = Math.max( - ...stats.searchTrends.map((t) => t.count), - ); - const percentage = - maxCount > 0 ? (trend.count / maxCount) * 100 : 0; - - return ( - - - {new Date(trend.date).toLocaleDateString("en", { - month: "short", - day: "numeric", - })} - - - - - - {trend.count} - - - - ); - })} - - - - )} - - ); -} diff --git a/client/components/App/App.tsx b/client/components/App/App.tsx index d97fd7085483edca19fea04f85828141b5e81a99..94bd6a2a44a266b8da6701f40d090f271711dce0 100644 --- a/client/components/App/App.tsx +++ b/client/components/App/App.tsx @@ -1,66 +1,43 @@ -import { - Center, - Container, - Loader, - MantineProvider, - Stack, - Text, -} from "@mantine/core"; +import { MantineProvider } from "@mantine/core"; import { Route, Switch } from "wouter"; import "@mantine/core/styles.css"; import { Notifications } from "@mantine/notifications"; import { usePubSub } from "create-pubsub/react"; import { lazy, useEffect, useState } from "react"; -import { addLogEntry } from "@/modules/logEntries"; -import { settingsPubSub } from "@/modules/pubSub"; -import { defaultSettings } from "@/modules/settings"; +import { addLogEntry } from "../../modules/logEntries"; +import { settingsPubSub } from "../../modules/pubSub"; +import { defaultSettings } from "../../modules/settings"; import "@mantine/notifications/styles.css"; -import { verifyStoredAccessKey } from "@/modules/accessKey"; +import { verifyStoredAccessKey } from "../../modules/accessKey"; import MainPage from "../Pages/Main/MainPage"; const AccessPage = lazy(() => import("../Pages/AccessPage")); -/** - * Main application component with access key validation and routing - */ -function App() { +export function App() { useInitializeSettings(); const { hasValidatedAccessKey, isCheckingStoredKey, setValidatedAccessKey } = useAccessKeyValidation(); + if (isCheckingStoredKey) { + return null; + } + return ( - {isCheckingStoredKey ? ( - -
    - - - Verifying access... - -
    -
    - ) : ( - <> - - - - {hasValidatedAccessKey ? ( - - ) : ( - setValidatedAccessKey(true)} - /> - )} - - - - )} + + + + {VITE_ACCESS_KEYS_ENABLED && !hasValidatedAccessKey ? ( + setValidatedAccessKey(true)} /> + ) : ( + + )} + +
    ); } -export default App; - /** * A custom React hook that initializes the application settings. * @@ -96,18 +73,18 @@ function useInitializeSettings() { * @returns An object containing the validation state and loading state */ function useAccessKeyValidation() { - const [state, setState] = useState(() => ({ - hasValidatedAccessKey: !VITE_ACCESS_KEYS_ENABLED, - isCheckingStoredKey: VITE_ACCESS_KEYS_ENABLED, - })); + const [state, setState] = useState({ + hasValidatedAccessKey: false, + isCheckingStoredKey: true, + }); useEffect(() => { - if (!VITE_ACCESS_KEYS_ENABLED) return; - async function checkStoredAccessKey() { - const isValid = await verifyStoredAccessKey(); - if (isValid) - setState((prev) => ({ ...prev, hasValidatedAccessKey: true })); + if (VITE_ACCESS_KEYS_ENABLED) { + const isValid = await verifyStoredAccessKey(); + if (isValid) + setState((prev) => ({ ...prev, hasValidatedAccessKey: true })); + } setState((prev) => ({ ...prev, isCheckingStoredKey: false })); } diff --git a/client/components/Logs/LogsModal.tsx b/client/components/Logs/LogsModal.tsx index 099452ada78316218c6842edbe79d2dc07d9e642..35c0abcb0a0f2835fc05d96b2bc23ba0e70439e1 100644 --- a/client/components/Logs/LogsModal.tsx +++ b/client/components/Logs/LogsModal.tsx @@ -13,7 +13,7 @@ import { import { IconInfoCircle, IconSearch } from "@tabler/icons-react"; import { usePubSub } from "create-pubsub/react"; import { useCallback, useEffect, useMemo, useState } from "react"; -import { logEntriesPubSub } from "@/modules/logEntries"; +import { logEntriesPubSub } from "../../modules/logEntries"; export default function LogsModal({ opened, @@ -112,8 +112,8 @@ export default function LogsModal({ - {logEntriesFromCurrentPage.map((entry) => ( - + {logEntriesFromCurrentPage.map((entry, index) => ( + {new Date(entry.timestamp).toLocaleTimeString()} diff --git a/client/components/Logs/ShowLogsButton.tsx b/client/components/Logs/ShowLogsButton.tsx index a61c099676737405ab820b5d8890e9b1389a8e2d..9851a61191b8063322497fb3c588570e8240957c 100644 --- a/client/components/Logs/ShowLogsButton.tsx +++ b/client/components/Logs/ShowLogsButton.tsx @@ -1,6 +1,6 @@ import { Button, Center, Loader, Stack, Text } from "@mantine/core"; import { lazy, Suspense, useState } from "react"; -import { addLogEntry } from "@/modules/logEntries"; +import { addLogEntry } from "../../modules/logEntries"; const LogsModal = lazy(() => import("./LogsModal")); diff --git a/client/components/Pages/AccessPage.tsx b/client/components/Pages/AccessPage.tsx index c11cd8c0dfb9a69b883f312d022ad464f56bfb88..a15ac688054a8613e964998eef195d202307ed0c 100644 --- a/client/components/Pages/AccessPage.tsx +++ b/client/components/Pages/AccessPage.tsx @@ -1,7 +1,7 @@ import { Button, Container, Stack, TextInput, Title } from "@mantine/core"; import { type FormEvent, useState } from "react"; -import { validateAccessKey } from "@/modules/accessKey"; -import { addLogEntry } from "@/modules/logEntries"; +import { validateAccessKey } from "../../modules/accessKey"; +import { addLogEntry } from "../../modules/logEntries"; interface AccessPageState { accessKey: string; diff --git a/client/components/Pages/Main/MainPage.test.tsx b/client/components/Pages/Main/MainPage.test.tsx deleted file mode 100644 index 3baefa16187e602a2f706134cfe9b3ea7376bbf7..0000000000000000000000000000000000000000 --- a/client/components/Pages/Main/MainPage.test.tsx +++ /dev/null @@ -1,110 +0,0 @@ -import { describe, expect, it } from "vitest"; - -describe("MainPage component logic", () => { - it("should show results only when query is not empty", () => { - const isQueryEmpty = (query: string) => query.length === 0; - - expect(isQueryEmpty("")).toBe(true); - expect(isQueryEmpty("test query")).toBe(false); - expect(isQueryEmpty(" ")).toBe(false); - }); - - it("should determine when to show search results section", () => { - const shouldShowSearchResults = ( - textSearchState: string, - imageSearchState: string, - ) => textSearchState !== "idle" || imageSearchState !== "idle"; - - expect(shouldShowSearchResults("idle", "idle")).toBe(false); - expect(shouldShowSearchResults("loading", "idle")).toBe(true); - expect(shouldShowSearchResults("idle", "loading")).toBe(true); - expect(shouldShowSearchResults("success", "success")).toBe(true); - }); - - it("should determine when to show AI response section", () => { - const shouldShowAiResponse = ( - textGenerationState: string, - showEnableAiResponsePrompt: boolean, - ) => !showEnableAiResponsePrompt && textGenerationState !== "idle"; - - expect(shouldShowAiResponse("idle", false)).toBe(false); - expect(shouldShowAiResponse("generating", false)).toBe(true); - expect(shouldShowAiResponse("generating", true)).toBe(false); - expect(shouldShowAiResponse("complete", false)).toBe(true); - }); - - it("should determine when to show enable AI prompt", () => { - const shouldShowEnablePrompt = (showEnableAiResponsePrompt: boolean) => - showEnableAiResponsePrompt; - - expect(shouldShowEnablePrompt(true)).toBe(true); - expect(shouldShowEnablePrompt(false)).toBe(false); - }); - - it("should combine conditions correctly for full page state", () => { - interface PageState { - query: string; - textSearchState: string; - imageSearchState: string; - textGenerationState: string; - showEnableAiResponsePrompt: boolean; - } - - const getVisibleSections = (state: PageState) => { - const isQueryEmpty = state.query.length === 0; - return { - showResults: - !isQueryEmpty && - (state.textSearchState !== "idle" || - state.imageSearchState !== "idle"), - showAiResponse: - !isQueryEmpty && - !state.showEnableAiResponsePrompt && - state.textGenerationState !== "idle", - showEnablePrompt: !isQueryEmpty && state.showEnableAiResponsePrompt, - }; - }; - - expect( - getVisibleSections({ - query: "", - textSearchState: "success", - imageSearchState: "idle", - textGenerationState: "generating", - showEnableAiResponsePrompt: false, - }), - ).toEqual({ - showResults: false, - showAiResponse: false, - showEnablePrompt: false, - }); - - expect( - getVisibleSections({ - query: "test", - textSearchState: "success", - imageSearchState: "idle", - textGenerationState: "generating", - showEnableAiResponsePrompt: false, - }), - ).toEqual({ - showResults: true, - showAiResponse: true, - showEnablePrompt: false, - }); - - expect( - getVisibleSections({ - query: "test", - textSearchState: "idle", - imageSearchState: "idle", - textGenerationState: "idle", - showEnableAiResponsePrompt: true, - }), - ).toEqual({ - showResults: false, - showAiResponse: false, - showEnablePrompt: true, - }); - }); -}); diff --git a/client/components/Pages/Main/MainPage.tsx b/client/components/Pages/Main/MainPage.tsx index 61ceb056e548f8d99f20de4ace68f5f473c2bef1..69b207fb20050ef9fb4eae286c08909e2d1d04f6 100644 --- a/client/components/Pages/Main/MainPage.tsx +++ b/client/components/Pages/Main/MainPage.tsx @@ -1,25 +1,25 @@ import { Container, Stack } from "@mantine/core"; import { usePubSub } from "create-pubsub/react"; import { lazy, Suspense } from "react"; -import SearchForm from "@/components/Search/Form/SearchForm"; import { imageSearchStatePubSub, queryPubSub, settingsPubSub, textGenerationStatePubSub, textSearchStatePubSub, -} from "@/modules/pubSub"; -import { searchAndRespond } from "@/modules/textGeneration"; +} from "../../../modules/pubSub"; +import { searchAndRespond } from "../../../modules/textGeneration"; +import SearchForm from "../../Search/Form/SearchForm"; import MenuButton from "./Menu/MenuButton"; const AiResponseSection = lazy( - () => import("@/components/AiResponse/AiResponseSection"), + () => import("../../AiResponse/AiResponseSection"), ); const SearchResultsSection = lazy( - () => import("@/components/Search/Results/SearchResultsSection"), + () => import("../../Search/Results/SearchResultsSection"), ); const EnableAiResponsePrompt = lazy( - () => import("@/components/AiResponse/EnableAiResponsePrompt"), + () => import("../../AiResponse/EnableAiResponsePrompt"), ); export default function MainPage() { diff --git a/client/components/Pages/Main/Menu/AISettings/AISettingsForm.tsx b/client/components/Pages/Main/Menu/AISettings/AISettingsForm.tsx index f57118ac6f6e816640be11dfd9af48954571555c..7f55ed227e55a7cb90f4733e5d14fd405cfff9ef 100644 --- a/client/components/Pages/Main/Menu/AISettings/AISettingsForm.tsx +++ b/client/components/Pages/Main/Menu/AISettings/AISettingsForm.tsx @@ -2,9 +2,12 @@ import { Select, Slider, Stack, Switch, Text, TextInput } from "@mantine/core"; import { useForm } from "@mantine/form"; import { usePubSub } from "create-pubsub/react"; import { useMemo } from "react"; -import { settingsPubSub } from "@/modules/pubSub"; -import { defaultSettings, inferenceTypes } from "@/modules/settings"; -import { isWebGPUAvailable } from "@/modules/webGpu"; +import { settingsPubSub } from "../../../../../modules/pubSub"; +import { + defaultSettings, + inferenceTypes, +} from "../../../../../modules/settings"; +import { isWebGPUAvailable } from "../../../../../modules/webGpu"; import { AIParameterSlider } from "./components/AIParameterSlider"; import { BrowserSettings } from "./components/BrowserSettings"; import { HordeSettings } from "./components/HordeSettings"; diff --git a/client/components/Pages/Main/Menu/AISettings/components/AIParameterSlider.tsx b/client/components/Pages/Main/Menu/AISettings/components/AIParameterSlider.tsx index 6373ed6f4186e1dff3cc5f9889283b43bd7c44fc..fd9240e9f48dfbfc94c7fb9197b9b56d6d720629 100644 --- a/client/components/Pages/Main/Menu/AISettings/components/AIParameterSlider.tsx +++ b/client/components/Pages/Main/Menu/AISettings/components/AIParameterSlider.tsx @@ -1,13 +1,6 @@ import { Slider, Stack, Text } from "@mantine/core"; import type { AIParameterSliderProps } from "../types"; -/** - * Slider component for AI parameters with label and description - * @param label - The parameter label - * @param description - Parameter description text - * @param defaultValue - Default value for the parameter - * @param props - Additional props to pass to Slider component - */ export const AIParameterSlider = ({ label, description, diff --git a/client/components/Pages/Main/Menu/AISettings/components/BrowserSettings.tsx b/client/components/Pages/Main/Menu/AISettings/components/BrowserSettings.tsx index 5e972620ef48697cbc41a18ac5d53c5c32ffa740..fe907fff6f344ea36c04249eab7674f486907c3e 100644 --- a/client/components/Pages/Main/Menu/AISettings/components/BrowserSettings.tsx +++ b/client/components/Pages/Main/Menu/AISettings/components/BrowserSettings.tsx @@ -1,29 +1,20 @@ import { NumberInput, Skeleton, Switch } from "@mantine/core"; import type { UseFormReturnType } from "@mantine/form"; import { lazy, Suspense } from "react"; -import type { defaultSettings } from "@/modules/settings"; +import type { defaultSettings } from "../../../../../../modules/settings"; const WebLlmModelSelect = lazy( - () => import("@/components/AiResponse/WebLlmModelSelect"), + () => import("../../../../../../components/AiResponse/WebLlmModelSelect"), ); const WllamaModelSelect = lazy( - () => import("@/components/AiResponse/WllamaModelSelect"), + () => import("../../../../../../components/AiResponse/WllamaModelSelect"), ); -/** - * Props for the BrowserSettings component - */ interface BrowserSettingsProps { - /** Form instance for managing browser AI settings */ form: UseFormReturnType; - /** Whether WebGPU is available in the current browser */ isWebGPUAvailable: boolean; } -/** - * Component for managing browser-based AI settings. - * Provides controls for WebGPU/CPU selection, model selection, and CPU thread configuration. - */ export const BrowserSettings = ({ form, isWebGPUAvailable, diff --git a/client/components/Pages/Main/Menu/AISettings/components/HordeSettings.tsx b/client/components/Pages/Main/Menu/AISettings/components/HordeSettings.tsx index 45fd4bddd00df0ebce2b2bbafee27be04c6d2c86..6e3f466ec9dad5cb010c309e7461080c6f37a22a 100644 --- a/client/components/Pages/Main/Menu/AISettings/components/HordeSettings.tsx +++ b/client/components/Pages/Main/Menu/AISettings/components/HordeSettings.tsx @@ -1,25 +1,15 @@ import { Select, TextInput } from "@mantine/core"; import type { UseFormReturnType } from "@mantine/form"; -import type { defaultSettings } from "@/modules/settings"; -import { aiHordeDefaultApiKey } from "@/modules/textGenerationWithHorde"; +import type { defaultSettings } from "../../../../../../modules/settings"; +import { aiHordeDefaultApiKey } from "../../../../../../modules/textGenerationWithHorde"; import type { HordeUserInfo, ModelOption } from "../types"; -/** - * Props for the HordeSettings component - */ interface HordeSettingsProps { - /** Form instance for managing Horde AI settings */ form: UseFormReturnType; - /** User information from AI Horde, or null if not logged in */ hordeUserInfo: HordeUserInfo | null; - /** Available models from AI Horde */ hordeModels: ModelOption[]; } -/** - * Component for managing AI Horde settings. - * Provides controls for API key input and model selection. - */ export const HordeSettings = ({ form, hordeUserInfo, diff --git a/client/components/Pages/Main/Menu/AISettings/components/OpenAISettings.tsx b/client/components/Pages/Main/Menu/AISettings/components/OpenAISettings.tsx index 7fd268680ba19ebd4cc7f8cdb9656e3b7f444214..b1a99cd175bd36a8b22aadfadb0f6e6c95e46f33 100644 --- a/client/components/Pages/Main/Menu/AISettings/components/OpenAISettings.tsx +++ b/client/components/Pages/Main/Menu/AISettings/components/OpenAISettings.tsx @@ -1,25 +1,15 @@ -import { Group, NumberInput, Select, Text, TextInput } from "@mantine/core"; +import { Group, Select, Text, TextInput } from "@mantine/core"; import type { UseFormReturnType } from "@mantine/form"; import { IconInfoCircle } from "@tabler/icons-react"; -import { defaultSettings } from "@/modules/settings"; +import type { defaultSettings } from "../../../../../../modules/settings"; import type { ModelOption } from "../types"; -/** - * Props for the OpenAISettings component - */ interface OpenAISettingsProps { - /** Form instance for managing OpenAI API settings */ form: UseFormReturnType; - /** Available OpenAI-compatible models */ openAiModels: ModelOption[]; - /** Whether to use text input instead of select for model */ useTextInput: boolean; } -/** - * Component for managing OpenAI API settings. - * Provides controls for API base URL, API key, model selection, and context length. - */ export const OpenAISettings = ({ form, openAiModels, @@ -61,16 +51,7 @@ export const OpenAISettings = ({ allowDeselect={false} disabled={openAiModels.length === 0} searchable - clearable /> )} - ); diff --git a/client/components/Pages/Main/Menu/AISettings/components/SystemPromptInput.tsx b/client/components/Pages/Main/Menu/AISettings/components/SystemPromptInput.tsx index 544ee1bc791ba4a11dd216335922be363c29bf34..9f7421726be55ca70dec5b5670d9c6a89e0b16f1 100644 --- a/client/components/Pages/Main/Menu/AISettings/components/SystemPromptInput.tsx +++ b/client/components/Pages/Main/Menu/AISettings/components/SystemPromptInput.tsx @@ -1,26 +1,15 @@ import { Text, Textarea } from "@mantine/core"; import type { UseFormReturnType } from "@mantine/form"; -import { defaultSettings } from "@/modules/settings"; +import { defaultSettings } from "../../../../../../modules/settings"; -/** - * Props for the SystemPromptInput component - */ interface SystemPromptInputProps { - /** Form instance for managing system prompt settings */ form: UseFormReturnType; } -/** - * Component for managing system prompt/instructions for AI. - * Provides a textarea for customizing AI behavior with examples and restore functionality. - */ export const SystemPromptInput = ({ form }: SystemPromptInputProps) => { const isUsingCustomInstructions = form.values.systemPrompt !== defaultSettings.systemPrompt; - /** - * Handles restoring the default system prompt instructions - */ const handleRestoreDefaultInstructions = () => { form.setFieldValue("systemPrompt", defaultSettings.systemPrompt); }; @@ -79,8 +68,8 @@ export const SystemPromptInput = ({ form }: SystemPromptInputProps) => { The special tag {"{{searchResults}}"} will be replaced with - the search results, while {"{{currentDate}}"} will be - replaced with the current date. + the search results, while {"{{dateTime}}"} will be replaced + with the current date and time. {isUsingCustomInstructions && ( diff --git a/client/components/Pages/Main/Menu/AISettings/hooks/useHordeModels.ts b/client/components/Pages/Main/Menu/AISettings/hooks/useHordeModels.ts index 3f225263b3b53b66efe031e5b39ab05efb0cc512..c0eb64e19ac09eb97e4461df1fd80677dc40472b 100644 --- a/client/components/Pages/Main/Menu/AISettings/hooks/useHordeModels.ts +++ b/client/components/Pages/Main/Menu/AISettings/hooks/useHordeModels.ts @@ -1,26 +1,15 @@ import { useEffect, useState } from "react"; -import { addLogEntry } from "@/modules/logEntries"; -import type { defaultSettings } from "@/modules/settings"; -import { fetchHordeModels } from "@/modules/textGenerationWithHorde"; +import { addLogEntry } from "../../../../../../modules/logEntries"; +import type { defaultSettings } from "../../../../../../modules/settings"; +import { fetchHordeModels } from "../../../../../../modules/textGenerationWithHorde"; import type { ModelOption } from "../types"; -/** - * Type alias for the settings object - */ type Settings = typeof defaultSettings; -/** - * Hook for fetching and managing AI Horde models - * @param settings - Application settings object - * @returns Array of available AI Horde models formatted as ModelOption[] - */ export const useHordeModels = (settings: Settings) => { const [hordeModels, setHordeModels] = useState([]); useEffect(() => { - /** - * Fetches available models from AI Horde and formats them for UI - */ async function fetchAvailableHordeModels() { try { const models = await fetchHordeModels(); diff --git a/client/components/Pages/Main/Menu/AISettings/hooks/useHordeUserInfo.ts b/client/components/Pages/Main/Menu/AISettings/hooks/useHordeUserInfo.ts index bd1ce6ab409793e6949ba26edc0f28e41f3a06c7..e6bdfd9b6346f322a4f3b551846ed4708c47c7b0 100644 --- a/client/components/Pages/Main/Menu/AISettings/hooks/useHordeUserInfo.ts +++ b/client/components/Pages/Main/Menu/AISettings/hooks/useHordeUserInfo.ts @@ -1,31 +1,20 @@ import { useEffect, useState } from "react"; -import { addLogEntry } from "@/modules/logEntries"; -import type { defaultSettings } from "@/modules/settings"; +import { addLogEntry } from "../../../../../../modules/logEntries"; +import type { defaultSettings } from "../../../../../../modules/settings"; import { aiHordeDefaultApiKey, fetchHordeUserInfo, -} from "@/modules/textGenerationWithHorde"; +} from "../../../../../../modules/textGenerationWithHorde"; import type { HordeUserInfo } from "../types"; -/** - * Type alias for the settings object - */ type Settings = typeof defaultSettings; -/** - * Hook for fetching and managing AI Horde user information - * @param settings - Application settings object - * @returns Horde user information or null if not authenticated - */ export const useHordeUserInfo = (settings: Settings) => { const [hordeUserInfo, setHordeUserInfo] = useState( null, ); useEffect(() => { - /** - * Fetches user information from AI Horde API - */ async function fetchUserInfo() { try { if ( diff --git a/client/components/Pages/Main/Menu/AISettings/hooks/useOpenAiModels.ts b/client/components/Pages/Main/Menu/AISettings/hooks/useOpenAiModels.ts index 050714a33b9402e613012a5d5fe8d2f927b23bef..fa5b32c1bca436a838d1eba33cfbabbafc997d2d 100644 --- a/client/components/Pages/Main/Menu/AISettings/hooks/useOpenAiModels.ts +++ b/client/components/Pages/Main/Menu/AISettings/hooks/useOpenAiModels.ts @@ -1,43 +1,39 @@ -import { listOpenAiCompatibleModels } from "@shared/openaiModels"; import { useEffect, useState } from "react"; -import { addLogEntry } from "@/modules/logEntries"; -import type { defaultSettings } from "@/modules/settings"; +import { addLogEntry } from "../../../../../../modules/logEntries"; +import type { defaultSettings } from "../../../../../../modules/settings"; import type { ModelOption } from "../types"; -/** - * Type alias for the settings object - */ type Settings = typeof defaultSettings; -/** - * Hook for fetching and managing OpenAI-compatible models - * @param settings - Application settings object - * @returns Object containing available models and whether to use text input - */ export const useOpenAiModels = (settings: Settings) => { const [openAiModels, setOpenAiModels] = useState([]); const [useTextInput, setUseTextInput] = useState(false); useEffect(() => { - /** - * Fetches available models from OpenAI-compatible API - */ async function fetchOpenAiModels() { try { - const models = await listOpenAiCompatibleModels( - settings.openAiApiBaseUrl, - settings.openAiApiKey, + const response = await fetch(`${settings.openAiApiBaseUrl}/models`, { + headers: { + Authorization: `Bearer ${settings.openAiApiKey}`, + }, + }); + + if (!response.ok) { + throw new Error(`Failed to fetch models: ${response.statusText}`); + } + + const data = await response.json(); + const modelIds: string[] = data.data.map( + (model: { id: string }) => model.id, ); - const uniqueModelIds = [ - ...new Set(models.map((m: { id: string }) => m.id)), - ]; - const options: ModelOption[] = uniqueModelIds.map((id) => ({ + const uniqueModelIds = [...new Set(modelIds)]; + const models = uniqueModelIds.map((id) => ({ label: id, value: id, })); - setOpenAiModels(options); - setUseTextInput(!Array.isArray(options) || options.length === 0); + setOpenAiModels(models); + setUseTextInput(!Array.isArray(models) || models.length === 0); } catch (error) { const errorMessage = error instanceof Error ? error.message : String(error); diff --git a/client/components/Pages/Main/Menu/AISettings/types.ts b/client/components/Pages/Main/Menu/AISettings/types.ts index 06eceb82965639d20e9cfb7ed017c5771fab1bb5..b4df4de1e79dbbb5a6c6d54b33993670c2e38fcb 100644 --- a/client/components/Pages/Main/Menu/AISettings/types.ts +++ b/client/components/Pages/Main/Menu/AISettings/types.ts @@ -1,31 +1,15 @@ -/** - * Represents a model option for select components - */ export interface ModelOption { - /** Display label for the model */ label: string; - /** Internal value for the model */ value: string; } -/** - * Represents user information from AI Horde - */ export interface HordeUserInfo { - /** Username of the Horde user */ username: string; - /** Number of kudos (credits) the user has */ kudos: number; } -/** - * Props for AI parameter slider components - */ export interface AIParameterSliderProps extends Record { - /** Label for the slider */ label: string; - /** Description for the slider */ description: string; - /** Default value for the slider */ defaultValue: number; } diff --git a/client/components/Pages/Main/Menu/ActionsForm.tsx b/client/components/Pages/Main/Menu/ActionsForm.tsx index 19203009ee9bfacb9a6f94c1da67932c8f59fd20..f2f14010d3849d98b8a00c5851339f896599c311 100644 --- a/client/components/Pages/Main/Menu/ActionsForm.tsx +++ b/client/components/Pages/Main/Menu/ActionsForm.tsx @@ -1,5 +1,5 @@ import { Stack } from "@mantine/core"; -import ShowLogsButton from "@/components/Logs/ShowLogsButton"; +import ShowLogsButton from "../../../Logs/ShowLogsButton"; import ClearDataButton from "./ClearDataButton"; export default function ActionsForm() { diff --git a/client/components/Pages/Main/Menu/ClearDataButton.tsx b/client/components/Pages/Main/Menu/ClearDataButton.tsx index e7fbd6a0fde9da935399b631e5e3be0c198dfba9..205af5718c2c757eddb3aa1a1991491f5ea3391b 100644 --- a/client/components/Pages/Main/Menu/ClearDataButton.tsx +++ b/client/components/Pages/Main/Menu/ClearDataButton.tsx @@ -2,7 +2,7 @@ import { Button, Stack, Text } from "@mantine/core"; import Dexie from "dexie"; import { useState } from "react"; import { useLocation } from "wouter"; -import { addLogEntry } from "@/modules/logEntries"; +import { addLogEntry } from "../../../../modules/logEntries"; interface ClearDataState { isClearingData: boolean; diff --git a/client/components/Pages/Main/Menu/InterfaceSettingsForm.tsx b/client/components/Pages/Main/Menu/InterfaceSettingsForm.tsx index 5322b8ce0aabe57815cd903696353ee1315a6276..925b33fa9e3d6716e157c2bbf2ef39cf189c2c4d 100644 --- a/client/components/Pages/Main/Menu/InterfaceSettingsForm.tsx +++ b/client/components/Pages/Main/Menu/InterfaceSettingsForm.tsx @@ -6,7 +6,7 @@ import { } from "@mantine/core"; import { useForm } from "@mantine/form"; import { usePubSub } from "create-pubsub/react"; -import { settingsPubSub } from "@/modules/pubSub"; +import { settingsPubSub } from "../../../../modules/pubSub"; export default function InterfaceSettingsForm() { const [settings, setSettings] = usePubSub(settingsPubSub); diff --git a/client/components/Pages/Main/Menu/MenuButton.tsx b/client/components/Pages/Main/Menu/MenuButton.tsx index 51b888414efef1fd38c77b5b030356afb2201757..01cb4e02bca1aa09c9c80998708262070f10d035 100644 --- a/client/components/Pages/Main/Menu/MenuButton.tsx +++ b/client/components/Pages/Main/Menu/MenuButton.tsx @@ -1,6 +1,6 @@ import { Button } from "@mantine/core"; import { lazy, Suspense, useCallback, useEffect, useState } from "react"; -import { addLogEntry } from "@/modules/logEntries"; +import { addLogEntry } from "../../../../modules/logEntries"; const MenuDrawer = lazy(() => import("./MenuDrawer")); diff --git a/client/components/Pages/Main/Menu/MenuDrawer.tsx b/client/components/Pages/Main/Menu/MenuDrawer.tsx index 924b13878f54707e32225debf74c370a06208098..8435b589c646f188431168691fccd2dac3ac1703 100644 --- a/client/components/Pages/Main/Menu/MenuDrawer.tsx +++ b/client/components/Pages/Main/Menu/MenuDrawer.tsx @@ -10,14 +10,13 @@ import { Stack, Tooltip, } from "@mantine/core"; -import { repository } from "@root/package.json"; import { IconBrandGithub } from "@tabler/icons-react"; import { usePubSub } from "create-pubsub/react"; import prettyMilliseconds from "pretty-ms"; -import HistorySettings from "@/components/Settings/HistorySettings"; -import { appName, appVersion } from "@/modules/appInfo"; -import { addLogEntry } from "@/modules/logEntries"; -import { menuExpandedAccordionsPubSub } from "@/modules/pubSub"; +import { repository } from "../../../../../package.json"; +import { appName, appVersion } from "../../../../modules/appInfo"; +import { addLogEntry } from "../../../../modules/logEntries"; +import { menuExpandedAccordionsPubSub } from "../../../../modules/pubSub"; import ActionsForm from "./ActionsForm"; import AISettingsForm from "./AISettings/AISettingsForm"; import InterfaceSettingsForm from "./InterfaceSettingsForm"; @@ -54,6 +53,7 @@ export default function MenuDrawer(drawerProps: DrawerProps) { +
    {appName}
    {`v${appVersion}`}
    Released{" "} @@ -98,12 +98,6 @@ export default function MenuDrawer(drawerProps: DrawerProps) { - - History Settings - - - - Voice Settings diff --git a/client/components/Pages/Main/Menu/SearchSettingsForm.tsx b/client/components/Pages/Main/Menu/SearchSettingsForm.tsx index ca8884674ca017cc0a2569a0318054a0b25753a9..9363fc23c3fc3bdf28a7fa916f64acfc0bfb432b 100644 --- a/client/components/Pages/Main/Menu/SearchSettingsForm.tsx +++ b/client/components/Pages/Main/Menu/SearchSettingsForm.tsx @@ -1,7 +1,7 @@ import { Slider, Stack, Switch, Text } from "@mantine/core"; import { useForm } from "@mantine/form"; import { usePubSub } from "create-pubsub/react"; -import { settingsPubSub } from "@/modules/pubSub"; +import { settingsPubSub } from "../../../../modules/pubSub"; export default function SearchSettingsForm() { const [settings, setSettings] = usePubSub(settingsPubSub); diff --git a/client/components/Pages/Main/Menu/VoiceSettingsForm.tsx b/client/components/Pages/Main/Menu/VoiceSettingsForm.tsx index 3d64ef40fb4c5d87487af16a470b5c6d4204e2e7..7ee5b968c333f815797f1b82a2e23f521745ac6c 100644 --- a/client/components/Pages/Main/Menu/VoiceSettingsForm.tsx +++ b/client/components/Pages/Main/Menu/VoiceSettingsForm.tsx @@ -3,7 +3,7 @@ import { useForm } from "@mantine/form"; import getUnicodeFlagIcon from "country-flag-icons/unicode"; import { usePubSub } from "create-pubsub/react"; import { useCallback, useEffect, useState } from "react"; -import { settingsPubSub } from "@/modules/pubSub"; +import { settingsPubSub } from "../../../../modules/pubSub"; export default function VoiceSettingsForm() { const [settings, setSettings] = usePubSub(settingsPubSub); diff --git a/client/components/Search/Form/SearchForm.test.tsx b/client/components/Search/Form/SearchForm.test.tsx deleted file mode 100644 index 0cd3e8064555e3bd3ca87d0aa9ace7fc16d7b172..0000000000000000000000000000000000000000 --- a/client/components/Search/Form/SearchForm.test.tsx +++ /dev/null @@ -1,89 +0,0 @@ -import { MantineProvider } from "@mantine/core"; -import { render, screen, waitFor } from "@testing-library/react"; -import userEvent from "@testing-library/user-event"; -import SearchForm from "@/components/Search/Form/SearchForm"; - -vi.mock("create-pubsub/react", () => ({ - usePubSub: vi.fn((pubSub: unknown) => { - if (!Array.isArray(pubSub)) { - return [undefined, vi.fn()]; - } - - const maybeFactory = pubSub[2]; - if (typeof maybeFactory !== "function") { - return [undefined, vi.fn()]; - } - - return [maybeFactory() ?? undefined, vi.fn()]; - }), -})); - -vi.mock("wouter", () => ({ - useLocation: vi.fn(() => ["/", vi.fn()]), -})); - -vi.mock("../../../hooks/useSearchHistory", () => ({ - useSearchHistory: vi.fn(() => ({ - addToHistory: vi.fn(), - })), -})); - -vi.mock("../../../hooks/useHistoryRestore", () => ({ - useHistoryRestore: vi.fn(() => ({ - restoreSearch: vi.fn(), - })), -})); - -vi.mock("../History/HistoryButton", () => ({ - default: function HistoryButton() { - return null; - }, -})); - -vi.mock("../../../modules/textGeneration", () => ({ - searchAndRespond: vi.fn(), -})); - -vi.mock("../../../modules/querySuggestions", () => ({ - getRandomQuerySuggestion: vi.fn(async () => "Anything you need!"), -})); - -const renderSearchForm = ( - query: string, - updateQuery: (query: string) => void, -) => { - return render( - - - , - ); -}; - -const waitForPlaceholder = async () => { - const textarea = await screen.findByRole("textbox"); - await waitFor(() => { - expect(textarea).toHaveAttribute("placeholder", "Anything you need!"); - }); - return textarea; -}; - -describe("SearchForm component", () => { - it("renders textarea with placeholder when empty", async () => { - const mockUpdate = vi.fn(); - renderSearchForm("", mockUpdate); - await waitForPlaceholder(); - }); - - it("calls updateQuery on submit", async () => { - const mockUpdate = vi.fn(); - const user = userEvent.setup(); - renderSearchForm("", mockUpdate); - - const textarea = await waitForPlaceholder(); - await user.type(textarea, "test query"); - const button = screen.getByRole("button", { name: /search/i }); - await user.click(button); - - expect(mockUpdate).toHaveBeenCalledWith("test query"); - }); -}); diff --git a/client/components/Search/Form/SearchForm.tsx b/client/components/Search/Form/SearchForm.tsx index 6426f32951c136940ecdaa3668ce7ac22c2cf243..29f7f71cf6e0d1c8bac354f9c64172b0c5e69c4a 100644 --- a/client/components/Search/Form/SearchForm.tsx +++ b/client/components/Search/Form/SearchForm.tsx @@ -10,23 +10,13 @@ import { useState, } from "react"; import { useLocation } from "wouter"; -import { useHistoryRestore } from "@/hooks/useHistoryRestore"; -import { useSearchHistory } from "@/hooks/useSearchHistory"; -import { resetSearchRunId } from "@/modules/history"; -import { handleEnterKeyDown } from "@/modules/keyboard"; -import { addLogEntry } from "@/modules/logEntries"; -import { postMessageToParentWindow } from "@/modules/parentWindow"; -import { - imageSearchResultsPubSub, - isRestoringFromHistoryPubSub, - responsePubSub, - settingsPubSub, - textSearchResultsPubSub, -} from "@/modules/pubSub"; -import { getRandomQuerySuggestion } from "@/modules/querySuggestions"; -import { sleepUntilIdle } from "@/modules/sleep"; -import { searchAndRespond } from "@/modules/textGeneration"; -import HistoryButton from "../History/HistoryButton"; +import { handleEnterKeyDown } from "../../../modules/keyboard"; +import { addLogEntry } from "../../../modules/logEntries"; +import { postMessageToParentWindow } from "../../../modules/parentWindow"; +import { settingsPubSub } from "../../../modules/pubSub"; +import { getRandomQuerySuggestion } from "../../../modules/querySuggestions"; +import { sleepUntilIdle } from "../../../modules/sleep"; +import { searchAndRespond } from "../../../modules/textGeneration"; interface SearchFormState { textAreaValue: string; @@ -43,109 +33,37 @@ export default function SearchForm({ additionalButtons?: ReactNode; }) { const textAreaRef = useRef(null); - const autoInitializedQueriesRef = useRef(new Set()); const defaultSuggestedQuery = "Anything you need!"; const [state, setState] = useState({ textAreaValue: query, suggestedQuery: defaultSuggestedQuery, }); - const [, navigate] = useLocation(); - const [pubSubSettings] = usePubSub(settingsPubSub); - const [isRestoringFromHistory] = usePubSub(isRestoringFromHistoryPubSub); - const [textSearchResults] = usePubSub(textSearchResultsPubSub); - const [imageSearchResults] = usePubSub(imageSearchResultsPubSub); - const [responseValue] = usePubSub(responsePubSub); - const { addToHistory } = useSearchHistory(); - const { restoreSearch } = useHistoryRestore((newQuery) => { - setState((prev) => ({ ...prev, textAreaValue: newQuery })); - updateQuery(newQuery); - }, textAreaRef); + const [settings] = usePubSub(settingsPubSub); + + const handleMount = useCallback(async () => { + await sleepUntilIdle(); + searchAndRespond(); + }, []); + const fetchQuerySuggestion = useCallback(async () => { try { return await getRandomQuerySuggestion(); - } catch { + } catch (_) { + addLogEntry("Failed to get query suggestion"); return defaultSuggestedQuery; } }, []); - useEffect(() => { - const initializeComponent = async () => { - const urlParams = new URLSearchParams(window.location.search); - const urlQuery = urlParams.get("q"); - - if (urlQuery && !autoInitializedQueriesRef.current.has(urlQuery)) { - autoInitializedQueriesRef.current.add(urlQuery); - updateQuery(urlQuery); - setState((prevState) => ({ - ...prevState, - textAreaValue: urlQuery, - })); - await sleepUntilIdle(); - searchAndRespond(); - } - }; - - initializeComponent(); - }, [updateQuery]); - - useEffect(() => { - const initializeComponent = async () => { - const urlParams = new URLSearchParams(window.location.search); - const urlQuery = urlParams.get("q"); - const normalizedUrlQuery = urlQuery?.trim(); - - const hasRestoredResults = - textSearchResults.length > 0 || imageSearchResults.length > 0; - const hasRestoredResponse = responseValue.trim().length > 0; - - if ( - normalizedUrlQuery && - !autoInitializedQueriesRef.current.has(normalizedUrlQuery) && - !isRestoringFromHistory && - !hasRestoredResults && - !hasRestoredResponse - ) { - autoInitializedQueriesRef.current.add(normalizedUrlQuery); - await sleepUntilIdle(); - - try { - resetSearchRunId(); - await addToHistory(normalizedUrlQuery, { - type: "text" as const, - items: [], - }); - } catch (error) { - addLogEntry(`Failed to add search to history: ${error}`); - } - - searchAndRespond(); - } - }; - - void initializeComponent(); - }, [ - isRestoringFromHistory, - textSearchResults.length, - imageSearchResults.length, - responseValue, - addToHistory, - ]); + const handleInitialSuggestion = useCallback(async () => { + const suggestion = await fetchQuerySuggestion(); + setState((prev) => ({ ...prev, suggestedQuery: suggestion })); + }, [fetchQuerySuggestion]); useEffect(() => { - if (state.textAreaValue.length === 0) { - fetchQuerySuggestion() - .then((suggestion) => { - setState((prev) => ({ ...prev, suggestedQuery: suggestion })); - }) - .catch(() => { - setState((prev) => ({ - ...prev, - suggestedQuery: defaultSuggestedQuery, - })); - }); - } - }, [state.textAreaValue.length, fetchQuerySuggestion]); + handleMount(); + handleInitialSuggestion(); + }, [handleMount, handleInitialSuggestion]); const handleInputChange = async (event: ChangeEvent) => { const text = event.target.value; @@ -156,7 +74,7 @@ export default function SearchForm({ try { const suggestion = await getRandomQuerySuggestion(); setState((prev) => ({ ...prev, suggestedQuery: suggestion })); - } catch { + } catch (_) { addLogEntry("Failed to get query suggestion"); setState((prev) => ({ ...prev, @@ -180,70 +98,45 @@ export default function SearchForm({ })); }; - const startSearching = useCallback(async () => { + const startSearching = useCallback(() => { const queryToEncode = state.textAreaValue.trim().length >= 1 ? state.textAreaValue : state.suggestedQuery; - const normalizedQuery = queryToEncode.trim(); - - if (normalizedQuery.length > 0) { - autoInitializedQueriesRef.current.add(normalizedQuery); - } setState((prev) => ({ ...prev, textAreaValue: queryToEncode })); - updateQuery(queryToEncode); const queryString = `q=${encodeURIComponent(queryToEncode)}`; postMessageToParentWindow({ queryString, hash: "" }); + navigate(`/?${queryString}`, { replace: true }); - try { - resetSearchRunId(); - await addToHistory(queryToEncode, { - type: "text" as const, - items: [], - }); - } catch (error) { - addLogEntry(`Failed to add search to history: ${error}`); - } + updateQuery(queryToEncode); searchAndRespond(); addLogEntry( `User submitted a search with ${queryToEncode.length} characters length`, ); - }, [ - state.textAreaValue, - state.suggestedQuery, - updateQuery, - navigate, - addToHistory, - ]); + }, [state.textAreaValue, state.suggestedQuery, updateQuery, navigate]); - const handleSubmit = (event: React.FormEvent) => { + const handleSubmit = (event: { preventDefault: () => void }) => { event.preventDefault(); startSearching(); }; const handleKeyDown = (event: KeyboardEvent) => { - if (event.key === "Enter" && !event.shiftKey) { - handleEnterKeyDown(event, pubSubSettings, startSearching); - } + handleEnterKeyDown(event, settings, () => handleSubmit(event)); }; return ( -
    +