Charan5775 commited on
Commit
8f7821c
·
1 Parent(s): c1f470c

Add application file

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .dockerignore +26 -0
  2. .editorconfig +13 -0
  3. .env.example +82 -0
  4. .github/ISSUE_TEMPLATE/bug_report.yml +73 -0
  5. .github/ISSUE_TEMPLATE/feature_request.md +23 -0
  6. .github/actions/setup-and-build/action.yaml +32 -0
  7. .github/workflows/ci.yaml +27 -0
  8. .github/workflows/docs.yaml +33 -0
  9. .github/workflows/stale.yml +25 -0
  10. .gitignore +39 -0
  11. .husky/pre-commit +20 -0
  12. .prettierignore +2 -0
  13. .prettierrc +8 -0
  14. .tool-versions +2 -0
  15. CONTRIBUTING.md +217 -0
  16. Dockerfile +46 -0
  17. Dockerfile (copy) +83 -0
  18. FAQ.md +54 -0
  19. LICENSE +21 -0
  20. app/components/chat/APIKeyManager.tsx +67 -0
  21. app/components/chat/Artifact.tsx +241 -0
  22. app/components/chat/AssistantMessage.tsx +14 -0
  23. app/components/chat/BaseChat.module.scss +123 -0
  24. app/components/chat/BaseChat.tsx +534 -0
  25. app/components/chat/Chat.client.tsx +358 -0
  26. app/components/chat/CodeBlock.module.scss +10 -0
  27. app/components/chat/CodeBlock.tsx +82 -0
  28. app/components/chat/ExamplePrompts.tsx +36 -0
  29. app/components/chat/FilePreview.tsx +35 -0
  30. app/components/chat/ImportFolderButton.tsx +164 -0
  31. app/components/chat/Markdown.module.scss +171 -0
  32. app/components/chat/Markdown.spec.ts +48 -0
  33. app/components/chat/Markdown.tsx +118 -0
  34. app/components/chat/Messages.client.tsx +106 -0
  35. app/components/chat/ModelSelector.tsx +63 -0
  36. app/components/chat/SendButton.client.tsx +34 -0
  37. app/components/chat/SpeechRecognition.tsx +28 -0
  38. app/components/chat/UserMessage.tsx +53 -0
  39. app/components/chat/chatExportAndImport/ExportChatButton.tsx +13 -0
  40. app/components/chat/chatExportAndImport/ImportButtons.tsx +71 -0
  41. app/components/editor/codemirror/BinaryContent.tsx +7 -0
  42. app/components/editor/codemirror/CodeMirrorEditor.tsx +461 -0
  43. app/components/editor/codemirror/cm-theme.ts +192 -0
  44. app/components/editor/codemirror/indent.ts +68 -0
  45. app/components/editor/codemirror/languages.ts +105 -0
  46. app/components/header/Header.tsx +43 -0
  47. app/components/header/HeaderActionButtons.client.tsx +71 -0
  48. app/components/sidebar/HistoryItem.tsx +127 -0
  49. app/components/sidebar/Menu.client.tsx +209 -0
  50. app/components/sidebar/date-binning.ts +59 -0
.dockerignore ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Ignore Git and GitHub files
2
+ .git
3
+ .github/
4
+
5
+ # Ignore Husky configuration files
6
+ .husky/
7
+
8
+ # Ignore documentation and metadata files
9
+ CONTRIBUTING.md
10
+ LICENSE
11
+ README.md
12
+
13
+ # Ignore environment examples and sensitive info
14
+ .env
15
+ *.local
16
+ *.example
17
+
18
+ # Ignore node modules, logs and cache files
19
+ **/*.log
20
+ **/node_modules
21
+ **/dist
22
+ **/build
23
+ **/.cache
24
+ logs
25
+ dist-ssr
26
+ .DS_Store
.editorconfig ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ root = true
2
+
3
+ [*]
4
+ indent_style = space
5
+ end_of_line = lf
6
+ charset = utf-8
7
+ trim_trailing_whitespace = true
8
+ insert_final_newline = true
9
+ max_line_length = 120
10
+ indent_size = 2
11
+
12
+ [*.md]
13
+ trim_trailing_whitespace = false
.env.example ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Rename this file to .env once you have filled in the below environment variables!
2
+
3
+ # Get your GROQ API Key here -
4
+ # https://console.groq.com/keys
5
+ # You only need this environment variable set if you want to use Groq models
6
+ GROQ_API_KEY=
7
+
8
+ # Get your HuggingFace API Key here -
9
+ # https://huggingface.co/settings/tokens
10
+ # You only need this environment variable set if you want to use HuggingFace models
11
+ HuggingFace_API_KEY=
12
+
13
+
14
+ # Get your Open AI API Key by following these instructions -
15
+ # https://help.openai.com/en/articles/4936850-where-do-i-find-my-openai-api-key
16
+ # You only need this environment variable set if you want to use GPT models
17
+ OPENAI_API_KEY=
18
+
19
+ # Get your Anthropic API Key in your account settings -
20
+ # https://console.anthropic.com/settings/keys
21
+ # You only need this environment variable set if you want to use Claude models
22
+ ANTHROPIC_API_KEY=
23
+
24
+ # Get your OpenRouter API Key in your account settings -
25
+ # https://openrouter.ai/settings/keys
26
+ # You only need this environment variable set if you want to use OpenRouter models
27
+ OPEN_ROUTER_API_KEY=
28
+
29
+ # Get your Google Generative AI API Key by following these instructions -
30
+ # https://console.cloud.google.com/apis/credentials
31
+ # You only need this environment variable set if you want to use Google Generative AI models
32
+ GOOGLE_GENERATIVE_AI_API_KEY=
33
+
34
+ # You only need this environment variable set if you want to use oLLAMA models
35
+ # EXAMPLE http://localhost:11434
36
+ OLLAMA_API_BASE_URL=
37
+
38
+ # You only need this environment variable set if you want to use OpenAI Like models
39
+ OPENAI_LIKE_API_BASE_URL=
40
+
41
+ # You only need this environment variable set if you want to use Together AI models
42
+ TOGETHER_API_BASE_URL=
43
+
44
+ # You only need this environment variable set if you want to use DeepSeek models through their API
45
+ DEEPSEEK_API_KEY=
46
+
47
+ # Get your OpenAI Like API Key
48
+ OPENAI_LIKE_API_KEY=
49
+
50
+ # Get your Together API Key
51
+ TOGETHER_API_KEY=
52
+
53
+ # Get your Mistral API Key by following these instructions -
54
+ # https://console.mistral.ai/api-keys/
55
+ # You only need this environment variable set if you want to use Mistral models
56
+ MISTRAL_API_KEY=
57
+
58
+ # Get the Cohere Api key by following these instructions -
59
+ # https://dashboard.cohere.com/api-keys
60
+ # You only need this environment variable set if you want to use Cohere models
61
+ COHERE_API_KEY=
62
+
63
+ # Get LMStudio Base URL from LM Studio Developer Console
64
+ # Make sure to enable CORS
65
+ # Example: http://localhost:1234
66
+ LMSTUDIO_API_BASE_URL=
67
+
68
+ # Get your xAI API key
69
+ # https://x.ai/api
70
+ # You only need this environment variable set if you want to use xAI models
71
+ XAI_API_KEY=
72
+
73
+ # Include this environment variable if you want more logging for debugging locally
74
+ VITE_LOG_LEVEL=debug
75
+
76
+ # Example Context Values for qwen2.5-coder:32b
77
+ #
78
+ # DEFAULT_NUM_CTX=32768 # Consumes 36GB of VRAM
79
+ # DEFAULT_NUM_CTX=24576 # Consumes 32GB of VRAM
80
+ # DEFAULT_NUM_CTX=12288 # Consumes 26GB of VRAM
81
+ # DEFAULT_NUM_CTX=6144 # Consumes 24GB of VRAM
82
+ DEFAULT_NUM_CTX=
.github/ISSUE_TEMPLATE/bug_report.yml ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: "Bug report"
2
+ description: Create a report to help us improve
3
+ body:
4
+ - type: markdown
5
+ attributes:
6
+ value: |
7
+ Thank you for reporting an issue :pray:.
8
+
9
+ This issue tracker is for bugs and issues found with [Bolt.new](https://bolt.new).
10
+ If you experience issues related to WebContainer, please file an issue in our [WebContainer repo](https://github.com/stackblitz/webcontainer-core), or file an issue in our [StackBlitz core repo](https://github.com/stackblitz/core) for issues with StackBlitz.
11
+
12
+ The more information you fill in, the better we can help you.
13
+ - type: textarea
14
+ id: description
15
+ attributes:
16
+ label: Describe the bug
17
+ description: Provide a clear and concise description of what you're running into.
18
+ validations:
19
+ required: true
20
+ - type: input
21
+ id: link
22
+ attributes:
23
+ label: Link to the Bolt URL that caused the error
24
+ description: Please do not delete it after reporting!
25
+ validations:
26
+ required: true
27
+ - type: textarea
28
+ id: steps
29
+ attributes:
30
+ label: Steps to reproduce
31
+ description: Describe the steps we have to take to reproduce the behavior.
32
+ placeholder: |
33
+ 1. Go to '...'
34
+ 2. Click on '....'
35
+ 3. Scroll down to '....'
36
+ 4. See error
37
+ validations:
38
+ required: true
39
+ - type: textarea
40
+ id: expected
41
+ attributes:
42
+ label: Expected behavior
43
+ description: Provide a clear and concise description of what you expected to happen.
44
+ validations:
45
+ required: true
46
+ - type: textarea
47
+ id: screenshots
48
+ attributes:
49
+ label: Screen Recording / Screenshot
50
+ description: If applicable, **please include a screen recording** (preferably) or screenshot showcasing the issue. This will assist us in resolving your issue <u>quickly</u>.
51
+ - type: textarea
52
+ id: platform
53
+ attributes:
54
+ label: Platform
55
+ value: |
56
+ - OS: [e.g. macOS, Windows, Linux]
57
+ - Browser: [e.g. Chrome, Safari, Firefox]
58
+ - Version: [e.g. 91.1]
59
+ - type: input
60
+ id: provider
61
+ attributes:
62
+ label: Provider Used
63
+ description: Tell us the provider you are using.
64
+ - type: input
65
+ id: model
66
+ attributes:
67
+ label: Model Used
68
+ description: Tell us the model you are using.
69
+ - type: textarea
70
+ id: additional
71
+ attributes:
72
+ label: Additional context
73
+ description: Add any other context about the problem here.
.github/ISSUE_TEMPLATE/feature_request.md ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ name: Feature request
3
+ about: Suggest an idea for this project
4
+ title: ''
5
+ labels: ''
6
+ assignees: ''
7
+ ---
8
+
9
+ **Is your feature request related to a problem? Please describe:**
10
+
11
+ <!-- A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] -->
12
+
13
+ **Describe the solution you'd like:**
14
+
15
+ <!-- A clear and concise description of what you want to happen. -->
16
+
17
+ **Describe alternatives you've considered:**
18
+
19
+ <!-- A clear and concise description of any alternative solutions or features you've considered. -->
20
+
21
+ **Additional context:**
22
+
23
+ <!-- Add any other context or screenshots about the feature request here. -->
.github/actions/setup-and-build/action.yaml ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Setup and Build
2
+ description: Generic setup action
3
+ inputs:
4
+ pnpm-version:
5
+ required: false
6
+ type: string
7
+ default: '9.4.0'
8
+ node-version:
9
+ required: false
10
+ type: string
11
+ default: '20.15.1'
12
+
13
+ runs:
14
+ using: composite
15
+
16
+ steps:
17
+ - uses: pnpm/action-setup@v4
18
+ with:
19
+ version: ${{ inputs.pnpm-version }}
20
+ run_install: false
21
+
22
+ - name: Set Node.js version to ${{ inputs.node-version }}
23
+ uses: actions/setup-node@v4
24
+ with:
25
+ node-version: ${{ inputs.node-version }}
26
+ cache: pnpm
27
+
28
+ - name: Install dependencies and build project
29
+ shell: bash
30
+ run: |
31
+ pnpm install
32
+ pnpm run build
.github/workflows/ci.yaml ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: CI/CD
2
+
3
+ on:
4
+ push:
5
+ branches:
6
+ - master
7
+ pull_request:
8
+
9
+ jobs:
10
+ test:
11
+ name: Test
12
+ runs-on: ubuntu-latest
13
+ steps:
14
+ - name: Checkout
15
+ uses: actions/checkout@v4
16
+
17
+ - name: Setup and Build
18
+ uses: ./.github/actions/setup-and-build
19
+
20
+ - name: Run type check
21
+ run: pnpm run typecheck
22
+
23
+ # - name: Run ESLint
24
+ # run: pnpm run lint
25
+
26
+ - name: Run tests
27
+ run: pnpm run test
.github/workflows/docs.yaml ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Docs CI/CD
2
+
3
+ on:
4
+ push:
5
+ branches:
6
+ - main
7
+ permissions:
8
+ contents: write
9
+ jobs:
10
+ build_docs:
11
+ runs-on: ubuntu-latest
12
+ defaults:
13
+ run:
14
+ working-directory: ./docs
15
+ steps:
16
+ - uses: actions/checkout@v4
17
+ - name: Configure Git Credentials
18
+ run: |
19
+ git config user.name github-actions[bot]
20
+ git config user.email 41898282+github-actions[bot]@users.noreply.github.com
21
+ - uses: actions/setup-python@v5
22
+ with:
23
+ python-version: 3.x
24
+ - run: echo "cache_id=$(date --utc '+%V')" >> $GITHUB_ENV
25
+ - uses: actions/cache@v4
26
+ with:
27
+ key: mkdocs-material-${{ env.cache_id }}
28
+ path: .cache
29
+ restore-keys: |
30
+ mkdocs-material-
31
+
32
+ - run: pip install mkdocs-material
33
+ - run: mkdocs gh-deploy --force
.github/workflows/stale.yml ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Mark Stale Issues and Pull Requests
2
+
3
+ on:
4
+ schedule:
5
+ - cron: '0 2 * * *' # Runs daily at 2:00 AM UTC
6
+ workflow_dispatch: # Allows manual triggering of the workflow
7
+
8
+ jobs:
9
+ stale:
10
+ runs-on: ubuntu-latest
11
+
12
+ steps:
13
+ - name: Mark stale issues and pull requests
14
+ uses: actions/stale@v8
15
+ with:
16
+ repo-token: ${{ secrets.GITHUB_TOKEN }}
17
+ stale-issue-message: "This issue has been marked as stale due to inactivity. If no further activity occurs, it will be closed in 7 days."
18
+ stale-pr-message: "This pull request has been marked as stale due to inactivity. If no further activity occurs, it will be closed in 7 days."
19
+ days-before-stale: 10 # Number of days before marking an issue or PR as stale
20
+ days-before-close: 4 # Number of days after being marked stale before closing
21
+ stale-issue-label: "stale" # Label to apply to stale issues
22
+ stale-pr-label: "stale" # Label to apply to stale pull requests
23
+ exempt-issue-labels: "pinned,important" # Issues with these labels won't be marked stale
24
+ exempt-pr-labels: "pinned,important" # PRs with these labels won't be marked stale
25
+ operations-per-run: 75 # Limits the number of actions per run to avoid API rate limits
.gitignore ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ logs
2
+ *.log
3
+ npm-debug.log*
4
+ yarn-debug.log*
5
+ yarn-error.log*
6
+ pnpm-debug.log*
7
+ lerna-debug.log*
8
+
9
+ node_modules
10
+ dist
11
+ dist-ssr
12
+ *.local
13
+
14
+ .vscode/*
15
+ .vscode/launch.json
16
+ !.vscode/extensions.json
17
+ .idea
18
+ .DS_Store
19
+ *.suo
20
+ *.ntvs*
21
+ *.njsproj
22
+ *.sln
23
+ *.sw?
24
+
25
+ /.history
26
+ /.cache
27
+ /build
28
+ .env.local
29
+ .env
30
+ .dev.vars
31
+ *.vars
32
+ .wrangler
33
+ _worker.bundle
34
+
35
+ Modelfile
36
+ modelfiles
37
+
38
+ # docs ignore
39
+ site
.husky/pre-commit ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/sh
2
+
3
+ echo "🔍 Running pre-commit hook to check the code looks good... 🔍"
4
+
5
+ export NVM_DIR="$HOME/.nvm"
6
+ [ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh" # Load nvm if you're using i
7
+
8
+ if ! pnpm typecheck; then
9
+ echo "❌ Type checking failed! Please review TypeScript types."
10
+ echo "Once you're done, don't forget to add your changes to the commit! 🚀"
11
+ exit 1
12
+ fi
13
+
14
+ if ! pnpm lint; then
15
+ echo "❌ Linting failed! 'pnpm lint:fix' will help you fix the easy ones."
16
+ echo "Once you're done, don't forget to add your beautification to the commit! 🤩"
17
+ exit 1
18
+ fi
19
+
20
+ echo "👍 All good! Committing changes..."
.prettierignore ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ pnpm-lock.yaml
2
+ .astro
.prettierrc ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "printWidth": 120,
3
+ "singleQuote": true,
4
+ "useTabs": false,
5
+ "tabWidth": 2,
6
+ "semi": true,
7
+ "bracketSpacing": true
8
+ }
.tool-versions ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ nodejs 20.15.1
2
+ pnpm 9.4.0
CONTRIBUTING.md ADDED
@@ -0,0 +1,217 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Contributing to oTToDev
2
+
3
+ First off, thank you for considering contributing to oTToDev! This fork aims to expand the capabilities of the original project by integrating multiple LLM providers and enhancing functionality. Every contribution helps make oTToDev a better tool for developers worldwide.
4
+
5
+ ## 📋 Table of Contents
6
+ - [Code of Conduct](#code-of-conduct)
7
+ - [How Can I Contribute?](#how-can-i-contribute)
8
+ - [Pull Request Guidelines](#pull-request-guidelines)
9
+ - [Coding Standards](#coding-standards)
10
+ - [Development Setup](#development-setup)
11
+ - [Deploymnt with Docker](#docker-deployment-documentation)
12
+ - [Project Structure](#project-structure)
13
+
14
+ ## Code of Conduct
15
+
16
+ This project and everyone participating in it is governed by our Code of Conduct. By participating, you are expected to uphold this code. Please report unacceptable behavior to the project maintainers.
17
+
18
+ ## How Can I Contribute?
19
+
20
+ ### 🐞 Reporting Bugs and Feature Requests
21
+ - Check the issue tracker to avoid duplicates
22
+ - Use the issue templates when available
23
+ - Include as much relevant information as possible
24
+ - For bugs, add steps to reproduce the issue
25
+
26
+ ### 🔧 Code Contributions
27
+ 1. Fork the repository
28
+ 2. Create a new branch for your feature/fix
29
+ 3. Write your code
30
+ 4. Submit a pull request
31
+
32
+ ### ✨ Becoming a Core Contributor
33
+ We're looking for dedicated contributors to help maintain and grow this project. If you're interested in becoming a core contributor, please fill out our [Contributor Application Form](https://forms.gle/TBSteXSDCtBDwr5m7).
34
+
35
+ ## Pull Request Guidelines
36
+
37
+ ### 📝 PR Checklist
38
+ - [ ] Branch from the main branch
39
+ - [ ] Update documentation if needed
40
+ - [ ] Manually verify all new functionality works as expected
41
+ - [ ] Keep PRs focused and atomic
42
+
43
+ ### 👀 Review Process
44
+ 1. Manually test the changes
45
+ 2. At least one maintainer review required
46
+ 3. Address all review comments
47
+ 4. Maintain clean commit history
48
+
49
+ ## Coding Standards
50
+
51
+ ### 💻 General Guidelines
52
+ - Follow existing code style
53
+ - Comment complex logic
54
+ - Keep functions focused and small
55
+ - Use meaningful variable names
56
+ - Lint your code. This repo contains a pre-commit-hook that will verify your code is linted properly,
57
+ so set up your IDE to do that for you!
58
+
59
+ ## Development Setup
60
+
61
+ ### 🔄 Initial Setup
62
+ 1. Clone the repository:
63
+ ```bash
64
+ git clone https://github.com/coleam00/bolt.new-any-llm.git
65
+ ```
66
+
67
+ 2. Install dependencies:
68
+ ```bash
69
+ pnpm install
70
+ ```
71
+
72
+ 3. Set up environment variables:
73
+ - Rename `.env.example` to `.env.local`
74
+ - Add your LLM API keys (only set the ones you plan to use):
75
+ ```bash
76
+ GROQ_API_KEY=XXX
77
+ HuggingFace_API_KEY=XXX
78
+ OPENAI_API_KEY=XXX
79
+ ANTHROPIC_API_KEY=XXX
80
+ ...
81
+ ```
82
+ - Optionally set debug level:
83
+ ```bash
84
+ VITE_LOG_LEVEL=debug
85
+ ```
86
+
87
+ - Optionally set context size:
88
+ ```bash
89
+ DEFAULT_NUM_CTX=32768
90
+ ```
91
+
92
+ Some Example Context Values for the qwen2.5-coder:32b models are.
93
+
94
+ * DEFAULT_NUM_CTX=32768 - Consumes 36GB of VRAM
95
+ * DEFAULT_NUM_CTX=24576 - Consumes 32GB of VRAM
96
+ * DEFAULT_NUM_CTX=12288 - Consumes 26GB of VRAM
97
+ * DEFAULT_NUM_CTX=6144 - Consumes 24GB of VRAM
98
+
99
+ **Important**: Never commit your `.env.local` file to version control. It's already included in .gitignore.
100
+
101
+ ### 🚀 Running the Development Server
102
+ ```bash
103
+ pnpm run dev
104
+ ```
105
+
106
+ **Note**: You will need Google Chrome Canary to run this locally if you use Chrome! It's an easy install and a good browser for web development anyway.
107
+
108
+ ## Testing
109
+
110
+ Run the test suite with:
111
+
112
+ ```bash
113
+ pnpm test
114
+ ```
115
+
116
+ ## Deployment
117
+
118
+ To deploy the application to Cloudflare Pages:
119
+
120
+ ```bash
121
+ pnpm run deploy
122
+ ```
123
+
124
+ Make sure you have the necessary permissions and Wrangler is correctly configured for your Cloudflare account.
125
+
126
+ # Docker Deployment Documentation
127
+
128
+ This guide outlines various methods for building and deploying the application using Docker.
129
+
130
+ ## Build Methods
131
+
132
+ ### 1. Using Helper Scripts
133
+
134
+ NPM scripts are provided for convenient building:
135
+
136
+ ```bash
137
+ # Development build
138
+ npm run dockerbuild
139
+
140
+ # Production build
141
+ npm run dockerbuild:prod
142
+ ```
143
+
144
+ ### 2. Direct Docker Build Commands
145
+
146
+ You can use Docker's target feature to specify the build environment:
147
+
148
+ ```bash
149
+ # Development build
150
+ docker build . --target bolt-ai-development
151
+
152
+ # Production build
153
+ docker build . --target bolt-ai-production
154
+ ```
155
+
156
+ ### 3. Docker Compose with Profiles
157
+
158
+ Use Docker Compose profiles to manage different environments:
159
+
160
+ ```bash
161
+ # Development environment
162
+ docker-compose --profile development up
163
+
164
+ # Production environment
165
+ docker-compose --profile production up
166
+ ```
167
+
168
+ ## Running the Application
169
+
170
+ After building using any of the methods above, run the container with:
171
+
172
+ ```bash
173
+ # Development
174
+ docker run -p 5173:5173 --env-file .env.local bolt-ai:development
175
+
176
+ # Production
177
+ docker run -p 5173:5173 --env-file .env.local bolt-ai:production
178
+ ```
179
+
180
+ ## Deployment with Coolify
181
+
182
+ [Coolify](https://github.com/coollabsio/coolify) provides a straightforward deployment process:
183
+
184
+ 1. Import your Git repository as a new project
185
+ 2. Select your target environment (development/production)
186
+ 3. Choose "Docker Compose" as the Build Pack
187
+ 4. Configure deployment domains
188
+ 5. Set the custom start command:
189
+ ```bash
190
+ docker compose --profile production up
191
+ ```
192
+ 6. Configure environment variables
193
+ - Add necessary AI API keys
194
+ - Adjust other environment variables as needed
195
+ 7. Deploy the application
196
+
197
+ ## VS Code Integration
198
+
199
+ The `docker-compose.yaml` configuration is compatible with VS Code dev containers:
200
+
201
+ 1. Open the command palette in VS Code
202
+ 2. Select the dev container configuration
203
+ 3. Choose the "development" profile from the context menu
204
+
205
+ ## Environment Files
206
+
207
+ Ensure you have the appropriate `.env.local` file configured before running the containers. This file should contain:
208
+ - API keys
209
+ - Environment-specific configurations
210
+ - Other required environment variables
211
+
212
+ ## Notes
213
+
214
+ - Port 5173 is exposed and mapped for both development and production environments
215
+ - Environment variables are loaded from `.env.local`
216
+ - Different profiles (development/production) can be used for different deployment scenarios
217
+ - The configuration supports both local development and production deployment
Dockerfile ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ARG BASE=node:20.18.0
2
+ FROM ${BASE} AS base
3
+
4
+ WORKDIR /app
5
+
6
+ # Install dependencies (this step is cached as long as the dependencies don't change)
7
+ COPY package.json pnpm-lock.yaml ./
8
+
9
+ RUN corepack enable pnpm && pnpm install
10
+
11
+ # Copy the rest of your app's source code
12
+ COPY . .
13
+
14
+ # Expose the port the app runs on
15
+ EXPOSE 5173
16
+
17
+ # Development image
18
+ FROM base AS bolt-ai-development
19
+
20
+ # Define the same environment variables for development
21
+ ARG GROQ_API_KEY
22
+ ARG HuggingFace
23
+ ARG OPENAI_API_KEY
24
+ ARG ANTHROPIC_API_KEY
25
+ ARG OPEN_ROUTER_API_KEY
26
+ ARG GOOGLE_GENERATIVE_AI_API_KEY
27
+ ARG OLLAMA_API_BASE_URL
28
+ ARG TOGETHER_API_KEY
29
+ ARG TOGETHER_API_BASE_URL
30
+ ARG VITE_LOG_LEVEL=debug
31
+ ARG DEFAULT_NUM_CTX
32
+
33
+ ENV GROQ_API_KEY=${GROQ_API_KEY} \
34
+ HuggingFace_API_KEY=${HuggingFace_API_KEY} \
35
+ OPENAI_API_KEY=${OPENAI_API_KEY} \
36
+ ANTHROPIC_API_KEY=${ANTHROPIC_API_KEY} \
37
+ OPEN_ROUTER_API_KEY=${OPEN_ROUTER_API_KEY} \
38
+ GOOGLE_GENERATIVE_AI_API_KEY=${GOOGLE_GENERATIVE_AI_API_KEY} \
39
+ OLLAMA_API_BASE_URL=${OLLAMA_API_BASE_URL} \
40
+ TOGETHER_API_KEY=${TOGETHER_API_KEY} \
41
+ TOGETHER_API_BASE_URL=${TOGETHER_API_BASE_URL} \
42
+ VITE_LOG_LEVEL=${VITE_LOG_LEVEL} \
43
+ DEFAULT_NUM_CTX=${DEFAULT_NUM_CTX}
44
+
45
+ RUN mkdir -p ${WORKDIR}/run
46
+ CMD pnpm run dev --host
Dockerfile (copy) ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ARG BASE=node:20.18.0
2
+ FROM ${BASE} AS base
3
+
4
+ WORKDIR /app
5
+
6
+ # Install dependencies (this step is cached as long as the dependencies don't change)
7
+ COPY package.json pnpm-lock.yaml ./
8
+
9
+ RUN corepack enable pnpm && pnpm install
10
+
11
+ # Copy the rest of your app's source code
12
+ COPY . .
13
+
14
+ # Expose the port the app runs on
15
+ EXPOSE 5173
16
+
17
+ # Production image
18
+ FROM base AS bolt-ai-production
19
+
20
+ # Define environment variables with default values or let them be overridden
21
+ ARG GROQ_API_KEY
22
+ ARG HuggingFace_API_KEY
23
+ ARG OPENAI_API_KEY
24
+ ARG ANTHROPIC_API_KEY
25
+ ARG OPEN_ROUTER_API_KEY
26
+ ARG GOOGLE_GENERATIVE_AI_API_KEY
27
+ ARG OLLAMA_API_BASE_URL
28
+ ARG TOGETHER_API_KEY
29
+ ARG TOGETHER_API_BASE_URL
30
+ ARG VITE_LOG_LEVEL=debug
31
+ ARG DEFAULT_NUM_CTX
32
+
33
+ ENV WRANGLER_SEND_METRICS=false \
34
+ GROQ_API_KEY=${GROQ_API_KEY} \
35
+ HuggingFace_KEY=${HuggingFace_API_KEY} \
36
+ OPENAI_API_KEY=${OPENAI_API_KEY} \
37
+ ANTHROPIC_API_KEY=${ANTHROPIC_API_KEY} \
38
+ OPEN_ROUTER_API_KEY=${OPEN_ROUTER_API_KEY} \
39
+ GOOGLE_GENERATIVE_AI_API_KEY=${GOOGLE_GENERATIVE_AI_API_KEY} \
40
+ OLLAMA_API_BASE_URL=${OLLAMA_API_BASE_URL} \
41
+ TOGETHER_API_KEY=${TOGETHER_API_KEY} \
42
+ TOGETHER_API_BASE_URL=${TOGETHER_API_BASE_URL} \
43
+ VITE_LOG_LEVEL=${VITE_LOG_LEVEL} \
44
+ DEFAULT_NUM_CTX=${DEFAULT_NUM_CTX}
45
+
46
+ # Pre-configure wrangler to disable metrics
47
+ RUN mkdir -p /root/.config/.wrangler && \
48
+ echo '{"enabled":false}' > /root/.config/.wrangler/metrics.json
49
+
50
+ RUN npm run build
51
+
52
+ CMD [ "pnpm", "run", "dockerstart"]
53
+
54
+ # Development image
55
+ FROM base AS bolt-ai-development
56
+
57
+ # Define the same environment variables for development
58
+ ARG GROQ_API_KEY
59
+ ARG HuggingFace
60
+ ARG OPENAI_API_KEY
61
+ ARG ANTHROPIC_API_KEY
62
+ ARG OPEN_ROUTER_API_KEY
63
+ ARG GOOGLE_GENERATIVE_AI_API_KEY
64
+ ARG OLLAMA_API_BASE_URL
65
+ ARG TOGETHER_API_KEY
66
+ ARG TOGETHER_API_BASE_URL
67
+ ARG VITE_LOG_LEVEL=debug
68
+ ARG DEFAULT_NUM_CTX
69
+
70
+ ENV GROQ_API_KEY=${GROQ_API_KEY} \
71
+ HuggingFace_API_KEY=${HuggingFace_API_KEY} \
72
+ OPENAI_API_KEY=${OPENAI_API_KEY} \
73
+ ANTHROPIC_API_KEY=${ANTHROPIC_API_KEY} \
74
+ OPEN_ROUTER_API_KEY=${OPEN_ROUTER_API_KEY} \
75
+ GOOGLE_GENERATIVE_AI_API_KEY=${GOOGLE_GENERATIVE_AI_API_KEY} \
76
+ OLLAMA_API_BASE_URL=${OLLAMA_API_BASE_URL} \
77
+ TOGETHER_API_KEY=${TOGETHER_API_KEY} \
78
+ TOGETHER_API_BASE_URL=${TOGETHER_API_BASE_URL} \
79
+ VITE_LOG_LEVEL=${VITE_LOG_LEVEL} \
80
+ DEFAULT_NUM_CTX=${DEFAULT_NUM_CTX}
81
+
82
+ RUN mkdir -p ${WORKDIR}/run
83
+ CMD pnpm run dev --host
FAQ.md ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [![Bolt.new: AI-Powered Full-Stack Web Development in the Browser](./public/social_preview_index.jpg)](https://bolt.new)
2
+
3
+ # Bolt.new Fork by Cole Medin - oTToDev
4
+
5
+ ## FAQ
6
+
7
+ ### How do I get the best results with oTToDev?
8
+
9
+ - **Be specific about your stack**: If you want to use specific frameworks or libraries (like Astro, Tailwind, ShadCN, or any other popular JavaScript framework), mention them in your initial prompt to ensure Bolt scaffolds the project accordingly.
10
+
11
+ - **Use the enhance prompt icon**: Before sending your prompt, try clicking the 'enhance' icon to have the AI model help you refine your prompt, then edit the results before submitting.
12
+
13
+ - **Scaffold the basics first, then add features**: Make sure the basic structure of your application is in place before diving into more advanced functionality. This helps oTToDev understand the foundation of your project and ensure everything is wired up right before building out more advanced functionality.
14
+
15
+ - **Batch simple instructions**: Save time by combining simple instructions into one message. For example, you can ask oTToDev to change the color scheme, add mobile responsiveness, and restart the dev server, all in one go saving you time and reducing API credit consumption significantly.
16
+
17
+ ### Do you plan on merging oTToDev back into the official Bolt.new repo?
18
+
19
+ More news coming on this coming early next month - stay tuned!
20
+
21
+ ### Why are there so many open issues/pull requests?
22
+
23
+ oTToDev was started simply to showcase how to edit an open source project and to do something cool with local LLMs on my (@ColeMedin) YouTube channel! However, it quickly
24
+ grew into a massive community project that I am working hard to keep up with the demand of by forming a team of maintainers and getting as many people involved as I can.
25
+ That effort is going well and all of our maintainers are ABSOLUTE rockstars, but it still takes time to organize everything so we can efficiently get through all
26
+ the issues and PRs. But rest assured, we are working hard and even working on some partnerships behind the scenes to really help this project take off!
27
+
28
+ ### How do local LLMs fair compared to larger models like Claude 3.5 Sonnet for oTToDev/Bolt.new?
29
+
30
+ As much as the gap is quickly closing between open source and massive close source models, you’re still going to get the best results with the very large models like GPT-4o, Claude 3.5 Sonnet, and DeepSeek Coder V2 236b. This is one of the big tasks we have at hand - figuring out how to prompt better, use agents, and improve the platform as a whole to make it work better for even the smaller local LLMs!
31
+
32
+ ### I'm getting the error: "There was an error processing this request"
33
+
34
+ If you see this error within oTToDev, that is just the application telling you there is a problem at a high level, and this could mean a number of different things. To find the actual error, please check BOTH the terminal where you started the application (with Docker or pnpm) and the developer console in the browser. For most browsers, you can access the developer console by pressing F12 or right clicking anywhere in the browser and selecting “Inspect”. Then go to the “console” tab in the top right.
35
+
36
+ ### I'm getting the error: "x-api-key header missing"
37
+
38
+ We have seen this error a couple times and for some reason just restarting the Docker container has fixed it. This seems to be Ollama specific. Another thing to try is try to run oTToDev with Docker or pnpm, whichever you didn’t run first. We are still on the hunt for why this happens once and a while!
39
+
40
+ ### I'm getting a blank preview when oTToDev runs my app!
41
+
42
+ We promise you that we are constantly testing new PRs coming into oTToDev and the preview is core functionality, so the application is not broken! When you get a blank preview or don’t get a preview, this is generally because the LLM hallucinated bad code or incorrect commands. We are working on making this more transparent so it is obvious. Sometimes the error will appear in developer console too so check that as well.
43
+
44
+ ### How to add a LLM:
45
+
46
+ To make new LLMs available to use in this version of Bolt.new, head on over to `app/utils/constants.ts` and find the constant MODEL_LIST. Each element in this array is an object that has the model ID for the name (get this from the provider's API documentation), a label for the frontend model dropdown, and the provider.
47
+
48
+ By default, Anthropic, OpenAI, Groq, and Ollama are implemented as providers, but the YouTube video for this repo covers how to extend this to work with more providers if you wish!
49
+
50
+ When you add a new model to the MODEL_LIST array, it will immediately be available to use when you run the app locally or reload it. For Ollama models, make sure you have the model installed already before trying to use it here!
51
+
52
+ ### Everything works but the results are bad
53
+
54
+ This goes to the point above about how local LLMs are getting very powerful but you still are going to see better (sometimes much better) results with the largest LLMs like GPT-4o, Claude 3.5 Sonnet, and DeepSeek Coder V2 236b. If you are using smaller LLMs like Qwen-2.5-Coder, consider it more experimental and educational at this point. It can build smaller applications really well, which is super impressive for a local LLM, but for larger scale applications you want to use the larger LLMs still!
LICENSE ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ MIT License
2
+
3
+ Copyright (c) 2024 StackBlitz, Inc.
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
app/components/chat/APIKeyManager.tsx ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import React, { useState } from 'react';
2
+ import { IconButton } from '~/components/ui/IconButton';
3
+ import type { ProviderInfo } from '~/types/model';
4
+
5
+ interface APIKeyManagerProps {
6
+ provider: ProviderInfo;
7
+ apiKey: string;
8
+ setApiKey: (key: string) => void;
9
+ getApiKeyLink?: string;
10
+ labelForGetApiKey?: string;
11
+ }
12
+
13
+ // eslint-disable-next-line @typescript-eslint/naming-convention
14
+ export const APIKeyManager: React.FC<APIKeyManagerProps> = ({ provider, apiKey, setApiKey }) => {
15
+ const [isEditing, setIsEditing] = useState(false);
16
+ const [tempKey, setTempKey] = useState(apiKey);
17
+
18
+ const handleSave = () => {
19
+ setApiKey(tempKey);
20
+ setIsEditing(false);
21
+ };
22
+
23
+ return (
24
+ <div className="flex items-start sm:items-center mt-2 mb-2 flex-col sm:flex-row">
25
+ <div>
26
+ <span className="text-sm text-bolt-elements-textSecondary">{provider?.name} API Key:</span>
27
+ {!isEditing && (
28
+ <div className="flex items-center mb-4">
29
+ <span className="flex-1 text-xs text-bolt-elements-textPrimary mr-2">
30
+ {apiKey ? '••••••••' : 'Not set (will still work if set in .env file)'}
31
+ </span>
32
+ <IconButton onClick={() => setIsEditing(true)} title="Edit API Key">
33
+ <div className="i-ph:pencil-simple" />
34
+ </IconButton>
35
+ </div>
36
+ )}
37
+ </div>
38
+
39
+ {isEditing ? (
40
+ <div className="flex items-center gap-3 mt-2">
41
+ <input
42
+ type="password"
43
+ value={tempKey}
44
+ placeholder="Your API Key"
45
+ onChange={(e) => setTempKey(e.target.value)}
46
+ className="flex-1 px-2 py-1 text-xs lg:text-sm rounded border border-bolt-elements-borderColor bg-bolt-elements-prompt-background text-bolt-elements-textPrimary focus:outline-none focus:ring-2 focus:ring-bolt-elements-focus"
47
+ />
48
+ <IconButton onClick={handleSave} title="Save API Key">
49
+ <div className="i-ph:check" />
50
+ </IconButton>
51
+ <IconButton onClick={() => setIsEditing(false)} title="Cancel">
52
+ <div className="i-ph:x" />
53
+ </IconButton>
54
+ </div>
55
+ ) : (
56
+ <>
57
+ {provider?.getApiKeyLink && (
58
+ <IconButton className="ml-auto" onClick={() => window.open(provider?.getApiKeyLink)} title="Edit API Key">
59
+ <span className="mr-2 text-xs lg:text-sm">{provider?.labelForGetApiKey || 'Get API Key'}</span>
60
+ <div className={provider?.icon || 'i-ph:key'} />
61
+ </IconButton>
62
+ )}
63
+ </>
64
+ )}
65
+ </div>
66
+ );
67
+ };
app/components/chat/Artifact.tsx ADDED
@@ -0,0 +1,241 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { useStore } from '@nanostores/react';
2
+ import { AnimatePresence, motion } from 'framer-motion';
3
+ import { computed } from 'nanostores';
4
+ import { memo, useEffect, useRef, useState } from 'react';
5
+ import { createHighlighter, type BundledLanguage, type BundledTheme, type HighlighterGeneric } from 'shiki';
6
+ import type { ActionState } from '~/lib/runtime/action-runner';
7
+ import { workbenchStore } from '~/lib/stores/workbench';
8
+ import { classNames } from '~/utils/classNames';
9
+ import { cubicEasingFn } from '~/utils/easings';
10
+ import { WORK_DIR } from '~/utils/constants';
11
+
12
+ const highlighterOptions = {
13
+ langs: ['shell'],
14
+ themes: ['light-plus', 'dark-plus'],
15
+ };
16
+
17
+ const shellHighlighter: HighlighterGeneric<BundledLanguage, BundledTheme> =
18
+ import.meta.hot?.data.shellHighlighter ?? (await createHighlighter(highlighterOptions));
19
+
20
+ if (import.meta.hot) {
21
+ import.meta.hot.data.shellHighlighter = shellHighlighter;
22
+ }
23
+
24
+ interface ArtifactProps {
25
+ messageId: string;
26
+ }
27
+
28
+ export const Artifact = memo(({ messageId }: ArtifactProps) => {
29
+ const userToggledActions = useRef(false);
30
+ const [showActions, setShowActions] = useState(false);
31
+
32
+ const artifacts = useStore(workbenchStore.artifacts);
33
+ const artifact = artifacts[messageId];
34
+
35
+ const actions = useStore(
36
+ computed(artifact.runner.actions, (actions) => {
37
+ return Object.values(actions);
38
+ }),
39
+ );
40
+
41
+ const toggleActions = () => {
42
+ userToggledActions.current = true;
43
+ setShowActions(!showActions);
44
+ };
45
+
46
+ useEffect(() => {
47
+ if (actions.length && !showActions && !userToggledActions.current) {
48
+ setShowActions(true);
49
+ }
50
+ }, [actions]);
51
+
52
+ return (
53
+ <div className="artifact border border-bolt-elements-borderColor flex flex-col overflow-hidden rounded-lg w-full transition-border duration-150">
54
+ <div className="flex">
55
+ <button
56
+ className="flex items-stretch bg-bolt-elements-artifacts-background hover:bg-bolt-elements-artifacts-backgroundHover w-full overflow-hidden"
57
+ onClick={() => {
58
+ const showWorkbench = workbenchStore.showWorkbench.get();
59
+ workbenchStore.showWorkbench.set(!showWorkbench);
60
+ }}
61
+ >
62
+ <div className="px-5 p-3.5 w-full text-left">
63
+ <div className="w-full text-bolt-elements-textPrimary font-medium leading-5 text-sm">{artifact?.title}</div>
64
+ <div className="w-full w-full text-bolt-elements-textSecondary text-xs mt-0.5">Click to open Workbench</div>
65
+ </div>
66
+ </button>
67
+ <div className="bg-bolt-elements-artifacts-borderColor w-[1px]" />
68
+ <AnimatePresence>
69
+ {actions.length && (
70
+ <motion.button
71
+ initial={{ width: 0 }}
72
+ animate={{ width: 'auto' }}
73
+ exit={{ width: 0 }}
74
+ transition={{ duration: 0.15, ease: cubicEasingFn }}
75
+ className="bg-bolt-elements-artifacts-background hover:bg-bolt-elements-artifacts-backgroundHover"
76
+ onClick={toggleActions}
77
+ >
78
+ <div className="p-4">
79
+ <div className={showActions ? 'i-ph:caret-up-bold' : 'i-ph:caret-down-bold'}></div>
80
+ </div>
81
+ </motion.button>
82
+ )}
83
+ </AnimatePresence>
84
+ </div>
85
+ <AnimatePresence>
86
+ {showActions && actions.length > 0 && (
87
+ <motion.div
88
+ className="actions"
89
+ initial={{ height: 0 }}
90
+ animate={{ height: 'auto' }}
91
+ exit={{ height: '0px' }}
92
+ transition={{ duration: 0.15 }}
93
+ >
94
+ <div className="bg-bolt-elements-artifacts-borderColor h-[1px]" />
95
+ <div className="p-5 text-left bg-bolt-elements-actions-background">
96
+ <ActionList actions={actions} />
97
+ </div>
98
+ </motion.div>
99
+ )}
100
+ </AnimatePresence>
101
+ </div>
102
+ );
103
+ });
104
+
105
+ interface ShellCodeBlockProps {
106
+ classsName?: string;
107
+ code: string;
108
+ }
109
+
110
+ function ShellCodeBlock({ classsName, code }: ShellCodeBlockProps) {
111
+ return (
112
+ <div
113
+ className={classNames('text-xs', classsName)}
114
+ dangerouslySetInnerHTML={{
115
+ __html: shellHighlighter.codeToHtml(code, {
116
+ lang: 'shell',
117
+ theme: 'dark-plus',
118
+ }),
119
+ }}
120
+ ></div>
121
+ );
122
+ }
123
+
124
+ interface ActionListProps {
125
+ actions: ActionState[];
126
+ }
127
+
128
+ const actionVariants = {
129
+ hidden: { opacity: 0, y: 20 },
130
+ visible: { opacity: 1, y: 0 },
131
+ };
132
+
133
+ function openArtifactInWorkbench(filePath: any) {
134
+ if (workbenchStore.currentView.get() !== 'code') {
135
+ workbenchStore.currentView.set('code');
136
+ }
137
+
138
+ workbenchStore.setSelectedFile(`${WORK_DIR}/${filePath}`);
139
+ }
140
+
141
+ const ActionList = memo(({ actions }: ActionListProps) => {
142
+ return (
143
+ <motion.div initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }} transition={{ duration: 0.15 }}>
144
+ <ul className="list-none space-y-2.5">
145
+ {actions.map((action, index) => {
146
+ const { status, type, content } = action;
147
+ const isLast = index === actions.length - 1;
148
+
149
+ return (
150
+ <motion.li
151
+ key={index}
152
+ variants={actionVariants}
153
+ initial="hidden"
154
+ animate="visible"
155
+ transition={{
156
+ duration: 0.2,
157
+ ease: cubicEasingFn,
158
+ }}
159
+ >
160
+ <div className="flex items-center gap-1.5 text-sm">
161
+ <div className={classNames('text-lg', getIconColor(action.status))}>
162
+ {status === 'running' ? (
163
+ <>
164
+ {type !== 'start' ? (
165
+ <div className="i-svg-spinners:90-ring-with-bg"></div>
166
+ ) : (
167
+ <div className="i-ph:terminal-window-duotone"></div>
168
+ )}
169
+ </>
170
+ ) : status === 'pending' ? (
171
+ <div className="i-ph:circle-duotone"></div>
172
+ ) : status === 'complete' ? (
173
+ <div className="i-ph:check"></div>
174
+ ) : status === 'failed' || status === 'aborted' ? (
175
+ <div className="i-ph:x"></div>
176
+ ) : null}
177
+ </div>
178
+ {type === 'file' ? (
179
+ <div>
180
+ Create{' '}
181
+ <code
182
+ className="bg-bolt-elements-artifacts-inlineCode-background text-bolt-elements-artifacts-inlineCode-text px-1.5 py-1 rounded-md text-bolt-elements-item-contentAccent hover:underline cursor-pointer"
183
+ onClick={() => openArtifactInWorkbench(action.filePath)}
184
+ >
185
+ {action.filePath}
186
+ </code>
187
+ </div>
188
+ ) : type === 'shell' ? (
189
+ <div className="flex items-center w-full min-h-[28px]">
190
+ <span className="flex-1">Run command</span>
191
+ </div>
192
+ ) : type === 'start' ? (
193
+ <a
194
+ onClick={(e) => {
195
+ e.preventDefault();
196
+ workbenchStore.currentView.set('preview');
197
+ }}
198
+ className="flex items-center w-full min-h-[28px]"
199
+ >
200
+ <span className="flex-1">Start Application</span>
201
+ </a>
202
+ ) : null}
203
+ </div>
204
+ {(type === 'shell' || type === 'start') && (
205
+ <ShellCodeBlock
206
+ classsName={classNames('mt-1', {
207
+ 'mb-3.5': !isLast,
208
+ })}
209
+ code={content}
210
+ />
211
+ )}
212
+ </motion.li>
213
+ );
214
+ })}
215
+ </ul>
216
+ </motion.div>
217
+ );
218
+ });
219
+
220
+ function getIconColor(status: ActionState['status']) {
221
+ switch (status) {
222
+ case 'pending': {
223
+ return 'text-bolt-elements-textTertiary';
224
+ }
225
+ case 'running': {
226
+ return 'text-bolt-elements-loader-progress';
227
+ }
228
+ case 'complete': {
229
+ return 'text-bolt-elements-icon-success';
230
+ }
231
+ case 'aborted': {
232
+ return 'text-bolt-elements-textSecondary';
233
+ }
234
+ case 'failed': {
235
+ return 'text-bolt-elements-icon-error';
236
+ }
237
+ default: {
238
+ return undefined;
239
+ }
240
+ }
241
+ }
app/components/chat/AssistantMessage.tsx ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { memo } from 'react';
2
+ import { Markdown } from './Markdown';
3
+
4
+ interface AssistantMessageProps {
5
+ content: string;
6
+ }
7
+
8
+ export const AssistantMessage = memo(({ content }: AssistantMessageProps) => {
9
+ return (
10
+ <div className="overflow-hidden w-full">
11
+ <Markdown html>{content}</Markdown>
12
+ </div>
13
+ );
14
+ });
app/components/chat/BaseChat.module.scss ADDED
@@ -0,0 +1,123 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ .BaseChat {
2
+ &[data-chat-visible='false'] {
3
+ --workbench-inner-width: 100%;
4
+ --workbench-left: 0;
5
+
6
+ .Chat {
7
+ --at-apply: bolt-ease-cubic-bezier;
8
+ transition-property: transform, opacity;
9
+ transition-duration: 0.3s;
10
+ will-change: transform, opacity;
11
+ transform: translateX(-50%);
12
+ opacity: 0;
13
+ }
14
+ }
15
+ }
16
+
17
+ .Chat {
18
+ opacity: 1;
19
+ }
20
+
21
+ .RayContainer {
22
+ --gradient-opacity: 0.85;
23
+ --ray-gradient: radial-gradient(rgba(83, 196, 255, var(--gradient-opacity)) 0%, rgba(43, 166, 255, 0) 100%);
24
+ transition: opacity 0.25s linear;
25
+ position: fixed;
26
+ inset: 0;
27
+ pointer-events: none;
28
+ user-select: none;
29
+ }
30
+
31
+ .LightRayOne {
32
+ width: 480px;
33
+ height: 680px;
34
+ transform: rotate(80deg);
35
+ top: -540px;
36
+ left: 250px;
37
+ filter: blur(110px);
38
+ position: absolute;
39
+ border-radius: 100%;
40
+ background: var(--ray-gradient);
41
+ }
42
+
43
+ .LightRayTwo {
44
+ width: 110px;
45
+ height: 400px;
46
+ transform: rotate(-20deg);
47
+ top: -280px;
48
+ left: 350px;
49
+ mix-blend-mode: overlay;
50
+ opacity: 0.6;
51
+ filter: blur(60px);
52
+ position: absolute;
53
+ border-radius: 100%;
54
+ background: var(--ray-gradient);
55
+ }
56
+
57
+ .LightRayThree {
58
+ width: 400px;
59
+ height: 370px;
60
+ top: -350px;
61
+ left: 200px;
62
+ mix-blend-mode: overlay;
63
+ opacity: 0.6;
64
+ filter: blur(21px);
65
+ position: absolute;
66
+ border-radius: 100%;
67
+ background: var(--ray-gradient);
68
+ }
69
+
70
+ .LightRayFour {
71
+ position: absolute;
72
+ width: 330px;
73
+ height: 370px;
74
+ top: -330px;
75
+ left: 50px;
76
+ mix-blend-mode: overlay;
77
+ opacity: 0.5;
78
+ filter: blur(21px);
79
+ border-radius: 100%;
80
+ background: var(--ray-gradient);
81
+ }
82
+
83
+ .LightRayFive {
84
+ position: absolute;
85
+ width: 110px;
86
+ height: 400px;
87
+ transform: rotate(-40deg);
88
+ top: -280px;
89
+ left: -10px;
90
+ mix-blend-mode: overlay;
91
+ opacity: 0.8;
92
+ filter: blur(60px);
93
+ border-radius: 100%;
94
+ background: var(--ray-gradient);
95
+ }
96
+
97
+ .PromptEffectContainer {
98
+ --prompt-container-offset: 50px;
99
+ --prompt-line-stroke-width: 1px;
100
+ position: absolute;
101
+ pointer-events: none;
102
+ inset: calc(var(--prompt-container-offset) / -2);
103
+ width: calc(100% + var(--prompt-container-offset));
104
+ height: calc(100% + var(--prompt-container-offset));
105
+ }
106
+
107
+ .PromptEffectLine {
108
+ width: calc(100% - var(--prompt-container-offset) + var(--prompt-line-stroke-width));
109
+ height: calc(100% - var(--prompt-container-offset) + var(--prompt-line-stroke-width));
110
+ x: calc(var(--prompt-container-offset) / 2 - var(--prompt-line-stroke-width) / 2);
111
+ y: calc(var(--prompt-container-offset) / 2 - var(--prompt-line-stroke-width) / 2);
112
+ rx: calc(8px - var(--prompt-line-stroke-width));
113
+ fill: transparent;
114
+ stroke-width: var(--prompt-line-stroke-width);
115
+ stroke: url(#line-gradient);
116
+ stroke-dasharray: 35px 65px;
117
+ stroke-dashoffset: 10;
118
+ }
119
+
120
+ .PromptShine {
121
+ fill: url(#shine-gradient);
122
+ mix-blend-mode: overlay;
123
+ }
app/components/chat/BaseChat.tsx ADDED
@@ -0,0 +1,534 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * @ts-nocheck
3
+ * Preventing TS checks with files presented in the video for a better presentation.
4
+ */
5
+ import type { Message } from 'ai';
6
+ import React, { type RefCallback, useEffect, useState } from 'react';
7
+ import { ClientOnly } from 'remix-utils/client-only';
8
+ import { Menu } from '~/components/sidebar/Menu.client';
9
+ import { IconButton } from '~/components/ui/IconButton';
10
+ import { Workbench } from '~/components/workbench/Workbench.client';
11
+ import { classNames } from '~/utils/classNames';
12
+ import { MODEL_LIST, PROVIDER_LIST, initializeModelList } from '~/utils/constants';
13
+ import { Messages } from './Messages.client';
14
+ import { SendButton } from './SendButton.client';
15
+ import { APIKeyManager } from './APIKeyManager';
16
+ import Cookies from 'js-cookie';
17
+ import * as Tooltip from '@radix-ui/react-tooltip';
18
+
19
+ import styles from './BaseChat.module.scss';
20
+ import type { ProviderInfo } from '~/utils/types';
21
+ import { ExportChatButton } from '~/components/chat/chatExportAndImport/ExportChatButton';
22
+ import { ImportButtons } from '~/components/chat/chatExportAndImport/ImportButtons';
23
+ import { ExamplePrompts } from '~/components/chat/ExamplePrompts';
24
+
25
+ import FilePreview from './FilePreview';
26
+ import { ModelSelector } from '~/components/chat/ModelSelector';
27
+ import { SpeechRecognitionButton } from '~/components/chat/SpeechRecognition';
28
+
29
+ const TEXTAREA_MIN_HEIGHT = 76;
30
+
31
+ interface BaseChatProps {
32
+ textareaRef?: React.RefObject<HTMLTextAreaElement> | undefined;
33
+ messageRef?: RefCallback<HTMLDivElement> | undefined;
34
+ scrollRef?: RefCallback<HTMLDivElement> | undefined;
35
+ showChat?: boolean;
36
+ chatStarted?: boolean;
37
+ isStreaming?: boolean;
38
+ messages?: Message[];
39
+ description?: string;
40
+ enhancingPrompt?: boolean;
41
+ promptEnhanced?: boolean;
42
+ input?: string;
43
+ model?: string;
44
+ setModel?: (model: string) => void;
45
+ provider?: ProviderInfo;
46
+ setProvider?: (provider: ProviderInfo) => void;
47
+ handleStop?: () => void;
48
+ sendMessage?: (event: React.UIEvent, messageInput?: string) => void;
49
+ handleInputChange?: (event: React.ChangeEvent<HTMLTextAreaElement>) => void;
50
+ enhancePrompt?: () => void;
51
+ importChat?: (description: string, messages: Message[]) => Promise<void>;
52
+ exportChat?: () => void;
53
+ uploadedFiles?: File[];
54
+ setUploadedFiles?: (files: File[]) => void;
55
+ imageDataList?: string[];
56
+ setImageDataList?: (dataList: string[]) => void;
57
+ }
58
+
59
+ export const BaseChat = React.forwardRef<HTMLDivElement, BaseChatProps>(
60
+ (
61
+ {
62
+ textareaRef,
63
+ messageRef,
64
+ scrollRef,
65
+ showChat = true,
66
+ chatStarted = false,
67
+ isStreaming = false,
68
+ model,
69
+ setModel,
70
+ provider,
71
+ setProvider,
72
+ input = '',
73
+ enhancingPrompt,
74
+ handleInputChange,
75
+ promptEnhanced,
76
+ enhancePrompt,
77
+ sendMessage,
78
+ handleStop,
79
+ importChat,
80
+ exportChat,
81
+ uploadedFiles = [],
82
+ setUploadedFiles,
83
+ imageDataList = [],
84
+ setImageDataList,
85
+ messages,
86
+ },
87
+ ref,
88
+ ) => {
89
+ const TEXTAREA_MAX_HEIGHT = chatStarted ? 400 : 200;
90
+ const [apiKeys, setApiKeys] = useState<Record<string, string>>({});
91
+ const [modelList, setModelList] = useState(MODEL_LIST);
92
+ const [isModelSettingsCollapsed, setIsModelSettingsCollapsed] = useState(false);
93
+ const [isListening, setIsListening] = useState(false);
94
+ const [recognition, setRecognition] = useState<SpeechRecognition | null>(null);
95
+ const [transcript, setTranscript] = useState('');
96
+
97
+ console.log(transcript);
98
+ useEffect(() => {
99
+ // Load API keys from cookies on component mount
100
+ try {
101
+ const storedApiKeys = Cookies.get('apiKeys');
102
+
103
+ if (storedApiKeys) {
104
+ const parsedKeys = JSON.parse(storedApiKeys);
105
+
106
+ if (typeof parsedKeys === 'object' && parsedKeys !== null) {
107
+ setApiKeys(parsedKeys);
108
+ }
109
+ }
110
+ } catch (error) {
111
+ console.error('Error loading API keys from cookies:', error);
112
+
113
+ // Clear invalid cookie data
114
+ Cookies.remove('apiKeys');
115
+ }
116
+
117
+ initializeModelList().then((modelList) => {
118
+ setModelList(modelList);
119
+ });
120
+
121
+ if (typeof window !== 'undefined' && ('SpeechRecognition' in window || 'webkitSpeechRecognition' in window)) {
122
+ const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;
123
+ const recognition = new SpeechRecognition();
124
+ recognition.continuous = true;
125
+ recognition.interimResults = true;
126
+
127
+ recognition.onresult = (event) => {
128
+ const transcript = Array.from(event.results)
129
+ .map((result) => result[0])
130
+ .map((result) => result.transcript)
131
+ .join('');
132
+
133
+ setTranscript(transcript);
134
+
135
+ if (handleInputChange) {
136
+ const syntheticEvent = {
137
+ target: { value: transcript },
138
+ } as React.ChangeEvent<HTMLTextAreaElement>;
139
+ handleInputChange(syntheticEvent);
140
+ }
141
+ };
142
+
143
+ recognition.onerror = (event) => {
144
+ console.error('Speech recognition error:', event.error);
145
+ setIsListening(false);
146
+ };
147
+
148
+ setRecognition(recognition);
149
+ }
150
+ }, []);
151
+
152
+ const startListening = () => {
153
+ if (recognition) {
154
+ recognition.start();
155
+ setIsListening(true);
156
+ }
157
+ };
158
+
159
+ const stopListening = () => {
160
+ if (recognition) {
161
+ recognition.stop();
162
+ setIsListening(false);
163
+ }
164
+ };
165
+
166
+ const handleSendMessage = (event: React.UIEvent, messageInput?: string) => {
167
+ if (sendMessage) {
168
+ sendMessage(event, messageInput);
169
+
170
+ if (recognition) {
171
+ recognition.abort(); // Stop current recognition
172
+ setTranscript(''); // Clear transcript
173
+ setIsListening(false);
174
+
175
+ // Clear the input by triggering handleInputChange with empty value
176
+ if (handleInputChange) {
177
+ const syntheticEvent = {
178
+ target: { value: '' },
179
+ } as React.ChangeEvent<HTMLTextAreaElement>;
180
+ handleInputChange(syntheticEvent);
181
+ }
182
+ }
183
+ }
184
+ };
185
+
186
+ const updateApiKey = (provider: string, key: string) => {
187
+ try {
188
+ const updatedApiKeys = { ...apiKeys, [provider]: key };
189
+ setApiKeys(updatedApiKeys);
190
+
191
+ // Save updated API keys to cookies with 30 day expiry and secure settings
192
+ Cookies.set('apiKeys', JSON.stringify(updatedApiKeys), {
193
+ expires: 30, // 30 days
194
+ secure: true, // Only send over HTTPS
195
+ sameSite: 'strict', // Protect against CSRF
196
+ path: '/', // Accessible across the site
197
+ });
198
+ } catch (error) {
199
+ console.error('Error saving API keys to cookies:', error);
200
+ }
201
+ };
202
+
203
+ const handleFileUpload = () => {
204
+ const input = document.createElement('input');
205
+ input.type = 'file';
206
+ input.accept = 'image/*';
207
+
208
+ input.onchange = async (e) => {
209
+ const file = (e.target as HTMLInputElement).files?.[0];
210
+
211
+ if (file) {
212
+ const reader = new FileReader();
213
+
214
+ reader.onload = (e) => {
215
+ const base64Image = e.target?.result as string;
216
+ setUploadedFiles?.([...uploadedFiles, file]);
217
+ setImageDataList?.([...imageDataList, base64Image]);
218
+ };
219
+ reader.readAsDataURL(file);
220
+ }
221
+ };
222
+
223
+ input.click();
224
+ };
225
+
226
+ const handlePaste = async (e: React.ClipboardEvent) => {
227
+ const items = e.clipboardData?.items;
228
+
229
+ if (!items) {
230
+ return;
231
+ }
232
+
233
+ for (const item of items) {
234
+ if (item.type.startsWith('image/')) {
235
+ e.preventDefault();
236
+
237
+ const file = item.getAsFile();
238
+
239
+ if (file) {
240
+ const reader = new FileReader();
241
+
242
+ reader.onload = (e) => {
243
+ const base64Image = e.target?.result as string;
244
+ setUploadedFiles?.([...uploadedFiles, file]);
245
+ setImageDataList?.([...imageDataList, base64Image]);
246
+ };
247
+ reader.readAsDataURL(file);
248
+ }
249
+
250
+ break;
251
+ }
252
+ }
253
+ };
254
+
255
+ const baseChat = (
256
+ <div
257
+ ref={ref}
258
+ className={classNames(
259
+ styles.BaseChat,
260
+ 'relative flex flex-col lg:flex-row h-full w-full overflow-hidden bg-bolt-elements-background-depth-1',
261
+ )}
262
+ data-chat-visible={showChat}
263
+ >
264
+ <div className={classNames(styles.RayContainer)}>
265
+ <div className={classNames(styles.LightRayOne)}></div>
266
+ <div className={classNames(styles.LightRayTwo)}></div>
267
+ <div className={classNames(styles.LightRayThree)}></div>
268
+ <div className={classNames(styles.LightRayFour)}></div>
269
+ <div className={classNames(styles.LightRayFive)}></div>
270
+ </div>
271
+ <ClientOnly>{() => <Menu />}</ClientOnly>
272
+ <div ref={scrollRef} className="flex flex-col lg:flex-row overflow-y-auto w-full h-full">
273
+ <div className={classNames(styles.Chat, 'flex flex-col flex-grow lg:min-w-[var(--chat-min-width)] h-full')}>
274
+ {!chatStarted && (
275
+ <div id="intro" className="mt-[26vh] max-w-chat mx-auto text-center px-4 lg:px-0">
276
+ <h1 className="text-3xl lg:text-6xl font-bold text-bolt-elements-textPrimary mb-4 animate-fade-in">
277
+ Where ideas begin
278
+ </h1>
279
+ <p className="text-md lg:text-xl mb-8 text-bolt-elements-textSecondary animate-fade-in animation-delay-200">
280
+ Bring ideas to life in seconds or get help on existing projects.
281
+ </p>
282
+ </div>
283
+ )}
284
+ <div
285
+ className={classNames('pt-6 px-2 sm:px-6', {
286
+ 'h-full flex flex-col': chatStarted,
287
+ })}
288
+ >
289
+ <ClientOnly>
290
+ {() => {
291
+ return chatStarted ? (
292
+ <Messages
293
+ ref={messageRef}
294
+ className="flex flex-col w-full flex-1 max-w-chat pb-6 mx-auto z-1"
295
+ messages={messages}
296
+ isStreaming={isStreaming}
297
+ />
298
+ ) : null;
299
+ }}
300
+ </ClientOnly>
301
+ <div
302
+ className={classNames(
303
+ 'bg-bolt-elements-background-depth-2 p-3 rounded-lg border border-bolt-elements-borderColor relative w-full max-w-chat mx-auto z-prompt mb-6',
304
+ {
305
+ 'sticky bottom-2': chatStarted,
306
+ },
307
+ )}
308
+ >
309
+ <svg className={classNames(styles.PromptEffectContainer)}>
310
+ <defs>
311
+ <linearGradient
312
+ id="line-gradient"
313
+ x1="20%"
314
+ y1="0%"
315
+ x2="-14%"
316
+ y2="10%"
317
+ gradientUnits="userSpaceOnUse"
318
+ gradientTransform="rotate(-45)"
319
+ >
320
+ <stop offset="0%" stopColor="#1488fc" stopOpacity="0%"></stop>
321
+ <stop offset="40%" stopColor="#1488fc" stopOpacity="80%"></stop>
322
+ <stop offset="50%" stopColor="#1488fc" stopOpacity="80%"></stop>
323
+ <stop offset="100%" stopColor="#1488fc" stopOpacity="0%"></stop>
324
+ </linearGradient>
325
+ <linearGradient id="shine-gradient">
326
+ <stop offset="0%" stopColor="white" stopOpacity="0%"></stop>
327
+ <stop offset="40%" stopColor="#8adaff" stopOpacity="80%"></stop>
328
+ <stop offset="50%" stopColor="#8adaff" stopOpacity="80%"></stop>
329
+ <stop offset="100%" stopColor="white" stopOpacity="0%"></stop>
330
+ </linearGradient>
331
+ </defs>
332
+ <rect className={classNames(styles.PromptEffectLine)} pathLength="100" strokeLinecap="round"></rect>
333
+ <rect className={classNames(styles.PromptShine)} x="48" y="24" width="70" height="1"></rect>
334
+ </svg>
335
+ <div>
336
+ <div className="flex justify-between items-center mb-2">
337
+ <button
338
+ onClick={() => setIsModelSettingsCollapsed(!isModelSettingsCollapsed)}
339
+ className={classNames('flex items-center gap-2 p-2 rounded-lg transition-all', {
340
+ 'bg-bolt-elements-item-backgroundAccent text-bolt-elements-item-contentAccent':
341
+ isModelSettingsCollapsed,
342
+ 'bg-bolt-elements-item-backgroundDefault text-bolt-elements-item-contentDefault':
343
+ !isModelSettingsCollapsed,
344
+ })}
345
+ >
346
+ <div className={`i-ph:caret-${isModelSettingsCollapsed ? 'right' : 'down'} text-lg`} />
347
+ <span>Model Settings</span>
348
+ </button>
349
+ </div>
350
+
351
+ <div className={isModelSettingsCollapsed ? 'hidden' : ''}>
352
+ <ModelSelector
353
+ key={provider?.name + ':' + modelList.length}
354
+ model={model}
355
+ setModel={setModel}
356
+ modelList={modelList}
357
+ provider={provider}
358
+ setProvider={setProvider}
359
+ providerList={PROVIDER_LIST}
360
+ apiKeys={apiKeys}
361
+ />
362
+ {provider && (
363
+ <APIKeyManager
364
+ provider={provider}
365
+ apiKey={apiKeys[provider.name] || ''}
366
+ setApiKey={(key) => updateApiKey(provider.name, key)}
367
+ />
368
+ )}
369
+ </div>
370
+ </div>
371
+ <FilePreview
372
+ files={uploadedFiles}
373
+ imageDataList={imageDataList}
374
+ onRemove={(index) => {
375
+ setUploadedFiles?.(uploadedFiles.filter((_, i) => i !== index));
376
+ setImageDataList?.(imageDataList.filter((_, i) => i !== index));
377
+ }}
378
+ />
379
+ <div
380
+ className={classNames(
381
+ 'relative shadow-xs border border-bolt-elements-borderColor backdrop-blur rounded-lg',
382
+ )}
383
+ >
384
+ <textarea
385
+ ref={textareaRef}
386
+ className={classNames(
387
+ 'w-full pl-4 pt-4 pr-16 focus:outline-none resize-none text-bolt-elements-textPrimary placeholder-bolt-elements-textTertiary bg-transparent text-sm',
388
+ 'transition-all duration-200',
389
+ 'hover:border-bolt-elements-focus',
390
+ )}
391
+ onDragEnter={(e) => {
392
+ e.preventDefault();
393
+ e.currentTarget.style.border = '2px solid #1488fc';
394
+ }}
395
+ onDragOver={(e) => {
396
+ e.preventDefault();
397
+ e.currentTarget.style.border = '2px solid #1488fc';
398
+ }}
399
+ onDragLeave={(e) => {
400
+ e.preventDefault();
401
+ e.currentTarget.style.border = '1px solid var(--bolt-elements-borderColor)';
402
+ }}
403
+ onDrop={(e) => {
404
+ e.preventDefault();
405
+ e.currentTarget.style.border = '1px solid var(--bolt-elements-borderColor)';
406
+
407
+ const files = Array.from(e.dataTransfer.files);
408
+ files.forEach((file) => {
409
+ if (file.type.startsWith('image/')) {
410
+ const reader = new FileReader();
411
+
412
+ reader.onload = (e) => {
413
+ const base64Image = e.target?.result as string;
414
+ setUploadedFiles?.([...uploadedFiles, file]);
415
+ setImageDataList?.([...imageDataList, base64Image]);
416
+ };
417
+ reader.readAsDataURL(file);
418
+ }
419
+ });
420
+ }}
421
+ onKeyDown={(event) => {
422
+ if (event.key === 'Enter') {
423
+ if (event.shiftKey) {
424
+ return;
425
+ }
426
+
427
+ event.preventDefault();
428
+
429
+ if (isStreaming) {
430
+ handleStop?.();
431
+ return;
432
+ }
433
+
434
+ handleSendMessage?.(event);
435
+ }
436
+ }}
437
+ value={input}
438
+ onChange={(event) => {
439
+ handleInputChange?.(event);
440
+ }}
441
+ onPaste={handlePaste}
442
+ style={{
443
+ minHeight: TEXTAREA_MIN_HEIGHT,
444
+ maxHeight: TEXTAREA_MAX_HEIGHT,
445
+ }}
446
+ placeholder="How can Bolt help you today?"
447
+ translate="no"
448
+ />
449
+ <ClientOnly>
450
+ {() => (
451
+ <SendButton
452
+ show={input.length > 0 || isStreaming || uploadedFiles.length > 0}
453
+ isStreaming={isStreaming}
454
+ onClick={(event) => {
455
+ if (isStreaming) {
456
+ handleStop?.();
457
+ return;
458
+ }
459
+
460
+ if (input.length > 0 || uploadedFiles.length > 0) {
461
+ handleSendMessage?.(event);
462
+ }
463
+ }}
464
+ />
465
+ )}
466
+ </ClientOnly>
467
+ <div className="flex justify-between items-center text-sm p-4 pt-2">
468
+ <div className="flex gap-1 items-center">
469
+ <IconButton title="Upload file" className="transition-all" onClick={() => handleFileUpload()}>
470
+ <div className="i-ph:paperclip text-xl"></div>
471
+ </IconButton>
472
+ <IconButton
473
+ title="Enhance prompt"
474
+ disabled={input.length === 0 || enhancingPrompt}
475
+ className={classNames(
476
+ 'transition-all',
477
+ enhancingPrompt ? 'opacity-100' : '',
478
+ promptEnhanced ? 'text-bolt-elements-item-contentAccent' : '',
479
+ promptEnhanced ? 'pr-1.5' : '',
480
+ promptEnhanced ? 'enabled:hover:bg-bolt-elements-item-backgroundAccent' : '',
481
+ )}
482
+ onClick={() => enhancePrompt?.()}
483
+ >
484
+ {enhancingPrompt ? (
485
+ <>
486
+ <div className="i-svg-spinners:90-ring-with-bg text-bolt-elements-loader-progress text-xl animate-spin"></div>
487
+ <div className="ml-1.5">Enhancing prompt...</div>
488
+ </>
489
+ ) : (
490
+ <>
491
+ <div className="i-bolt:stars text-xl"></div>
492
+ {promptEnhanced && <div className="ml-1.5">Prompt enhanced</div>}
493
+ </>
494
+ )}
495
+ </IconButton>
496
+
497
+ <SpeechRecognitionButton
498
+ isListening={isListening}
499
+ onStart={startListening}
500
+ onStop={stopListening}
501
+ disabled={isStreaming}
502
+ />
503
+ {chatStarted && <ClientOnly>{() => <ExportChatButton exportChat={exportChat} />}</ClientOnly>}
504
+ </div>
505
+ {input.length > 3 ? (
506
+ <div className="text-xs text-bolt-elements-textTertiary">
507
+ Use <kbd className="kdb px-1.5 py-0.5 rounded bg-bolt-elements-background-depth-2">Shift</kbd> +{' '}
508
+ <kbd className="kdb px-1.5 py-0.5 rounded bg-bolt-elements-background-depth-2">Return</kbd> a
509
+ new line
510
+ </div>
511
+ ) : null}
512
+ </div>
513
+ </div>
514
+ </div>
515
+ </div>
516
+ {!chatStarted && ImportButtons(importChat)}
517
+ {!chatStarted &&
518
+ ExamplePrompts((event, messageInput) => {
519
+ if (isStreaming) {
520
+ handleStop?.();
521
+ return;
522
+ }
523
+
524
+ handleSendMessage?.(event, messageInput);
525
+ })}
526
+ </div>
527
+ <ClientOnly>{() => <Workbench chatStarted={chatStarted} isStreaming={isStreaming} />}</ClientOnly>
528
+ </div>
529
+ </div>
530
+ );
531
+
532
+ return <Tooltip.Provider delayDuration={200}>{baseChat}</Tooltip.Provider>;
533
+ },
534
+ );
app/components/chat/Chat.client.tsx ADDED
@@ -0,0 +1,358 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * @ts-nocheck
3
+ * Preventing TS checks with files presented in the video for a better presentation.
4
+ */
5
+ import { useStore } from '@nanostores/react';
6
+ import type { Message } from 'ai';
7
+ import { useChat } from 'ai/react';
8
+ import { useAnimate } from 'framer-motion';
9
+ import { memo, useCallback, useEffect, useRef, useState } from 'react';
10
+ import { cssTransition, toast, ToastContainer } from 'react-toastify';
11
+ import { useMessageParser, usePromptEnhancer, useShortcuts, useSnapScroll } from '~/lib/hooks';
12
+ import { description, useChatHistory } from '~/lib/persistence';
13
+ import { chatStore } from '~/lib/stores/chat';
14
+ import { workbenchStore } from '~/lib/stores/workbench';
15
+ import { DEFAULT_MODEL, DEFAULT_PROVIDER, PROMPT_COOKIE_KEY, PROVIDER_LIST } from '~/utils/constants';
16
+ import { cubicEasingFn } from '~/utils/easings';
17
+ import { createScopedLogger, renderLogger } from '~/utils/logger';
18
+ import { BaseChat } from './BaseChat';
19
+ import Cookies from 'js-cookie';
20
+ import type { ProviderInfo } from '~/utils/types';
21
+ import { debounce } from '~/utils/debounce';
22
+
23
+ const toastAnimation = cssTransition({
24
+ enter: 'animated fadeInRight',
25
+ exit: 'animated fadeOutRight',
26
+ });
27
+
28
+ const logger = createScopedLogger('Chat');
29
+
30
+ export function Chat() {
31
+ renderLogger.trace('Chat');
32
+
33
+ const { ready, initialMessages, storeMessageHistory, importChat, exportChat } = useChatHistory();
34
+ const title = useStore(description);
35
+
36
+ return (
37
+ <>
38
+ {ready && (
39
+ <ChatImpl
40
+ description={title}
41
+ initialMessages={initialMessages}
42
+ exportChat={exportChat}
43
+ storeMessageHistory={storeMessageHistory}
44
+ importChat={importChat}
45
+ />
46
+ )}
47
+ <ToastContainer
48
+ closeButton={({ closeToast }) => {
49
+ return (
50
+ <button className="Toastify__close-button" onClick={closeToast}>
51
+ <div className="i-ph:x text-lg" />
52
+ </button>
53
+ );
54
+ }}
55
+ icon={({ type }) => {
56
+ /**
57
+ * @todo Handle more types if we need them. This may require extra color palettes.
58
+ */
59
+ switch (type) {
60
+ case 'success': {
61
+ return <div className="i-ph:check-bold text-bolt-elements-icon-success text-2xl" />;
62
+ }
63
+ case 'error': {
64
+ return <div className="i-ph:warning-circle-bold text-bolt-elements-icon-error text-2xl" />;
65
+ }
66
+ }
67
+
68
+ return undefined;
69
+ }}
70
+ position="bottom-right"
71
+ pauseOnFocusLoss
72
+ transition={toastAnimation}
73
+ />
74
+ </>
75
+ );
76
+ }
77
+
78
+ interface ChatProps {
79
+ initialMessages: Message[];
80
+ storeMessageHistory: (messages: Message[]) => Promise<void>;
81
+ importChat: (description: string, messages: Message[]) => Promise<void>;
82
+ exportChat: () => void;
83
+ description?: string;
84
+ }
85
+
86
+ export const ChatImpl = memo(
87
+ ({ description, initialMessages, storeMessageHistory, importChat, exportChat }: ChatProps) => {
88
+ useShortcuts();
89
+
90
+ const textareaRef = useRef<HTMLTextAreaElement>(null);
91
+ const [chatStarted, setChatStarted] = useState(initialMessages.length > 0);
92
+ const [uploadedFiles, setUploadedFiles] = useState<File[]>([]); // Move here
93
+ const [imageDataList, setImageDataList] = useState<string[]>([]); // Move here
94
+
95
+ const [model, setModel] = useState(() => {
96
+ const savedModel = Cookies.get('selectedModel');
97
+ return savedModel || DEFAULT_MODEL;
98
+ });
99
+ const [provider, setProvider] = useState(() => {
100
+ const savedProvider = Cookies.get('selectedProvider');
101
+ return PROVIDER_LIST.find((p) => p.name === savedProvider) || DEFAULT_PROVIDER;
102
+ });
103
+
104
+ const { showChat } = useStore(chatStore);
105
+
106
+ const [animationScope, animate] = useAnimate();
107
+
108
+ const [apiKeys, setApiKeys] = useState<Record<string, string>>({});
109
+
110
+ const { messages, isLoading, input, handleInputChange, setInput, stop, append } = useChat({
111
+ api: '/api/chat',
112
+ body: {
113
+ apiKeys,
114
+ },
115
+ onError: (error) => {
116
+ logger.error('Request failed\n\n', error);
117
+ toast.error(
118
+ 'There was an error processing your request: ' + (error.message ? error.message : 'No details were returned'),
119
+ );
120
+ },
121
+ onFinish: () => {
122
+ logger.debug('Finished streaming');
123
+ },
124
+ initialMessages,
125
+ initialInput: Cookies.get(PROMPT_COOKIE_KEY) || '',
126
+ });
127
+
128
+ const { enhancingPrompt, promptEnhanced, enhancePrompt, resetEnhancer } = usePromptEnhancer();
129
+ const { parsedMessages, parseMessages } = useMessageParser();
130
+
131
+ const TEXTAREA_MAX_HEIGHT = chatStarted ? 400 : 200;
132
+
133
+ useEffect(() => {
134
+ chatStore.setKey('started', initialMessages.length > 0);
135
+ }, []);
136
+
137
+ useEffect(() => {
138
+ parseMessages(messages, isLoading);
139
+
140
+ if (messages.length > initialMessages.length) {
141
+ storeMessageHistory(messages).catch((error) => toast.error(error.message));
142
+ }
143
+ }, [messages, isLoading, parseMessages]);
144
+
145
+ const scrollTextArea = () => {
146
+ const textarea = textareaRef.current;
147
+
148
+ if (textarea) {
149
+ textarea.scrollTop = textarea.scrollHeight;
150
+ }
151
+ };
152
+
153
+ const abort = () => {
154
+ stop();
155
+ chatStore.setKey('aborted', true);
156
+ workbenchStore.abortAllActions();
157
+ };
158
+
159
+ useEffect(() => {
160
+ const textarea = textareaRef.current;
161
+
162
+ if (textarea) {
163
+ textarea.style.height = 'auto';
164
+
165
+ const scrollHeight = textarea.scrollHeight;
166
+
167
+ textarea.style.height = `${Math.min(scrollHeight, TEXTAREA_MAX_HEIGHT)}px`;
168
+ textarea.style.overflowY = scrollHeight > TEXTAREA_MAX_HEIGHT ? 'auto' : 'hidden';
169
+ }
170
+ }, [input, textareaRef]);
171
+
172
+ const runAnimation = async () => {
173
+ if (chatStarted) {
174
+ return;
175
+ }
176
+
177
+ await Promise.all([
178
+ animate('#examples', { opacity: 0, display: 'none' }, { duration: 0.1 }),
179
+ animate('#intro', { opacity: 0, flex: 1 }, { duration: 0.2, ease: cubicEasingFn }),
180
+ ]);
181
+
182
+ chatStore.setKey('started', true);
183
+
184
+ setChatStarted(true);
185
+ };
186
+
187
+ const sendMessage = async (_event: React.UIEvent, messageInput?: string) => {
188
+ const _input = messageInput || input;
189
+
190
+ if (_input.length === 0 || isLoading) {
191
+ return;
192
+ }
193
+
194
+ /**
195
+ * @note (delm) Usually saving files shouldn't take long but it may take longer if there
196
+ * many unsaved files. In that case we need to block user input and show an indicator
197
+ * of some kind so the user is aware that something is happening. But I consider the
198
+ * happy case to be no unsaved files and I would expect users to save their changes
199
+ * before they send another message.
200
+ */
201
+ await workbenchStore.saveAllFiles();
202
+
203
+ const fileModifications = workbenchStore.getFileModifcations();
204
+
205
+ chatStore.setKey('aborted', false);
206
+
207
+ runAnimation();
208
+
209
+ if (fileModifications !== undefined) {
210
+ /**
211
+ * If we have file modifications we append a new user message manually since we have to prefix
212
+ * the user input with the file modifications and we don't want the new user input to appear
213
+ * in the prompt. Using `append` is almost the same as `handleSubmit` except that we have to
214
+ * manually reset the input and we'd have to manually pass in file attachments. However, those
215
+ * aren't relevant here.
216
+ */
217
+ append({
218
+ role: 'user',
219
+ content: [
220
+ {
221
+ type: 'text',
222
+ text: `[Model: ${model}]\n\n[Provider: ${provider.name}]\n\n${_input}`,
223
+ },
224
+ ...imageDataList.map((imageData) => ({
225
+ type: 'image',
226
+ image: imageData,
227
+ })),
228
+ ] as any, // Type assertion to bypass compiler check
229
+ });
230
+
231
+ /**
232
+ * After sending a new message we reset all modifications since the model
233
+ * should now be aware of all the changes.
234
+ */
235
+ workbenchStore.resetAllFileModifications();
236
+ } else {
237
+ append({
238
+ role: 'user',
239
+ content: [
240
+ {
241
+ type: 'text',
242
+ text: `[Model: ${model}]\n\n[Provider: ${provider.name}]\n\n${_input}`,
243
+ },
244
+ ...imageDataList.map((imageData) => ({
245
+ type: 'image',
246
+ image: imageData,
247
+ })),
248
+ ] as any, // Type assertion to bypass compiler check
249
+ });
250
+ }
251
+
252
+ setInput('');
253
+ Cookies.remove(PROMPT_COOKIE_KEY);
254
+
255
+ // Add file cleanup here
256
+ setUploadedFiles([]);
257
+ setImageDataList([]);
258
+
259
+ resetEnhancer();
260
+
261
+ textareaRef.current?.blur();
262
+ };
263
+
264
+ /**
265
+ * Handles the change event for the textarea and updates the input state.
266
+ * @param event - The change event from the textarea.
267
+ */
268
+ const onTextareaChange = (event: React.ChangeEvent<HTMLTextAreaElement>) => {
269
+ handleInputChange(event);
270
+ };
271
+
272
+ /**
273
+ * Debounced function to cache the prompt in cookies.
274
+ * Caches the trimmed value of the textarea input after a delay to optimize performance.
275
+ */
276
+ const debouncedCachePrompt = useCallback(
277
+ debounce((event: React.ChangeEvent<HTMLTextAreaElement>) => {
278
+ const trimmedValue = event.target.value.trim();
279
+ Cookies.set(PROMPT_COOKIE_KEY, trimmedValue, { expires: 30 });
280
+ }, 1000),
281
+ [],
282
+ );
283
+
284
+ const [messageRef, scrollRef] = useSnapScroll();
285
+
286
+ useEffect(() => {
287
+ const storedApiKeys = Cookies.get('apiKeys');
288
+
289
+ if (storedApiKeys) {
290
+ setApiKeys(JSON.parse(storedApiKeys));
291
+ }
292
+ }, []);
293
+
294
+ const handleModelChange = (newModel: string) => {
295
+ setModel(newModel);
296
+ Cookies.set('selectedModel', newModel, { expires: 30 });
297
+ };
298
+
299
+ const handleProviderChange = (newProvider: ProviderInfo) => {
300
+ setProvider(newProvider);
301
+ Cookies.set('selectedProvider', newProvider.name, { expires: 30 });
302
+ };
303
+
304
+ return (
305
+ <BaseChat
306
+ ref={animationScope}
307
+ textareaRef={textareaRef}
308
+ input={input}
309
+ showChat={showChat}
310
+ chatStarted={chatStarted}
311
+ isStreaming={isLoading}
312
+ enhancingPrompt={enhancingPrompt}
313
+ promptEnhanced={promptEnhanced}
314
+ sendMessage={sendMessage}
315
+ model={model}
316
+ setModel={handleModelChange}
317
+ provider={provider}
318
+ setProvider={handleProviderChange}
319
+ messageRef={messageRef}
320
+ scrollRef={scrollRef}
321
+ handleInputChange={(e) => {
322
+ onTextareaChange(e);
323
+ debouncedCachePrompt(e);
324
+ }}
325
+ handleStop={abort}
326
+ description={description}
327
+ importChat={importChat}
328
+ exportChat={exportChat}
329
+ messages={messages.map((message, i) => {
330
+ if (message.role === 'user') {
331
+ return message;
332
+ }
333
+
334
+ return {
335
+ ...message,
336
+ content: parsedMessages[i] || '',
337
+ };
338
+ })}
339
+ enhancePrompt={() => {
340
+ enhancePrompt(
341
+ input,
342
+ (input) => {
343
+ setInput(input);
344
+ scrollTextArea();
345
+ },
346
+ model,
347
+ provider,
348
+ apiKeys,
349
+ );
350
+ }}
351
+ uploadedFiles={uploadedFiles}
352
+ setUploadedFiles={setUploadedFiles}
353
+ imageDataList={imageDataList}
354
+ setImageDataList={setImageDataList}
355
+ />
356
+ );
357
+ },
358
+ );
app/components/chat/CodeBlock.module.scss ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ .CopyButtonContainer {
2
+ button:before {
3
+ content: 'Copied';
4
+ font-size: 12px;
5
+ position: absolute;
6
+ left: -53px;
7
+ padding: 2px 6px;
8
+ height: 30px;
9
+ }
10
+ }
app/components/chat/CodeBlock.tsx ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { memo, useEffect, useState } from 'react';
2
+ import { bundledLanguages, codeToHtml, isSpecialLang, type BundledLanguage, type SpecialLanguage } from 'shiki';
3
+ import { classNames } from '~/utils/classNames';
4
+ import { createScopedLogger } from '~/utils/logger';
5
+
6
+ import styles from './CodeBlock.module.scss';
7
+
8
+ const logger = createScopedLogger('CodeBlock');
9
+
10
+ interface CodeBlockProps {
11
+ className?: string;
12
+ code: string;
13
+ language?: BundledLanguage | SpecialLanguage;
14
+ theme?: 'light-plus' | 'dark-plus';
15
+ disableCopy?: boolean;
16
+ }
17
+
18
+ export const CodeBlock = memo(
19
+ ({ className, code, language = 'plaintext', theme = 'dark-plus', disableCopy = false }: CodeBlockProps) => {
20
+ const [html, setHTML] = useState<string | undefined>(undefined);
21
+ const [copied, setCopied] = useState(false);
22
+
23
+ const copyToClipboard = () => {
24
+ if (copied) {
25
+ return;
26
+ }
27
+
28
+ navigator.clipboard.writeText(code);
29
+
30
+ setCopied(true);
31
+
32
+ setTimeout(() => {
33
+ setCopied(false);
34
+ }, 2000);
35
+ };
36
+
37
+ useEffect(() => {
38
+ if (language && !isSpecialLang(language) && !(language in bundledLanguages)) {
39
+ logger.warn(`Unsupported language '${language}'`);
40
+ }
41
+
42
+ logger.trace(`Language = ${language}`);
43
+
44
+ const processCode = async () => {
45
+ setHTML(await codeToHtml(code, { lang: language, theme }));
46
+ };
47
+
48
+ processCode();
49
+ }, [code]);
50
+
51
+ return (
52
+ <div className={classNames('relative group text-left', className)}>
53
+ <div
54
+ className={classNames(
55
+ styles.CopyButtonContainer,
56
+ 'bg-white absolute top-[10px] right-[10px] rounded-md z-10 text-lg flex items-center justify-center opacity-0 group-hover:opacity-100',
57
+ {
58
+ 'rounded-l-0 opacity-100': copied,
59
+ },
60
+ )}
61
+ >
62
+ {!disableCopy && (
63
+ <button
64
+ className={classNames(
65
+ 'flex items-center bg-transparent p-[6px] justify-center before:bg-white before:rounded-l-md before:text-gray-500 before:border-r before:border-gray-300',
66
+ {
67
+ 'before:opacity-0': !copied,
68
+ 'before:opacity-100': copied,
69
+ },
70
+ )}
71
+ title="Copy Code"
72
+ onClick={() => copyToClipboard()}
73
+ >
74
+ <div className="i-ph:clipboard-text-duotone"></div>
75
+ </button>
76
+ )}
77
+ </div>
78
+ <div dangerouslySetInnerHTML={{ __html: html ?? '' }}></div>
79
+ </div>
80
+ );
81
+ },
82
+ );
app/components/chat/ExamplePrompts.tsx ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import React from 'react';
2
+
3
+ const EXAMPLE_PROMPTS = [
4
+ { text: 'Build a todo app in React using Tailwind' },
5
+ { text: 'Build a simple blog using Astro' },
6
+ { text: 'Create a cookie consent form using Material UI' },
7
+ { text: 'Make a space invaders game' },
8
+ { text: 'Make a Tic Tac Toe game in html, css and js only' },
9
+ ];
10
+
11
+ export function ExamplePrompts(sendMessage?: { (event: React.UIEvent, messageInput?: string): void | undefined }) {
12
+ return (
13
+ <div id="examples" className="relative flex flex-col gap-9 w-full max-w-3xl mx-auto flex justify-center mt-6">
14
+ <div
15
+ className="flex flex-wrap justify-center gap-2"
16
+ style={{
17
+ animation: '.25s ease-out 0s 1 _fade-and-move-in_g2ptj_1 forwards',
18
+ }}
19
+ >
20
+ {EXAMPLE_PROMPTS.map((examplePrompt, index: number) => {
21
+ return (
22
+ <button
23
+ key={index}
24
+ onClick={(event) => {
25
+ sendMessage?.(event, examplePrompt.text);
26
+ }}
27
+ className="border border-bolt-elements-borderColor rounded-full bg-gray-50 hover:bg-gray-100 dark:bg-gray-950 dark:hover:bg-gray-900 text-bolt-elements-textSecondary hover:text-bolt-elements-textPrimary px-3 py-1 text-xs transition-theme"
28
+ >
29
+ {examplePrompt.text}
30
+ </button>
31
+ );
32
+ })}
33
+ </div>
34
+ </div>
35
+ );
36
+ }
app/components/chat/FilePreview.tsx ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import React from 'react';
2
+
3
+ interface FilePreviewProps {
4
+ files: File[];
5
+ imageDataList: string[];
6
+ onRemove: (index: number) => void;
7
+ }
8
+
9
+ const FilePreview: React.FC<FilePreviewProps> = ({ files, imageDataList, onRemove }) => {
10
+ if (!files || files.length === 0) {
11
+ return null;
12
+ }
13
+
14
+ return (
15
+ <div className="flex flex-row overflow-x-auto -mt-2">
16
+ {files.map((file, index) => (
17
+ <div key={file.name + file.size} className="mr-2 relative">
18
+ {imageDataList[index] && (
19
+ <div className="relative pt-4 pr-4">
20
+ <img src={imageDataList[index]} alt={file.name} className="max-h-20" />
21
+ <button
22
+ onClick={() => onRemove(index)}
23
+ className="absolute top-1 right-1 z-10 bg-black rounded-full w-5 h-5 shadow-md hover:bg-gray-900 transition-colors flex items-center justify-center"
24
+ >
25
+ <div className="i-ph:x w-3 h-3 text-gray-200" />
26
+ </button>
27
+ </div>
28
+ )}
29
+ </div>
30
+ ))}
31
+ </div>
32
+ );
33
+ };
34
+
35
+ export default FilePreview;
app/components/chat/ImportFolderButton.tsx ADDED
@@ -0,0 +1,164 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import React from 'react';
2
+ import type { Message } from 'ai';
3
+ import { toast } from 'react-toastify';
4
+ import ignore from 'ignore';
5
+
6
+ interface ImportFolderButtonProps {
7
+ className?: string;
8
+ importChat?: (description: string, messages: Message[]) => Promise<void>;
9
+ }
10
+
11
+ // Common patterns to ignore, similar to .gitignore
12
+ const IGNORE_PATTERNS = [
13
+ 'node_modules/**',
14
+ '.git/**',
15
+ 'dist/**',
16
+ 'build/**',
17
+ '.next/**',
18
+ 'coverage/**',
19
+ '.cache/**',
20
+ '.vscode/**',
21
+ '.idea/**',
22
+ '**/*.log',
23
+ '**/.DS_Store',
24
+ '**/npm-debug.log*',
25
+ '**/yarn-debug.log*',
26
+ '**/yarn-error.log*',
27
+ ];
28
+
29
+ const ig = ignore().add(IGNORE_PATTERNS);
30
+ const generateId = () => Math.random().toString(36).substring(2, 15);
31
+
32
+ const isBinaryFile = async (file: File): Promise<boolean> => {
33
+ const chunkSize = 1024; // Read the first 1 KB of the file
34
+ const buffer = new Uint8Array(await file.slice(0, chunkSize).arrayBuffer());
35
+
36
+ for (let i = 0; i < buffer.length; i++) {
37
+ const byte = buffer[i];
38
+
39
+ if (byte === 0 || (byte < 32 && byte !== 9 && byte !== 10 && byte !== 13)) {
40
+ return true; // Found a binary character
41
+ }
42
+ }
43
+
44
+ return false;
45
+ };
46
+
47
+ export const ImportFolderButton: React.FC<ImportFolderButtonProps> = ({ className, importChat }) => {
48
+ const shouldIncludeFile = (path: string): boolean => {
49
+ return !ig.ignores(path);
50
+ };
51
+
52
+ const createChatFromFolder = async (files: File[], binaryFiles: string[]) => {
53
+ const fileArtifacts = await Promise.all(
54
+ files.map(async (file) => {
55
+ return new Promise<string>((resolve, reject) => {
56
+ const reader = new FileReader();
57
+
58
+ reader.onload = () => {
59
+ const content = reader.result as string;
60
+ const relativePath = file.webkitRelativePath.split('/').slice(1).join('/');
61
+ resolve(
62
+ `<boltAction type="file" filePath="${relativePath}">
63
+ ${content}
64
+ </boltAction>`,
65
+ );
66
+ };
67
+ reader.onerror = reject;
68
+ reader.readAsText(file);
69
+ });
70
+ }),
71
+ );
72
+
73
+ const binaryFilesMessage =
74
+ binaryFiles.length > 0
75
+ ? `\n\nSkipped ${binaryFiles.length} binary files:\n${binaryFiles.map((f) => `- ${f}`).join('\n')}`
76
+ : '';
77
+
78
+ const message: Message = {
79
+ role: 'assistant',
80
+ content: `I'll help you set up these files.${binaryFilesMessage}
81
+
82
+ <boltArtifact id="imported-files" title="Imported Files">
83
+ ${fileArtifacts.join('\n\n')}
84
+ </boltArtifact>`,
85
+ id: generateId(),
86
+ createdAt: new Date(),
87
+ };
88
+
89
+ const userMessage: Message = {
90
+ role: 'user',
91
+ id: generateId(),
92
+ content: 'Import my files',
93
+ createdAt: new Date(),
94
+ };
95
+
96
+ const description = `Folder Import: ${files[0].webkitRelativePath.split('/')[0]}`;
97
+
98
+ if (importChat) {
99
+ await importChat(description, [userMessage, message]);
100
+ }
101
+ };
102
+
103
+ return (
104
+ <>
105
+ <input
106
+ type="file"
107
+ id="folder-import"
108
+ className="hidden"
109
+ webkitdirectory=""
110
+ directory=""
111
+ onChange={async (e) => {
112
+ const allFiles = Array.from(e.target.files || []);
113
+ const filteredFiles = allFiles.filter((file) => shouldIncludeFile(file.webkitRelativePath));
114
+
115
+ if (filteredFiles.length === 0) {
116
+ toast.error('No files found in the selected folder');
117
+ return;
118
+ }
119
+
120
+ try {
121
+ const fileChecks = await Promise.all(
122
+ filteredFiles.map(async (file) => ({
123
+ file,
124
+ isBinary: await isBinaryFile(file),
125
+ })),
126
+ );
127
+
128
+ const textFiles = fileChecks.filter((f) => !f.isBinary).map((f) => f.file);
129
+ const binaryFilePaths = fileChecks
130
+ .filter((f) => f.isBinary)
131
+ .map((f) => f.file.webkitRelativePath.split('/').slice(1).join('/'));
132
+
133
+ if (textFiles.length === 0) {
134
+ toast.error('No text files found in the selected folder');
135
+ return;
136
+ }
137
+
138
+ if (binaryFilePaths.length > 0) {
139
+ toast.info(`Skipping ${binaryFilePaths.length} binary files`);
140
+ }
141
+
142
+ await createChatFromFolder(textFiles, binaryFilePaths);
143
+ } catch (error) {
144
+ console.error('Failed to import folder:', error);
145
+ toast.error('Failed to import folder');
146
+ }
147
+
148
+ e.target.value = ''; // Reset file input
149
+ }}
150
+ {...({} as any)} // if removed webkitdirectory will throw errors as unknow attribute
151
+ />
152
+ <button
153
+ onClick={() => {
154
+ const input = document.getElementById('folder-import');
155
+ input?.click();
156
+ }}
157
+ className={className}
158
+ >
159
+ <div className="i-ph:upload-simple" />
160
+ Import Folder
161
+ </button>
162
+ </>
163
+ );
164
+ };
app/components/chat/Markdown.module.scss ADDED
@@ -0,0 +1,171 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ $font-mono: ui-monospace, 'Fira Code', Menlo, Monaco, Consolas, 'Liberation Mono', 'Courier New', monospace;
2
+ $code-font-size: 13px;
3
+
4
+ @mixin not-inside-actions {
5
+ &:not(:has(:global(.actions)), :global(.actions *)) {
6
+ @content;
7
+ }
8
+ }
9
+
10
+ .MarkdownContent {
11
+ line-height: 1.6;
12
+ color: var(--bolt-elements-textPrimary);
13
+
14
+ > *:not(:last-child) {
15
+ margin-block-end: 16px;
16
+ }
17
+
18
+ :global(.artifact) {
19
+ margin: 1.5em 0;
20
+ }
21
+
22
+ :is(h1, h2, h3, h4, h5, h6) {
23
+ @include not-inside-actions {
24
+ margin-block-start: 24px;
25
+ margin-block-end: 16px;
26
+ font-weight: 600;
27
+ line-height: 1.25;
28
+ color: var(--bolt-elements-textPrimary);
29
+ }
30
+ }
31
+
32
+ h1 {
33
+ font-size: 2em;
34
+ border-bottom: 1px solid var(--bolt-elements-borderColor);
35
+ padding-bottom: 0.3em;
36
+ }
37
+
38
+ h2 {
39
+ font-size: 1.5em;
40
+ border-bottom: 1px solid var(--bolt-elements-borderColor);
41
+ padding-bottom: 0.3em;
42
+ }
43
+
44
+ h3 {
45
+ font-size: 1.25em;
46
+ }
47
+
48
+ h4 {
49
+ font-size: 1em;
50
+ }
51
+
52
+ h5 {
53
+ font-size: 0.875em;
54
+ }
55
+
56
+ h6 {
57
+ font-size: 0.85em;
58
+ color: #6a737d;
59
+ }
60
+
61
+ p {
62
+ white-space: pre-wrap;
63
+
64
+ &:not(:last-of-type) {
65
+ margin-block-start: 0;
66
+ margin-block-end: 16px;
67
+ }
68
+ }
69
+
70
+ a {
71
+ color: var(--bolt-elements-messages-linkColor);
72
+ text-decoration: none;
73
+ cursor: pointer;
74
+
75
+ &:hover {
76
+ text-decoration: underline;
77
+ }
78
+ }
79
+
80
+ :not(pre) > code {
81
+ font-family: $font-mono;
82
+ font-size: $code-font-size;
83
+
84
+ @include not-inside-actions {
85
+ border-radius: 6px;
86
+ padding: 0.2em 0.4em;
87
+ background-color: var(--bolt-elements-messages-inlineCode-background);
88
+ color: var(--bolt-elements-messages-inlineCode-text);
89
+ }
90
+ }
91
+
92
+ pre {
93
+ padding: 20px 16px;
94
+ border-radius: 6px;
95
+ }
96
+
97
+ pre:has(> code) {
98
+ font-family: $font-mono;
99
+ font-size: $code-font-size;
100
+ background: transparent;
101
+ overflow-x: auto;
102
+ min-width: 0;
103
+ }
104
+
105
+ blockquote {
106
+ margin: 0;
107
+ padding: 0 1em;
108
+ color: var(--bolt-elements-textTertiary);
109
+ border-left: 0.25em solid var(--bolt-elements-borderColor);
110
+ }
111
+
112
+ :is(ul, ol) {
113
+ @include not-inside-actions {
114
+ padding-left: 2em;
115
+ margin-block-start: 0;
116
+ margin-block-end: 16px;
117
+ }
118
+ }
119
+
120
+ ul {
121
+ @include not-inside-actions {
122
+ list-style-type: disc;
123
+ }
124
+ }
125
+
126
+ ol {
127
+ @include not-inside-actions {
128
+ list-style-type: decimal;
129
+ }
130
+ }
131
+
132
+ li {
133
+ @include not-inside-actions {
134
+ & + li {
135
+ margin-block-start: 8px;
136
+ }
137
+
138
+ > *:not(:last-child) {
139
+ margin-block-end: 16px;
140
+ }
141
+ }
142
+ }
143
+
144
+ img {
145
+ max-width: 100%;
146
+ box-sizing: border-box;
147
+ }
148
+
149
+ hr {
150
+ height: 0.25em;
151
+ padding: 0;
152
+ margin: 24px 0;
153
+ background-color: var(--bolt-elements-borderColor);
154
+ border: 0;
155
+ }
156
+
157
+ table {
158
+ border-collapse: collapse;
159
+ width: 100%;
160
+ margin-block-end: 16px;
161
+
162
+ :is(th, td) {
163
+ padding: 6px 13px;
164
+ border: 1px solid #dfe2e5;
165
+ }
166
+
167
+ tr:nth-child(2n) {
168
+ background-color: #f6f8fa;
169
+ }
170
+ }
171
+ }
app/components/chat/Markdown.spec.ts ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { describe, expect, it } from 'vitest';
2
+ import { stripCodeFenceFromArtifact } from './Markdown';
3
+
4
+ describe('stripCodeFenceFromArtifact', () => {
5
+ it('should remove code fences around artifact element', () => {
6
+ const input = "```xml\n<div class='__boltArtifact__'></div>\n```";
7
+ const expected = "\n<div class='__boltArtifact__'></div>\n";
8
+ expect(stripCodeFenceFromArtifact(input)).toBe(expected);
9
+ });
10
+
11
+ it('should handle code fence with language specification', () => {
12
+ const input = "```typescript\n<div class='__boltArtifact__'></div>\n```";
13
+ const expected = "\n<div class='__boltArtifact__'></div>\n";
14
+ expect(stripCodeFenceFromArtifact(input)).toBe(expected);
15
+ });
16
+
17
+ it('should not modify content without artifacts', () => {
18
+ const input = '```\nregular code block\n```';
19
+ expect(stripCodeFenceFromArtifact(input)).toBe(input);
20
+ });
21
+
22
+ it('should handle empty input', () => {
23
+ expect(stripCodeFenceFromArtifact('')).toBe('');
24
+ });
25
+
26
+ it('should handle artifact without code fences', () => {
27
+ const input = "<div class='__boltArtifact__'></div>";
28
+ expect(stripCodeFenceFromArtifact(input)).toBe(input);
29
+ });
30
+
31
+ it('should handle multiple artifacts but only remove fences around them', () => {
32
+ const input = [
33
+ 'Some text',
34
+ '```typescript',
35
+ "<div class='__boltArtifact__'></div>",
36
+ '```',
37
+ '```',
38
+ 'regular code',
39
+ '```',
40
+ ].join('\n');
41
+
42
+ const expected = ['Some text', '', "<div class='__boltArtifact__'></div>", '', '```', 'regular code', '```'].join(
43
+ '\n',
44
+ );
45
+
46
+ expect(stripCodeFenceFromArtifact(input)).toBe(expected);
47
+ });
48
+ });
app/components/chat/Markdown.tsx ADDED
@@ -0,0 +1,118 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { memo, useMemo } from 'react';
2
+ import ReactMarkdown, { type Components } from 'react-markdown';
3
+ import type { BundledLanguage } from 'shiki';
4
+ import { createScopedLogger } from '~/utils/logger';
5
+ import { rehypePlugins, remarkPlugins, allowedHTMLElements } from '~/utils/markdown';
6
+ import { Artifact } from './Artifact';
7
+ import { CodeBlock } from './CodeBlock';
8
+
9
+ import styles from './Markdown.module.scss';
10
+
11
+ const logger = createScopedLogger('MarkdownComponent');
12
+
13
+ interface MarkdownProps {
14
+ children: string;
15
+ html?: boolean;
16
+ limitedMarkdown?: boolean;
17
+ }
18
+
19
+ export const Markdown = memo(({ children, html = false, limitedMarkdown = false }: MarkdownProps) => {
20
+ logger.trace('Render');
21
+
22
+ const components = useMemo(() => {
23
+ return {
24
+ div: ({ className, children, node, ...props }) => {
25
+ if (className?.includes('__boltArtifact__')) {
26
+ const messageId = node?.properties.dataMessageId as string;
27
+
28
+ if (!messageId) {
29
+ logger.error(`Invalid message id ${messageId}`);
30
+ }
31
+
32
+ return <Artifact messageId={messageId} />;
33
+ }
34
+
35
+ return (
36
+ <div className={className} {...props}>
37
+ {children}
38
+ </div>
39
+ );
40
+ },
41
+ pre: (props) => {
42
+ const { children, node, ...rest } = props;
43
+
44
+ const [firstChild] = node?.children ?? [];
45
+
46
+ if (
47
+ firstChild &&
48
+ firstChild.type === 'element' &&
49
+ firstChild.tagName === 'code' &&
50
+ firstChild.children[0].type === 'text'
51
+ ) {
52
+ const { className, ...rest } = firstChild.properties;
53
+ const [, language = 'plaintext'] = /language-(\w+)/.exec(String(className) || '') ?? [];
54
+
55
+ return <CodeBlock code={firstChild.children[0].value} language={language as BundledLanguage} {...rest} />;
56
+ }
57
+
58
+ return <pre {...rest}>{children}</pre>;
59
+ },
60
+ } satisfies Components;
61
+ }, []);
62
+
63
+ return (
64
+ <ReactMarkdown
65
+ allowedElements={allowedHTMLElements}
66
+ className={styles.MarkdownContent}
67
+ components={components}
68
+ remarkPlugins={remarkPlugins(limitedMarkdown)}
69
+ rehypePlugins={rehypePlugins(html)}
70
+ >
71
+ {stripCodeFenceFromArtifact(children)}
72
+ </ReactMarkdown>
73
+ );
74
+ });
75
+
76
+ /**
77
+ * Removes code fence markers (```) surrounding an artifact element while preserving the artifact content.
78
+ * This is necessary because artifacts should not be wrapped in code blocks when rendered for rendering action list.
79
+ *
80
+ * @param content - The markdown content to process
81
+ * @returns The processed content with code fence markers removed around artifacts
82
+ *
83
+ * @example
84
+ * // Removes code fences around artifact
85
+ * const input = "```xml\n<div class='__boltArtifact__'></div>\n```";
86
+ * stripCodeFenceFromArtifact(input);
87
+ * // Returns: "\n<div class='__boltArtifact__'></div>\n"
88
+ *
89
+ * @remarks
90
+ * - Only removes code fences that directly wrap an artifact (marked with __boltArtifact__ class)
91
+ * - Handles code fences with optional language specifications (e.g. ```xml, ```typescript)
92
+ * - Preserves original content if no artifact is found
93
+ * - Safely handles edge cases like empty input or artifacts at start/end of content
94
+ */
95
+ export const stripCodeFenceFromArtifact = (content: string) => {
96
+ if (!content || !content.includes('__boltArtifact__')) {
97
+ return content;
98
+ }
99
+
100
+ const lines = content.split('\n');
101
+ const artifactLineIndex = lines.findIndex((line) => line.includes('__boltArtifact__'));
102
+
103
+ // Return original content if artifact line not found
104
+ if (artifactLineIndex === -1) {
105
+ return content;
106
+ }
107
+
108
+ // Check previous line for code fence
109
+ if (artifactLineIndex > 0 && lines[artifactLineIndex - 1]?.trim().match(/^```\w*$/)) {
110
+ lines[artifactLineIndex - 1] = '';
111
+ }
112
+
113
+ if (artifactLineIndex < lines.length - 1 && lines[artifactLineIndex + 1]?.trim().match(/^```$/)) {
114
+ lines[artifactLineIndex + 1] = '';
115
+ }
116
+
117
+ return lines.join('\n');
118
+ };
app/components/chat/Messages.client.tsx ADDED
@@ -0,0 +1,106 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import type { Message } from 'ai';
2
+ import React from 'react';
3
+ import { classNames } from '~/utils/classNames';
4
+ import { AssistantMessage } from './AssistantMessage';
5
+ import { UserMessage } from './UserMessage';
6
+ import { useLocation } from '@remix-run/react';
7
+ import { db, chatId } from '~/lib/persistence/useChatHistory';
8
+ import { forkChat } from '~/lib/persistence/db';
9
+ import { toast } from 'react-toastify';
10
+ import WithTooltip from '~/components/ui/Tooltip';
11
+
12
+ interface MessagesProps {
13
+ id?: string;
14
+ className?: string;
15
+ isStreaming?: boolean;
16
+ messages?: Message[];
17
+ }
18
+
19
+ export const Messages = React.forwardRef<HTMLDivElement, MessagesProps>((props: MessagesProps, ref) => {
20
+ const { id, isStreaming = false, messages = [] } = props;
21
+ const location = useLocation();
22
+
23
+ const handleRewind = (messageId: string) => {
24
+ const searchParams = new URLSearchParams(location.search);
25
+ searchParams.set('rewindTo', messageId);
26
+ window.location.search = searchParams.toString();
27
+ };
28
+
29
+ const handleFork = async (messageId: string) => {
30
+ try {
31
+ if (!db || !chatId.get()) {
32
+ toast.error('Chat persistence is not available');
33
+ return;
34
+ }
35
+
36
+ const urlId = await forkChat(db, chatId.get()!, messageId);
37
+ window.location.href = `/chat/${urlId}`;
38
+ } catch (error) {
39
+ toast.error('Failed to fork chat: ' + (error as Error).message);
40
+ }
41
+ };
42
+
43
+ return (
44
+ <div id={id} ref={ref} className={props.className}>
45
+ {messages.length > 0
46
+ ? messages.map((message, index) => {
47
+ const { role, content, id: messageId } = message;
48
+ const isUserMessage = role === 'user';
49
+ const isFirst = index === 0;
50
+ const isLast = index === messages.length - 1;
51
+
52
+ return (
53
+ <div
54
+ key={index}
55
+ className={classNames('flex gap-4 p-6 w-full rounded-[calc(0.75rem-1px)]', {
56
+ 'bg-bolt-elements-messages-background': isUserMessage || !isStreaming || (isStreaming && !isLast),
57
+ 'bg-gradient-to-b from-bolt-elements-messages-background from-30% to-transparent':
58
+ isStreaming && isLast,
59
+ 'mt-4': !isFirst,
60
+ })}
61
+ >
62
+ {isUserMessage && (
63
+ <div className="flex items-center justify-center w-[34px] h-[34px] overflow-hidden bg-white text-gray-600 rounded-full shrink-0 self-start">
64
+ <div className="i-ph:user-fill text-xl"></div>
65
+ </div>
66
+ )}
67
+ <div className="grid grid-col-1 w-full">
68
+ {isUserMessage ? <UserMessage content={content} /> : <AssistantMessage content={content} />}
69
+ </div>
70
+ {!isUserMessage && (
71
+ <div className="flex gap-2 flex-col lg:flex-row">
72
+ <WithTooltip tooltip="Revert to this message">
73
+ {messageId && (
74
+ <button
75
+ onClick={() => handleRewind(messageId)}
76
+ key="i-ph:arrow-u-up-left"
77
+ className={classNames(
78
+ 'i-ph:arrow-u-up-left',
79
+ 'text-xl text-bolt-elements-textSecondary hover:text-bolt-elements-textPrimary transition-colors',
80
+ )}
81
+ />
82
+ )}
83
+ </WithTooltip>
84
+
85
+ <WithTooltip tooltip="Fork chat from this message">
86
+ <button
87
+ onClick={() => handleFork(messageId)}
88
+ key="i-ph:git-fork"
89
+ className={classNames(
90
+ 'i-ph:git-fork',
91
+ 'text-xl text-bolt-elements-textSecondary hover:text-bolt-elements-textPrimary transition-colors',
92
+ )}
93
+ />
94
+ </WithTooltip>
95
+ </div>
96
+ )}
97
+ </div>
98
+ );
99
+ })
100
+ : null}
101
+ {isStreaming && (
102
+ <div className="text-center w-full text-bolt-elements-textSecondary i-svg-spinners:3-dots-fade text-4xl mt-4"></div>
103
+ )}
104
+ </div>
105
+ );
106
+ });
app/components/chat/ModelSelector.tsx ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import type { ProviderInfo } from '~/types/model';
2
+ import type { ModelInfo } from '~/utils/types';
3
+
4
+ interface ModelSelectorProps {
5
+ model?: string;
6
+ setModel?: (model: string) => void;
7
+ provider?: ProviderInfo;
8
+ setProvider?: (provider: ProviderInfo) => void;
9
+ modelList: ModelInfo[];
10
+ providerList: ProviderInfo[];
11
+ apiKeys: Record<string, string>;
12
+ }
13
+
14
+ export const ModelSelector = ({
15
+ model,
16
+ setModel,
17
+ provider,
18
+ setProvider,
19
+ modelList,
20
+ providerList,
21
+ }: ModelSelectorProps) => {
22
+ return (
23
+ <div className="mb-2 flex gap-2 flex-col sm:flex-row">
24
+ <select
25
+ value={provider?.name ?? ''}
26
+ onChange={(e) => {
27
+ const newProvider = providerList.find((p: ProviderInfo) => p.name === e.target.value);
28
+
29
+ if (newProvider && setProvider) {
30
+ setProvider(newProvider);
31
+ }
32
+
33
+ const firstModel = [...modelList].find((m) => m.provider === e.target.value);
34
+
35
+ if (firstModel && setModel) {
36
+ setModel(firstModel.name);
37
+ }
38
+ }}
39
+ className="flex-1 p-2 rounded-lg border border-bolt-elements-borderColor bg-bolt-elements-prompt-background text-bolt-elements-textPrimary focus:outline-none focus:ring-2 focus:ring-bolt-elements-focus transition-all"
40
+ >
41
+ {providerList.map((provider: ProviderInfo) => (
42
+ <option key={provider.name} value={provider.name}>
43
+ {provider.name}
44
+ </option>
45
+ ))}
46
+ </select>
47
+ <select
48
+ key={provider?.name}
49
+ value={model}
50
+ onChange={(e) => setModel?.(e.target.value)}
51
+ className="flex-1 p-2 rounded-lg border border-bolt-elements-borderColor bg-bolt-elements-prompt-background text-bolt-elements-textPrimary focus:outline-none focus:ring-2 focus:ring-bolt-elements-focus transition-all lg:max-w-[70%]"
52
+ >
53
+ {[...modelList]
54
+ .filter((e) => e.provider == provider?.name && e.name)
55
+ .map((modelOption) => (
56
+ <option key={modelOption.name} value={modelOption.name}>
57
+ {modelOption.label}
58
+ </option>
59
+ ))}
60
+ </select>
61
+ </div>
62
+ );
63
+ };
app/components/chat/SendButton.client.tsx ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { AnimatePresence, cubicBezier, motion } from 'framer-motion';
2
+
3
+ interface SendButtonProps {
4
+ show: boolean;
5
+ isStreaming?: boolean;
6
+ onClick?: (event: React.MouseEvent<HTMLButtonElement, MouseEvent>) => void;
7
+ onImagesSelected?: (images: File[]) => void;
8
+ }
9
+
10
+ const customEasingFn = cubicBezier(0.4, 0, 0.2, 1);
11
+
12
+ export const SendButton = ({ show, isStreaming, onClick }: SendButtonProps) => {
13
+ return (
14
+ <AnimatePresence>
15
+ {show ? (
16
+ <motion.button
17
+ className="absolute flex justify-center items-center top-[18px] right-[22px] p-1 bg-accent-500 hover:brightness-94 color-white rounded-md w-[34px] h-[34px] transition-theme"
18
+ transition={{ ease: customEasingFn, duration: 0.17 }}
19
+ initial={{ opacity: 0, y: 10 }}
20
+ animate={{ opacity: 1, y: 0 }}
21
+ exit={{ opacity: 0, y: 10 }}
22
+ onClick={(event) => {
23
+ event.preventDefault();
24
+ onClick?.(event);
25
+ }}
26
+ >
27
+ <div className="text-lg">
28
+ {!isStreaming ? <div className="i-ph:arrow-right"></div> : <div className="i-ph:stop-circle-bold"></div>}
29
+ </div>
30
+ </motion.button>
31
+ ) : null}
32
+ </AnimatePresence>
33
+ );
34
+ };
app/components/chat/SpeechRecognition.tsx ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { IconButton } from '~/components/ui/IconButton';
2
+ import { classNames } from '~/utils/classNames';
3
+ import React from 'react';
4
+
5
+ export const SpeechRecognitionButton = ({
6
+ isListening,
7
+ onStart,
8
+ onStop,
9
+ disabled,
10
+ }: {
11
+ isListening: boolean;
12
+ onStart: () => void;
13
+ onStop: () => void;
14
+ disabled: boolean;
15
+ }) => {
16
+ return (
17
+ <IconButton
18
+ title={isListening ? 'Stop listening' : 'Start speech recognition'}
19
+ disabled={disabled}
20
+ className={classNames('transition-all', {
21
+ 'text-bolt-elements-item-contentAccent': isListening,
22
+ })}
23
+ onClick={isListening ? onStop : onStart}
24
+ >
25
+ {isListening ? <div className="i-ph:microphone-slash text-xl" /> : <div className="i-ph:microphone text-xl" />}
26
+ </IconButton>
27
+ );
28
+ };
app/components/chat/UserMessage.tsx ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * @ts-nocheck
3
+ * Preventing TS checks with files presented in the video for a better presentation.
4
+ */
5
+ import { MODEL_REGEX, PROVIDER_REGEX } from '~/utils/constants';
6
+ import { Markdown } from './Markdown';
7
+
8
+ interface UserMessageProps {
9
+ content: string | Array<{ type: string; text?: string; image?: string }>;
10
+ }
11
+
12
+ export function UserMessage({ content }: UserMessageProps) {
13
+ if (Array.isArray(content)) {
14
+ const textItem = content.find((item) => item.type === 'text');
15
+ const textContent = sanitizeUserMessage(textItem?.text || '');
16
+ const images = content.filter((item) => item.type === 'image' && item.image);
17
+
18
+ return (
19
+ <div className="overflow-hidden pt-[4px]">
20
+ <div className="flex items-start gap-4">
21
+ <div className="flex-1">
22
+ <Markdown limitedMarkdown>{textContent}</Markdown>
23
+ </div>
24
+ {images.length > 0 && (
25
+ <div className="flex-shrink-0 w-[160px]">
26
+ {images.map((item, index) => (
27
+ <div key={index} className="relative">
28
+ <img
29
+ src={item.image}
30
+ alt={`Uploaded image ${index + 1}`}
31
+ className="w-full h-[160px] rounded-lg object-cover border border-bolt-elements-borderColor"
32
+ />
33
+ </div>
34
+ ))}
35
+ </div>
36
+ )}
37
+ </div>
38
+ </div>
39
+ );
40
+ }
41
+
42
+ const textContent = sanitizeUserMessage(content);
43
+
44
+ return (
45
+ <div className="overflow-hidden pt-[4px]">
46
+ <Markdown limitedMarkdown>{textContent}</Markdown>
47
+ </div>
48
+ );
49
+ }
50
+
51
+ function sanitizeUserMessage(content: string) {
52
+ return content.replace(MODEL_REGEX, '').replace(PROVIDER_REGEX, '');
53
+ }
app/components/chat/chatExportAndImport/ExportChatButton.tsx ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import WithTooltip from '~/components/ui/Tooltip';
2
+ import { IconButton } from '~/components/ui/IconButton';
3
+ import React from 'react';
4
+
5
+ export const ExportChatButton = ({ exportChat }: { exportChat?: () => void }) => {
6
+ return (
7
+ <WithTooltip tooltip="Export Chat">
8
+ <IconButton title="Export Chat" onClick={() => exportChat?.()}>
9
+ <div className="i-ph:download-simple text-xl"></div>
10
+ </IconButton>
11
+ </WithTooltip>
12
+ );
13
+ };
app/components/chat/chatExportAndImport/ImportButtons.tsx ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import type { Message } from 'ai';
2
+ import { toast } from 'react-toastify';
3
+ import React from 'react';
4
+ import { ImportFolderButton } from '~/components/chat/ImportFolderButton';
5
+
6
+ export function ImportButtons(importChat: ((description: string, messages: Message[]) => Promise<void>) | undefined) {
7
+ return (
8
+ <div className="flex flex-col items-center justify-center flex-1 p-4">
9
+ <input
10
+ type="file"
11
+ id="chat-import"
12
+ className="hidden"
13
+ accept=".json"
14
+ onChange={async (e) => {
15
+ const file = e.target.files?.[0];
16
+
17
+ if (file && importChat) {
18
+ try {
19
+ const reader = new FileReader();
20
+
21
+ reader.onload = async (e) => {
22
+ try {
23
+ const content = e.target?.result as string;
24
+ const data = JSON.parse(content);
25
+
26
+ if (!Array.isArray(data.messages)) {
27
+ toast.error('Invalid chat file format');
28
+ }
29
+
30
+ await importChat(data.description, data.messages);
31
+ toast.success('Chat imported successfully');
32
+ } catch (error: unknown) {
33
+ if (error instanceof Error) {
34
+ toast.error('Failed to parse chat file: ' + error.message);
35
+ } else {
36
+ toast.error('Failed to parse chat file');
37
+ }
38
+ }
39
+ };
40
+ reader.onerror = () => toast.error('Failed to read chat file');
41
+ reader.readAsText(file);
42
+ } catch (error) {
43
+ toast.error(error instanceof Error ? error.message : 'Failed to import chat');
44
+ }
45
+ e.target.value = ''; // Reset file input
46
+ } else {
47
+ toast.error('Something went wrong');
48
+ }
49
+ }}
50
+ />
51
+ <div className="flex flex-col items-center gap-4 max-w-2xl text-center">
52
+ <div className="flex gap-2">
53
+ <button
54
+ onClick={() => {
55
+ const input = document.getElementById('chat-import');
56
+ input?.click();
57
+ }}
58
+ className="px-4 py-2 rounded-lg border border-bolt-elements-borderColor bg-bolt-elements-prompt-background text-bolt-elements-textPrimary hover:bg-bolt-elements-background-depth-3 transition-all flex items-center gap-2"
59
+ >
60
+ <div className="i-ph:upload-simple" />
61
+ Import Chat
62
+ </button>
63
+ <ImportFolderButton
64
+ importChat={importChat}
65
+ className="px-4 py-2 rounded-lg border border-bolt-elements-borderColor bg-bolt-elements-prompt-background text-bolt-elements-textPrimary hover:bg-bolt-elements-background-depth-3 transition-all flex items-center gap-2"
66
+ />
67
+ </div>
68
+ </div>
69
+ </div>
70
+ );
71
+ }
app/components/editor/codemirror/BinaryContent.tsx ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ export function BinaryContent() {
2
+ return (
3
+ <div className="flex items-center justify-center absolute inset-0 z-10 text-sm bg-tk-elements-app-backgroundColor text-tk-elements-app-textColor">
4
+ File format cannot be displayed.
5
+ </div>
6
+ );
7
+ }
app/components/editor/codemirror/CodeMirrorEditor.tsx ADDED
@@ -0,0 +1,461 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { acceptCompletion, autocompletion, closeBrackets } from '@codemirror/autocomplete';
2
+ import { defaultKeymap, history, historyKeymap } from '@codemirror/commands';
3
+ import { bracketMatching, foldGutter, indentOnInput, indentUnit } from '@codemirror/language';
4
+ import { searchKeymap } from '@codemirror/search';
5
+ import { Compartment, EditorSelection, EditorState, StateEffect, StateField, type Extension } from '@codemirror/state';
6
+ import {
7
+ drawSelection,
8
+ dropCursor,
9
+ EditorView,
10
+ highlightActiveLine,
11
+ highlightActiveLineGutter,
12
+ keymap,
13
+ lineNumbers,
14
+ scrollPastEnd,
15
+ showTooltip,
16
+ tooltips,
17
+ type Tooltip,
18
+ } from '@codemirror/view';
19
+ import { memo, useEffect, useRef, useState, type MutableRefObject } from 'react';
20
+ import type { Theme } from '~/types/theme';
21
+ import { classNames } from '~/utils/classNames';
22
+ import { debounce } from '~/utils/debounce';
23
+ import { createScopedLogger, renderLogger } from '~/utils/logger';
24
+ import { BinaryContent } from './BinaryContent';
25
+ import { getTheme, reconfigureTheme } from './cm-theme';
26
+ import { indentKeyBinding } from './indent';
27
+ import { getLanguage } from './languages';
28
+
29
+ const logger = createScopedLogger('CodeMirrorEditor');
30
+
31
+ export interface EditorDocument {
32
+ value: string;
33
+ isBinary: boolean;
34
+ filePath: string;
35
+ scroll?: ScrollPosition;
36
+ }
37
+
38
+ export interface EditorSettings {
39
+ fontSize?: string;
40
+ gutterFontSize?: string;
41
+ tabSize?: number;
42
+ }
43
+
44
+ type TextEditorDocument = EditorDocument & {
45
+ value: string;
46
+ };
47
+
48
+ export interface ScrollPosition {
49
+ top: number;
50
+ left: number;
51
+ }
52
+
53
+ export interface EditorUpdate {
54
+ selection: EditorSelection;
55
+ content: string;
56
+ }
57
+
58
+ export type OnChangeCallback = (update: EditorUpdate) => void;
59
+ export type OnScrollCallback = (position: ScrollPosition) => void;
60
+ export type OnSaveCallback = () => void;
61
+
62
+ interface Props {
63
+ theme: Theme;
64
+ id?: unknown;
65
+ doc?: EditorDocument;
66
+ editable?: boolean;
67
+ debounceChange?: number;
68
+ debounceScroll?: number;
69
+ autoFocusOnDocumentChange?: boolean;
70
+ onChange?: OnChangeCallback;
71
+ onScroll?: OnScrollCallback;
72
+ onSave?: OnSaveCallback;
73
+ className?: string;
74
+ settings?: EditorSettings;
75
+ }
76
+
77
+ type EditorStates = Map<string, EditorState>;
78
+
79
+ const readOnlyTooltipStateEffect = StateEffect.define<boolean>();
80
+
81
+ const editableTooltipField = StateField.define<readonly Tooltip[]>({
82
+ create: () => [],
83
+ update(_tooltips, transaction) {
84
+ if (!transaction.state.readOnly) {
85
+ return [];
86
+ }
87
+
88
+ for (const effect of transaction.effects) {
89
+ if (effect.is(readOnlyTooltipStateEffect) && effect.value) {
90
+ return getReadOnlyTooltip(transaction.state);
91
+ }
92
+ }
93
+
94
+ return [];
95
+ },
96
+ provide: (field) => {
97
+ return showTooltip.computeN([field], (state) => state.field(field));
98
+ },
99
+ });
100
+
101
+ const editableStateEffect = StateEffect.define<boolean>();
102
+
103
+ const editableStateField = StateField.define<boolean>({
104
+ create() {
105
+ return true;
106
+ },
107
+ update(value, transaction) {
108
+ for (const effect of transaction.effects) {
109
+ if (effect.is(editableStateEffect)) {
110
+ return effect.value;
111
+ }
112
+ }
113
+
114
+ return value;
115
+ },
116
+ });
117
+
118
+ export const CodeMirrorEditor = memo(
119
+ ({
120
+ id,
121
+ doc,
122
+ debounceScroll = 100,
123
+ debounceChange = 150,
124
+ autoFocusOnDocumentChange = false,
125
+ editable = true,
126
+ onScroll,
127
+ onChange,
128
+ onSave,
129
+ theme,
130
+ settings,
131
+ className = '',
132
+ }: Props) => {
133
+ renderLogger.trace('CodeMirrorEditor');
134
+
135
+ const [languageCompartment] = useState(new Compartment());
136
+
137
+ const containerRef = useRef<HTMLDivElement | null>(null);
138
+ const viewRef = useRef<EditorView>();
139
+ const themeRef = useRef<Theme>();
140
+ const docRef = useRef<EditorDocument>();
141
+ const editorStatesRef = useRef<EditorStates>();
142
+ const onScrollRef = useRef(onScroll);
143
+ const onChangeRef = useRef(onChange);
144
+ const onSaveRef = useRef(onSave);
145
+
146
+ /**
147
+ * This effect is used to avoid side effects directly in the render function
148
+ * and instead the refs are updated after each render.
149
+ */
150
+ useEffect(() => {
151
+ onScrollRef.current = onScroll;
152
+ onChangeRef.current = onChange;
153
+ onSaveRef.current = onSave;
154
+ docRef.current = doc;
155
+ themeRef.current = theme;
156
+ });
157
+
158
+ useEffect(() => {
159
+ const onUpdate = debounce((update: EditorUpdate) => {
160
+ onChangeRef.current?.(update);
161
+ }, debounceChange);
162
+
163
+ const view = new EditorView({
164
+ parent: containerRef.current!,
165
+ dispatchTransactions(transactions) {
166
+ const previousSelection = view.state.selection;
167
+
168
+ view.update(transactions);
169
+
170
+ const newSelection = view.state.selection;
171
+
172
+ const selectionChanged =
173
+ newSelection !== previousSelection &&
174
+ (newSelection === undefined || previousSelection === undefined || !newSelection.eq(previousSelection));
175
+
176
+ if (docRef.current && (transactions.some((transaction) => transaction.docChanged) || selectionChanged)) {
177
+ onUpdate({
178
+ selection: view.state.selection,
179
+ content: view.state.doc.toString(),
180
+ });
181
+
182
+ editorStatesRef.current!.set(docRef.current.filePath, view.state);
183
+ }
184
+ },
185
+ });
186
+
187
+ viewRef.current = view;
188
+
189
+ return () => {
190
+ viewRef.current?.destroy();
191
+ viewRef.current = undefined;
192
+ };
193
+ }, []);
194
+
195
+ useEffect(() => {
196
+ if (!viewRef.current) {
197
+ return;
198
+ }
199
+
200
+ viewRef.current.dispatch({
201
+ effects: [reconfigureTheme(theme)],
202
+ });
203
+ }, [theme]);
204
+
205
+ useEffect(() => {
206
+ editorStatesRef.current = new Map<string, EditorState>();
207
+ }, [id]);
208
+
209
+ useEffect(() => {
210
+ const editorStates = editorStatesRef.current!;
211
+ const view = viewRef.current!;
212
+ const theme = themeRef.current!;
213
+
214
+ if (!doc) {
215
+ const state = newEditorState('', theme, settings, onScrollRef, debounceScroll, onSaveRef, [
216
+ languageCompartment.of([]),
217
+ ]);
218
+
219
+ view.setState(state);
220
+
221
+ setNoDocument(view);
222
+
223
+ return;
224
+ }
225
+
226
+ if (doc.isBinary) {
227
+ return;
228
+ }
229
+
230
+ if (doc.filePath === '') {
231
+ logger.warn('File path should not be empty');
232
+ }
233
+
234
+ let state = editorStates.get(doc.filePath);
235
+
236
+ if (!state) {
237
+ state = newEditorState(doc.value, theme, settings, onScrollRef, debounceScroll, onSaveRef, [
238
+ languageCompartment.of([]),
239
+ ]);
240
+
241
+ editorStates.set(doc.filePath, state);
242
+ }
243
+
244
+ view.setState(state);
245
+
246
+ setEditorDocument(
247
+ view,
248
+ theme,
249
+ editable,
250
+ languageCompartment,
251
+ autoFocusOnDocumentChange,
252
+ doc as TextEditorDocument,
253
+ );
254
+ }, [doc?.value, editable, doc?.filePath, autoFocusOnDocumentChange]);
255
+
256
+ return (
257
+ <div className={classNames('relative h-full', className)}>
258
+ {doc?.isBinary && <BinaryContent />}
259
+ <div className="h-full overflow-hidden" ref={containerRef} />
260
+ </div>
261
+ );
262
+ },
263
+ );
264
+
265
+ export default CodeMirrorEditor;
266
+
267
+ CodeMirrorEditor.displayName = 'CodeMirrorEditor';
268
+
269
+ function newEditorState(
270
+ content: string,
271
+ theme: Theme,
272
+ settings: EditorSettings | undefined,
273
+ onScrollRef: MutableRefObject<OnScrollCallback | undefined>,
274
+ debounceScroll: number,
275
+ onFileSaveRef: MutableRefObject<OnSaveCallback | undefined>,
276
+ extensions: Extension[],
277
+ ) {
278
+ return EditorState.create({
279
+ doc: content,
280
+ extensions: [
281
+ EditorView.domEventHandlers({
282
+ scroll: debounce((event, view) => {
283
+ if (event.target !== view.scrollDOM) {
284
+ return;
285
+ }
286
+
287
+ onScrollRef.current?.({ left: view.scrollDOM.scrollLeft, top: view.scrollDOM.scrollTop });
288
+ }, debounceScroll),
289
+ keydown: (event, view) => {
290
+ if (view.state.readOnly) {
291
+ view.dispatch({
292
+ effects: [readOnlyTooltipStateEffect.of(event.key !== 'Escape')],
293
+ });
294
+
295
+ return true;
296
+ }
297
+
298
+ return false;
299
+ },
300
+ }),
301
+ getTheme(theme, settings),
302
+ history(),
303
+ keymap.of([
304
+ ...defaultKeymap,
305
+ ...historyKeymap,
306
+ ...searchKeymap,
307
+ { key: 'Tab', run: acceptCompletion },
308
+ {
309
+ key: 'Mod-s',
310
+ preventDefault: true,
311
+ run: () => {
312
+ onFileSaveRef.current?.();
313
+ return true;
314
+ },
315
+ },
316
+ indentKeyBinding,
317
+ ]),
318
+ indentUnit.of('\t'),
319
+ autocompletion({
320
+ closeOnBlur: false,
321
+ }),
322
+ tooltips({
323
+ position: 'absolute',
324
+ parent: document.body,
325
+ tooltipSpace: (view) => {
326
+ const rect = view.dom.getBoundingClientRect();
327
+
328
+ return {
329
+ top: rect.top - 50,
330
+ left: rect.left,
331
+ bottom: rect.bottom,
332
+ right: rect.right + 10,
333
+ };
334
+ },
335
+ }),
336
+ closeBrackets(),
337
+ lineNumbers(),
338
+ scrollPastEnd(),
339
+ dropCursor(),
340
+ drawSelection(),
341
+ bracketMatching(),
342
+ EditorState.tabSize.of(settings?.tabSize ?? 2),
343
+ indentOnInput(),
344
+ editableTooltipField,
345
+ editableStateField,
346
+ EditorState.readOnly.from(editableStateField, (editable) => !editable),
347
+ highlightActiveLineGutter(),
348
+ highlightActiveLine(),
349
+ foldGutter({
350
+ markerDOM: (open) => {
351
+ const icon = document.createElement('div');
352
+
353
+ icon.className = `fold-icon ${open ? 'i-ph-caret-down-bold' : 'i-ph-caret-right-bold'}`;
354
+
355
+ return icon;
356
+ },
357
+ }),
358
+ ...extensions,
359
+ ],
360
+ });
361
+ }
362
+
363
+ function setNoDocument(view: EditorView) {
364
+ view.dispatch({
365
+ selection: { anchor: 0 },
366
+ changes: {
367
+ from: 0,
368
+ to: view.state.doc.length,
369
+ insert: '',
370
+ },
371
+ });
372
+
373
+ view.scrollDOM.scrollTo(0, 0);
374
+ }
375
+
376
+ function setEditorDocument(
377
+ view: EditorView,
378
+ theme: Theme,
379
+ editable: boolean,
380
+ languageCompartment: Compartment,
381
+ autoFocus: boolean,
382
+ doc: TextEditorDocument,
383
+ ) {
384
+ if (doc.value !== view.state.doc.toString()) {
385
+ view.dispatch({
386
+ selection: { anchor: 0 },
387
+ changes: {
388
+ from: 0,
389
+ to: view.state.doc.length,
390
+ insert: doc.value,
391
+ },
392
+ });
393
+ }
394
+
395
+ view.dispatch({
396
+ effects: [editableStateEffect.of(editable && !doc.isBinary)],
397
+ });
398
+
399
+ getLanguage(doc.filePath).then((languageSupport) => {
400
+ if (!languageSupport) {
401
+ return;
402
+ }
403
+
404
+ view.dispatch({
405
+ effects: [languageCompartment.reconfigure([languageSupport]), reconfigureTheme(theme)],
406
+ });
407
+
408
+ requestAnimationFrame(() => {
409
+ const currentLeft = view.scrollDOM.scrollLeft;
410
+ const currentTop = view.scrollDOM.scrollTop;
411
+ const newLeft = doc.scroll?.left ?? 0;
412
+ const newTop = doc.scroll?.top ?? 0;
413
+
414
+ const needsScrolling = currentLeft !== newLeft || currentTop !== newTop;
415
+
416
+ if (autoFocus && editable) {
417
+ if (needsScrolling) {
418
+ // we have to wait until the scroll position was changed before we can set the focus
419
+ view.scrollDOM.addEventListener(
420
+ 'scroll',
421
+ () => {
422
+ view.focus();
423
+ },
424
+ { once: true },
425
+ );
426
+ } else {
427
+ // if the scroll position is still the same we can focus immediately
428
+ view.focus();
429
+ }
430
+ }
431
+
432
+ view.scrollDOM.scrollTo(newLeft, newTop);
433
+ });
434
+ });
435
+ }
436
+
437
+ function getReadOnlyTooltip(state: EditorState) {
438
+ if (!state.readOnly) {
439
+ return [];
440
+ }
441
+
442
+ return state.selection.ranges
443
+ .filter((range) => {
444
+ return range.empty;
445
+ })
446
+ .map((range) => {
447
+ return {
448
+ pos: range.head,
449
+ above: true,
450
+ strictSide: true,
451
+ arrow: true,
452
+ create: () => {
453
+ const divElement = document.createElement('div');
454
+ divElement.className = 'cm-readonly-tooltip';
455
+ divElement.textContent = 'Cannot edit file while AI response is being generated';
456
+
457
+ return { dom: divElement };
458
+ },
459
+ };
460
+ });
461
+ }
app/components/editor/codemirror/cm-theme.ts ADDED
@@ -0,0 +1,192 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { Compartment, type Extension } from '@codemirror/state';
2
+ import { EditorView } from '@codemirror/view';
3
+ import { vscodeDark, vscodeLight } from '@uiw/codemirror-theme-vscode';
4
+ import type { Theme } from '~/types/theme.js';
5
+ import type { EditorSettings } from './CodeMirrorEditor.js';
6
+
7
+ export const darkTheme = EditorView.theme({}, { dark: true });
8
+ export const themeSelection = new Compartment();
9
+
10
+ export function getTheme(theme: Theme, settings: EditorSettings = {}): Extension {
11
+ return [
12
+ getEditorTheme(settings),
13
+ theme === 'dark' ? themeSelection.of([getDarkTheme()]) : themeSelection.of([getLightTheme()]),
14
+ ];
15
+ }
16
+
17
+ export function reconfigureTheme(theme: Theme) {
18
+ return themeSelection.reconfigure(theme === 'dark' ? getDarkTheme() : getLightTheme());
19
+ }
20
+
21
+ function getEditorTheme(settings: EditorSettings) {
22
+ return EditorView.theme({
23
+ '&': {
24
+ fontSize: settings.fontSize ?? '12px',
25
+ },
26
+ '&.cm-editor': {
27
+ height: '100%',
28
+ background: 'var(--cm-backgroundColor)',
29
+ color: 'var(--cm-textColor)',
30
+ },
31
+ '.cm-cursor': {
32
+ borderLeft: 'var(--cm-cursor-width) solid var(--cm-cursor-backgroundColor)',
33
+ },
34
+ '.cm-scroller': {
35
+ lineHeight: '1.5',
36
+ '&:focus-visible': {
37
+ outline: 'none',
38
+ },
39
+ },
40
+ '.cm-line': {
41
+ padding: '0 0 0 4px',
42
+ },
43
+ '&.cm-focused > .cm-scroller > .cm-selectionLayer .cm-selectionBackground': {
44
+ backgroundColor: 'var(--cm-selection-backgroundColorFocused) !important',
45
+ opacity: 'var(--cm-selection-backgroundOpacityFocused, 0.3)',
46
+ },
47
+ '&:not(.cm-focused) > .cm-scroller > .cm-selectionLayer .cm-selectionBackground': {
48
+ backgroundColor: 'var(--cm-selection-backgroundColorBlured)',
49
+ opacity: 'var(--cm-selection-backgroundOpacityBlured, 0.3)',
50
+ },
51
+ '&.cm-focused > .cm-scroller .cm-matchingBracket': {
52
+ backgroundColor: 'var(--cm-matching-bracket)',
53
+ },
54
+ '.cm-activeLine': {
55
+ background: 'var(--cm-activeLineBackgroundColor)',
56
+ },
57
+ '.cm-gutters': {
58
+ background: 'var(--cm-gutter-backgroundColor)',
59
+ borderRight: 0,
60
+ color: 'var(--cm-gutter-textColor)',
61
+ },
62
+ '.cm-gutter': {
63
+ '&.cm-lineNumbers': {
64
+ fontFamily: 'Roboto Mono, monospace',
65
+ fontSize: settings.gutterFontSize ?? settings.fontSize ?? '12px',
66
+ minWidth: '40px',
67
+ },
68
+ '& .cm-activeLineGutter': {
69
+ background: 'transparent',
70
+ color: 'var(--cm-gutter-activeLineTextColor)',
71
+ },
72
+ '&.cm-foldGutter .cm-gutterElement > .fold-icon': {
73
+ cursor: 'pointer',
74
+ color: 'var(--cm-foldGutter-textColor)',
75
+ transform: 'translateY(2px)',
76
+ '&:hover': {
77
+ color: 'var(--cm-foldGutter-textColorHover)',
78
+ },
79
+ },
80
+ },
81
+ '.cm-foldGutter .cm-gutterElement': {
82
+ padding: '0 4px',
83
+ },
84
+ '.cm-tooltip-autocomplete > ul > li': {
85
+ minHeight: '18px',
86
+ },
87
+ '.cm-panel.cm-search label': {
88
+ marginLeft: '2px',
89
+ fontSize: '12px',
90
+ },
91
+ '.cm-panel.cm-search .cm-button': {
92
+ fontSize: '12px',
93
+ },
94
+ '.cm-panel.cm-search .cm-textfield': {
95
+ fontSize: '12px',
96
+ },
97
+ '.cm-panel.cm-search input[type=checkbox]': {
98
+ position: 'relative',
99
+ transform: 'translateY(2px)',
100
+ marginRight: '4px',
101
+ },
102
+ '.cm-panels': {
103
+ borderColor: 'var(--cm-panels-borderColor)',
104
+ },
105
+ '.cm-panels-bottom': {
106
+ borderTop: '1px solid var(--cm-panels-borderColor)',
107
+ backgroundColor: 'transparent',
108
+ },
109
+ '.cm-panel.cm-search': {
110
+ background: 'var(--cm-search-backgroundColor)',
111
+ color: 'var(--cm-search-textColor)',
112
+ padding: '8px',
113
+ },
114
+ '.cm-search .cm-button': {
115
+ background: 'var(--cm-search-button-backgroundColor)',
116
+ borderColor: 'var(--cm-search-button-borderColor)',
117
+ color: 'var(--cm-search-button-textColor)',
118
+ borderRadius: '4px',
119
+ '&:hover': {
120
+ color: 'var(--cm-search-button-textColorHover)',
121
+ },
122
+ '&:focus-visible': {
123
+ outline: 'none',
124
+ borderColor: 'var(--cm-search-button-borderColorFocused)',
125
+ },
126
+ '&:hover:not(:focus-visible)': {
127
+ background: 'var(--cm-search-button-backgroundColorHover)',
128
+ borderColor: 'var(--cm-search-button-borderColorHover)',
129
+ },
130
+ '&:hover:focus-visible': {
131
+ background: 'var(--cm-search-button-backgroundColorHover)',
132
+ borderColor: 'var(--cm-search-button-borderColorFocused)',
133
+ },
134
+ },
135
+ '.cm-panel.cm-search [name=close]': {
136
+ top: '6px',
137
+ right: '6px',
138
+ padding: '0 6px',
139
+ fontSize: '1rem',
140
+ backgroundColor: 'var(--cm-search-closeButton-backgroundColor)',
141
+ color: 'var(--cm-search-closeButton-textColor)',
142
+ '&:hover': {
143
+ 'border-radius': '6px',
144
+ color: 'var(--cm-search-closeButton-textColorHover)',
145
+ backgroundColor: 'var(--cm-search-closeButton-backgroundColorHover)',
146
+ },
147
+ },
148
+ '.cm-search input': {
149
+ background: 'var(--cm-search-input-backgroundColor)',
150
+ borderColor: 'var(--cm-search-input-borderColor)',
151
+ color: 'var(--cm-search-input-textColor)',
152
+ outline: 'none',
153
+ borderRadius: '4px',
154
+ '&:focus-visible': {
155
+ borderColor: 'var(--cm-search-input-borderColorFocused)',
156
+ },
157
+ },
158
+ '.cm-tooltip': {
159
+ background: 'var(--cm-tooltip-backgroundColor)',
160
+ border: '1px solid transparent',
161
+ borderColor: 'var(--cm-tooltip-borderColor)',
162
+ color: 'var(--cm-tooltip-textColor)',
163
+ },
164
+ '.cm-tooltip.cm-tooltip-autocomplete ul li[aria-selected]': {
165
+ background: 'var(--cm-tooltip-backgroundColorSelected)',
166
+ color: 'var(--cm-tooltip-textColorSelected)',
167
+ },
168
+ '.cm-searchMatch': {
169
+ backgroundColor: 'var(--cm-searchMatch-backgroundColor)',
170
+ },
171
+ '.cm-tooltip.cm-readonly-tooltip': {
172
+ padding: '4px',
173
+ whiteSpace: 'nowrap',
174
+ backgroundColor: 'var(--bolt-elements-bg-depth-2)',
175
+ borderColor: 'var(--bolt-elements-borderColorActive)',
176
+ '& .cm-tooltip-arrow:before': {
177
+ borderTopColor: 'var(--bolt-elements-borderColorActive)',
178
+ },
179
+ '& .cm-tooltip-arrow:after': {
180
+ borderTopColor: 'transparent',
181
+ },
182
+ },
183
+ });
184
+ }
185
+
186
+ function getLightTheme() {
187
+ return vscodeLight;
188
+ }
189
+
190
+ function getDarkTheme() {
191
+ return vscodeDark;
192
+ }
app/components/editor/codemirror/indent.ts ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { indentLess } from '@codemirror/commands';
2
+ import { indentUnit } from '@codemirror/language';
3
+ import { EditorSelection, EditorState, Line, type ChangeSpec } from '@codemirror/state';
4
+ import { EditorView, type KeyBinding } from '@codemirror/view';
5
+
6
+ export const indentKeyBinding: KeyBinding = {
7
+ key: 'Tab',
8
+ run: indentMore,
9
+ shift: indentLess,
10
+ };
11
+
12
+ function indentMore({ state, dispatch }: EditorView) {
13
+ if (state.readOnly) {
14
+ return false;
15
+ }
16
+
17
+ dispatch(
18
+ state.update(
19
+ changeBySelectedLine(state, (from, to, changes) => {
20
+ changes.push({ from, to, insert: state.facet(indentUnit) });
21
+ }),
22
+ { userEvent: 'input.indent' },
23
+ ),
24
+ );
25
+
26
+ return true;
27
+ }
28
+
29
+ function changeBySelectedLine(
30
+ state: EditorState,
31
+ cb: (from: number, to: number | undefined, changes: ChangeSpec[], line: Line) => void,
32
+ ) {
33
+ return state.changeByRange((range) => {
34
+ const changes: ChangeSpec[] = [];
35
+
36
+ const line = state.doc.lineAt(range.from);
37
+
38
+ // just insert single indent unit at the current cursor position
39
+ if (range.from === range.to) {
40
+ cb(range.from, undefined, changes, line);
41
+ }
42
+ // handle the case when multiple characters are selected in a single line
43
+ else if (range.from < range.to && range.to <= line.to) {
44
+ cb(range.from, range.to, changes, line);
45
+ } else {
46
+ let atLine = -1;
47
+
48
+ // handle the case when selection spans multiple lines
49
+ for (let pos = range.from; pos <= range.to; ) {
50
+ const line = state.doc.lineAt(pos);
51
+
52
+ if (line.number > atLine && (range.empty || range.to > line.from)) {
53
+ cb(line.from, undefined, changes, line);
54
+ atLine = line.number;
55
+ }
56
+
57
+ pos = line.to + 1;
58
+ }
59
+ }
60
+
61
+ const changeSet = state.changes(changes);
62
+
63
+ return {
64
+ changes,
65
+ range: EditorSelection.range(changeSet.mapPos(range.anchor, 1), changeSet.mapPos(range.head, 1)),
66
+ };
67
+ });
68
+ }
app/components/editor/codemirror/languages.ts ADDED
@@ -0,0 +1,105 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { LanguageDescription } from '@codemirror/language';
2
+
3
+ export const supportedLanguages = [
4
+ LanguageDescription.of({
5
+ name: 'TS',
6
+ extensions: ['ts'],
7
+ async load() {
8
+ return import('@codemirror/lang-javascript').then((module) => module.javascript({ typescript: true }));
9
+ },
10
+ }),
11
+ LanguageDescription.of({
12
+ name: 'JS',
13
+ extensions: ['js', 'mjs', 'cjs'],
14
+ async load() {
15
+ return import('@codemirror/lang-javascript').then((module) => module.javascript());
16
+ },
17
+ }),
18
+ LanguageDescription.of({
19
+ name: 'TSX',
20
+ extensions: ['tsx'],
21
+ async load() {
22
+ return import('@codemirror/lang-javascript').then((module) => module.javascript({ jsx: true, typescript: true }));
23
+ },
24
+ }),
25
+ LanguageDescription.of({
26
+ name: 'JSX',
27
+ extensions: ['jsx'],
28
+ async load() {
29
+ return import('@codemirror/lang-javascript').then((module) => module.javascript({ jsx: true }));
30
+ },
31
+ }),
32
+ LanguageDescription.of({
33
+ name: 'HTML',
34
+ extensions: ['html'],
35
+ async load() {
36
+ return import('@codemirror/lang-html').then((module) => module.html());
37
+ },
38
+ }),
39
+ LanguageDescription.of({
40
+ name: 'CSS',
41
+ extensions: ['css'],
42
+ async load() {
43
+ return import('@codemirror/lang-css').then((module) => module.css());
44
+ },
45
+ }),
46
+ LanguageDescription.of({
47
+ name: 'SASS',
48
+ extensions: ['sass'],
49
+ async load() {
50
+ return import('@codemirror/lang-sass').then((module) => module.sass({ indented: true }));
51
+ },
52
+ }),
53
+ LanguageDescription.of({
54
+ name: 'SCSS',
55
+ extensions: ['scss'],
56
+ async load() {
57
+ return import('@codemirror/lang-sass').then((module) => module.sass({ indented: false }));
58
+ },
59
+ }),
60
+ LanguageDescription.of({
61
+ name: 'JSON',
62
+ extensions: ['json'],
63
+ async load() {
64
+ return import('@codemirror/lang-json').then((module) => module.json());
65
+ },
66
+ }),
67
+ LanguageDescription.of({
68
+ name: 'Markdown',
69
+ extensions: ['md'],
70
+ async load() {
71
+ return import('@codemirror/lang-markdown').then((module) => module.markdown());
72
+ },
73
+ }),
74
+ LanguageDescription.of({
75
+ name: 'Wasm',
76
+ extensions: ['wat'],
77
+ async load() {
78
+ return import('@codemirror/lang-wast').then((module) => module.wast());
79
+ },
80
+ }),
81
+ LanguageDescription.of({
82
+ name: 'Python',
83
+ extensions: ['py'],
84
+ async load() {
85
+ return import('@codemirror/lang-python').then((module) => module.python());
86
+ },
87
+ }),
88
+ LanguageDescription.of({
89
+ name: 'C++',
90
+ extensions: ['cpp'],
91
+ async load() {
92
+ return import('@codemirror/lang-cpp').then((module) => module.cpp());
93
+ },
94
+ }),
95
+ ];
96
+
97
+ export async function getLanguage(fileName: string) {
98
+ const languageDescription = LanguageDescription.matchFilename(supportedLanguages, fileName);
99
+
100
+ if (languageDescription) {
101
+ return await languageDescription.load();
102
+ }
103
+
104
+ return undefined;
105
+ }
app/components/header/Header.tsx ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { useStore } from '@nanostores/react';
2
+ import { ClientOnly } from 'remix-utils/client-only';
3
+ import { chatStore } from '~/lib/stores/chat';
4
+ import { classNames } from '~/utils/classNames';
5
+ import { HeaderActionButtons } from './HeaderActionButtons.client';
6
+ import { ChatDescription } from '~/lib/persistence/ChatDescription.client';
7
+
8
+ export function Header() {
9
+ const chat = useStore(chatStore);
10
+
11
+ return (
12
+ <header
13
+ className={classNames(
14
+ 'flex items-center bg-bolt-elements-background-depth-1 p-5 border-b h-[var(--header-height)]',
15
+ {
16
+ 'border-transparent': !chat.started,
17
+ 'border-bolt-elements-borderColor': chat.started,
18
+ },
19
+ )}
20
+ >
21
+ <div className="flex items-center gap-2 z-logo text-bolt-elements-textPrimary cursor-pointer">
22
+ <div className="i-ph:sidebar-simple-duotone text-xl" />
23
+ <a href="/" className="text-2xl font-semibold text-accent flex items-center">
24
+ <span className="i-bolt:logo-text?mask w-[46px] inline-block" />
25
+ </a>
26
+ </div>
27
+ {chat.started && ( // Display ChatDescription and HeaderActionButtons only when the chat has started.
28
+ <>
29
+ <span className="flex-1 px-4 truncate text-center text-bolt-elements-textPrimary">
30
+ <ClientOnly>{() => <ChatDescription />}</ClientOnly>
31
+ </span>
32
+ <ClientOnly>
33
+ {() => (
34
+ <div className="mr-1">
35
+ <HeaderActionButtons />
36
+ </div>
37
+ )}
38
+ </ClientOnly>
39
+ </>
40
+ )}
41
+ </header>
42
+ );
43
+ }
app/components/header/HeaderActionButtons.client.tsx ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { useStore } from '@nanostores/react';
2
+ import useViewport from '~/lib/hooks';
3
+ import { chatStore } from '~/lib/stores/chat';
4
+ import { workbenchStore } from '~/lib/stores/workbench';
5
+ import { classNames } from '~/utils/classNames';
6
+
7
+ interface HeaderActionButtonsProps {}
8
+
9
+ export function HeaderActionButtons({}: HeaderActionButtonsProps) {
10
+ const showWorkbench = useStore(workbenchStore.showWorkbench);
11
+ const { showChat } = useStore(chatStore);
12
+
13
+ const isSmallViewport = useViewport(1024);
14
+
15
+ const canHideChat = showWorkbench || !showChat;
16
+
17
+ return (
18
+ <div className="flex">
19
+ <div className="flex border border-bolt-elements-borderColor rounded-md overflow-hidden">
20
+ <Button
21
+ active={showChat}
22
+ disabled={!canHideChat || isSmallViewport} // expand button is disabled on mobile as it's not needed
23
+ onClick={() => {
24
+ if (canHideChat) {
25
+ chatStore.setKey('showChat', !showChat);
26
+ }
27
+ }}
28
+ >
29
+ <div className="i-bolt:chat text-sm" />
30
+ </Button>
31
+ <div className="w-[1px] bg-bolt-elements-borderColor" />
32
+ <Button
33
+ active={showWorkbench}
34
+ onClick={() => {
35
+ if (showWorkbench && !showChat) {
36
+ chatStore.setKey('showChat', true);
37
+ }
38
+
39
+ workbenchStore.showWorkbench.set(!showWorkbench);
40
+ }}
41
+ >
42
+ <div className="i-ph:code-bold" />
43
+ </Button>
44
+ </div>
45
+ </div>
46
+ );
47
+ }
48
+
49
+ interface ButtonProps {
50
+ active?: boolean;
51
+ disabled?: boolean;
52
+ children?: any;
53
+ onClick?: VoidFunction;
54
+ }
55
+
56
+ function Button({ active = false, disabled = false, children, onClick }: ButtonProps) {
57
+ return (
58
+ <button
59
+ className={classNames('flex items-center p-1.5', {
60
+ 'bg-bolt-elements-item-backgroundDefault hover:bg-bolt-elements-item-backgroundActive text-bolt-elements-textTertiary hover:text-bolt-elements-textPrimary':
61
+ !active,
62
+ 'bg-bolt-elements-item-backgroundAccent text-bolt-elements-item-contentAccent': active && !disabled,
63
+ 'bg-bolt-elements-item-backgroundDefault text-alpha-gray-20 dark:text-alpha-white-20 cursor-not-allowed':
64
+ disabled,
65
+ })}
66
+ onClick={onClick}
67
+ >
68
+ {children}
69
+ </button>
70
+ );
71
+ }
app/components/sidebar/HistoryItem.tsx ADDED
@@ -0,0 +1,127 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { useParams } from '@remix-run/react';
2
+ import { classNames } from '~/utils/classNames';
3
+ import * as Dialog from '@radix-ui/react-dialog';
4
+ import { type ChatHistoryItem } from '~/lib/persistence';
5
+ import WithTooltip from '~/components/ui/Tooltip';
6
+ import { useEditChatDescription } from '~/lib/hooks';
7
+
8
+ interface HistoryItemProps {
9
+ item: ChatHistoryItem;
10
+ onDelete?: (event: React.UIEvent) => void;
11
+ onDuplicate?: (id: string) => void;
12
+ exportChat: (id?: string) => void;
13
+ }
14
+
15
+ export function HistoryItem({ item, onDelete, onDuplicate, exportChat }: HistoryItemProps) {
16
+ const { id: urlId } = useParams();
17
+ const isActiveChat = urlId === item.urlId;
18
+
19
+ const { editing, handleChange, handleBlur, handleSubmit, handleKeyDown, currentDescription, toggleEditMode } =
20
+ useEditChatDescription({
21
+ initialDescription: item.description,
22
+ customChatId: item.id,
23
+ syncWithGlobalStore: isActiveChat,
24
+ });
25
+
26
+ const renderDescriptionForm = (
27
+ <form onSubmit={handleSubmit} className="flex-1 flex items-center">
28
+ <input
29
+ type="text"
30
+ className="flex-1 bg-bolt-elements-background-depth-1 text-bolt-elements-textPrimary rounded px-2 mr-2"
31
+ autoFocus
32
+ value={currentDescription}
33
+ onChange={handleChange}
34
+ onBlur={handleBlur}
35
+ onKeyDown={handleKeyDown}
36
+ />
37
+ <button
38
+ type="submit"
39
+ className="i-ph:check scale-110 hover:text-bolt-elements-item-contentAccent"
40
+ onMouseDown={handleSubmit}
41
+ />
42
+ </form>
43
+ );
44
+
45
+ return (
46
+ <div
47
+ className={classNames(
48
+ 'group rounded-md text-bolt-elements-textSecondary hover:text-bolt-elements-textPrimary hover:bg-bolt-elements-background-depth-3 overflow-hidden flex justify-between items-center px-2 py-1',
49
+ { '[&&]:text-bolt-elements-textPrimary bg-bolt-elements-background-depth-3': isActiveChat },
50
+ )}
51
+ >
52
+ {editing ? (
53
+ renderDescriptionForm
54
+ ) : (
55
+ <a href={`/chat/${item.urlId}`} className="flex w-full relative truncate block">
56
+ {currentDescription}
57
+ <div
58
+ className={classNames(
59
+ 'absolute right-0 z-1 top-0 bottom-0 bg-gradient-to-l from-bolt-elements-background-depth-2 group-hover:from-bolt-elements-background-depth-3 box-content pl-3 to-transparent w-10 flex justify-end group-hover:w-22 group-hover:from-99%',
60
+ { 'from-bolt-elements-background-depth-3 w-10 ': isActiveChat },
61
+ )}
62
+ >
63
+ <div className="flex items-center p-1 text-bolt-elements-textSecondary opacity-0 group-hover:opacity-100 transition-opacity">
64
+ <ChatActionButton
65
+ toolTipContent="Export chat"
66
+ icon="i-ph:download-simple"
67
+ onClick={(event) => {
68
+ event.preventDefault();
69
+ exportChat(item.id);
70
+ }}
71
+ />
72
+ {onDuplicate && (
73
+ <ChatActionButton
74
+ toolTipContent="Duplicate chat"
75
+ icon="i-ph:copy"
76
+ onClick={() => onDuplicate?.(item.id)}
77
+ />
78
+ )}
79
+ <ChatActionButton
80
+ toolTipContent="Rename chat"
81
+ icon="i-ph:pencil-fill"
82
+ onClick={(event) => {
83
+ event.preventDefault();
84
+ toggleEditMode();
85
+ }}
86
+ />
87
+ <Dialog.Trigger asChild>
88
+ <ChatActionButton
89
+ toolTipContent="Delete chat"
90
+ icon="i-ph:trash"
91
+ className="[&&]:hover:text-bolt-elements-button-danger-text"
92
+ onClick={(event) => {
93
+ event.preventDefault();
94
+ onDelete?.(event);
95
+ }}
96
+ />
97
+ </Dialog.Trigger>
98
+ </div>
99
+ </div>
100
+ </a>
101
+ )}
102
+ </div>
103
+ );
104
+ }
105
+
106
+ const ChatActionButton = ({
107
+ toolTipContent,
108
+ icon,
109
+ className,
110
+ onClick,
111
+ }: {
112
+ toolTipContent: string;
113
+ icon: string;
114
+ className?: string;
115
+ onClick: (event: React.MouseEvent<HTMLButtonElement, MouseEvent>) => void;
116
+ btnTitle?: string;
117
+ }) => {
118
+ return (
119
+ <WithTooltip tooltip={toolTipContent}>
120
+ <button
121
+ type="button"
122
+ className={`scale-110 mr-2 hover:text-bolt-elements-item-contentAccent ${icon} ${className ? className : ''}`}
123
+ onClick={onClick}
124
+ />
125
+ </WithTooltip>
126
+ );
127
+ };
app/components/sidebar/Menu.client.tsx ADDED
@@ -0,0 +1,209 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { motion, type Variants } from 'framer-motion';
2
+ import { useCallback, useEffect, useRef, useState } from 'react';
3
+ import { toast } from 'react-toastify';
4
+ import { Dialog, DialogButton, DialogDescription, DialogRoot, DialogTitle } from '~/components/ui/Dialog';
5
+ import { ThemeSwitch } from '~/components/ui/ThemeSwitch';
6
+ import { db, deleteById, getAll, chatId, type ChatHistoryItem, useChatHistory } from '~/lib/persistence';
7
+ import { cubicEasingFn } from '~/utils/easings';
8
+ import { logger } from '~/utils/logger';
9
+ import { HistoryItem } from './HistoryItem';
10
+ import { binDates } from './date-binning';
11
+ import { useSearchFilter } from '~/lib/hooks/useSearchFilter';
12
+
13
+ const menuVariants = {
14
+ closed: {
15
+ opacity: 0,
16
+ visibility: 'hidden',
17
+ left: '-150px',
18
+ transition: {
19
+ duration: 0.2,
20
+ ease: cubicEasingFn,
21
+ },
22
+ },
23
+ open: {
24
+ opacity: 1,
25
+ visibility: 'initial',
26
+ left: 0,
27
+ transition: {
28
+ duration: 0.2,
29
+ ease: cubicEasingFn,
30
+ },
31
+ },
32
+ } satisfies Variants;
33
+
34
+ type DialogContent = { type: 'delete'; item: ChatHistoryItem } | null;
35
+
36
+ export const Menu = () => {
37
+ const { duplicateCurrentChat, exportChat } = useChatHistory();
38
+ const menuRef = useRef<HTMLDivElement>(null);
39
+ const [list, setList] = useState<ChatHistoryItem[]>([]);
40
+ const [open, setOpen] = useState(false);
41
+ const [dialogContent, setDialogContent] = useState<DialogContent>(null);
42
+
43
+ const { filteredItems: filteredList, handleSearchChange } = useSearchFilter({
44
+ items: list,
45
+ searchFields: ['description'],
46
+ });
47
+
48
+ const loadEntries = useCallback(() => {
49
+ if (db) {
50
+ getAll(db)
51
+ .then((list) => list.filter((item) => item.urlId && item.description))
52
+ .then(setList)
53
+ .catch((error) => toast.error(error.message));
54
+ }
55
+ }, []);
56
+
57
+ const deleteItem = useCallback((event: React.UIEvent, item: ChatHistoryItem) => {
58
+ event.preventDefault();
59
+
60
+ if (db) {
61
+ deleteById(db, item.id)
62
+ .then(() => {
63
+ loadEntries();
64
+
65
+ if (chatId.get() === item.id) {
66
+ // hard page navigation to clear the stores
67
+ window.location.pathname = '/';
68
+ }
69
+ })
70
+ .catch((error) => {
71
+ toast.error('Failed to delete conversation');
72
+ logger.error(error);
73
+ });
74
+ }
75
+ }, []);
76
+
77
+ const closeDialog = () => {
78
+ setDialogContent(null);
79
+ };
80
+
81
+ useEffect(() => {
82
+ if (open) {
83
+ loadEntries();
84
+ }
85
+ }, [open]);
86
+
87
+ useEffect(() => {
88
+ const enterThreshold = 40;
89
+ const exitThreshold = 40;
90
+
91
+ function onMouseMove(event: MouseEvent) {
92
+ if (event.pageX < enterThreshold) {
93
+ setOpen(true);
94
+ }
95
+
96
+ if (menuRef.current && event.clientX > menuRef.current.getBoundingClientRect().right + exitThreshold) {
97
+ setOpen(false);
98
+ }
99
+ }
100
+
101
+ window.addEventListener('mousemove', onMouseMove);
102
+
103
+ return () => {
104
+ window.removeEventListener('mousemove', onMouseMove);
105
+ };
106
+ }, []);
107
+
108
+ const handleDeleteClick = (event: React.UIEvent, item: ChatHistoryItem) => {
109
+ event.preventDefault();
110
+ setDialogContent({ type: 'delete', item });
111
+ };
112
+
113
+ const handleDuplicate = async (id: string) => {
114
+ await duplicateCurrentChat(id);
115
+ loadEntries(); // Reload the list after duplication
116
+ };
117
+
118
+ return (
119
+ <motion.div
120
+ ref={menuRef}
121
+ initial="closed"
122
+ animate={open ? 'open' : 'closed'}
123
+ variants={menuVariants}
124
+ className="flex selection-accent flex-col side-menu fixed top-0 w-[350px] h-full bg-bolt-elements-background-depth-2 border-r rounded-r-3xl border-bolt-elements-borderColor z-sidebar shadow-xl shadow-bolt-elements-sidebar-dropdownShadow text-sm"
125
+ >
126
+ <div className="flex items-center h-[var(--header-height)]">{/* Placeholder */}</div>
127
+ <div className="flex-1 flex flex-col h-full w-full overflow-hidden">
128
+ <div className="p-4 select-none">
129
+ <a
130
+ href="/"
131
+ className="flex gap-2 items-center bg-bolt-elements-sidebar-buttonBackgroundDefault text-bolt-elements-sidebar-buttonText hover:bg-bolt-elements-sidebar-buttonBackgroundHover rounded-md p-2 transition-theme"
132
+ >
133
+ <span className="inline-block i-bolt:chat scale-110" />
134
+ Start new chat
135
+ </a>
136
+ </div>
137
+ <div className="pl-4 pr-4 my-2">
138
+ <div className="relative w-full">
139
+ <input
140
+ className="w-full bg-white dark:bg-bolt-elements-background-depth-4 relative px-2 py-1.5 rounded-md focus:outline-none placeholder-bolt-elements-textTertiary text-bolt-elements-textPrimary dark:text-bolt-elements-textPrimary border border-bolt-elements-borderColor"
141
+ type="search"
142
+ placeholder="Search"
143
+ onChange={handleSearchChange}
144
+ aria-label="Search chats"
145
+ />
146
+ </div>
147
+ </div>
148
+ <div className="text-bolt-elements-textPrimary font-medium pl-6 pr-5 my-2">Your Chats</div>
149
+ <div className="flex-1 overflow-auto pl-4 pr-5 pb-5">
150
+ {filteredList.length === 0 && (
151
+ <div className="pl-2 text-bolt-elements-textTertiary">
152
+ {list.length === 0 ? 'No previous conversations' : 'No matches found'}
153
+ </div>
154
+ )}
155
+ <DialogRoot open={dialogContent !== null}>
156
+ {binDates(filteredList).map(({ category, items }) => (
157
+ <div key={category} className="mt-4 first:mt-0 space-y-1">
158
+ <div className="text-bolt-elements-textTertiary sticky top-0 z-1 bg-bolt-elements-background-depth-2 pl-2 pt-2 pb-1">
159
+ {category}
160
+ </div>
161
+ {items.map((item) => (
162
+ <HistoryItem
163
+ key={item.id}
164
+ item={item}
165
+ exportChat={exportChat}
166
+ onDelete={(event) => handleDeleteClick(event, item)}
167
+ onDuplicate={() => handleDuplicate(item.id)}
168
+ />
169
+ ))}
170
+ </div>
171
+ ))}
172
+ <Dialog onBackdrop={closeDialog} onClose={closeDialog}>
173
+ {dialogContent?.type === 'delete' && (
174
+ <>
175
+ <DialogTitle>Delete Chat?</DialogTitle>
176
+ <DialogDescription asChild>
177
+ <div>
178
+ <p>
179
+ You are about to delete <strong>{dialogContent.item.description}</strong>.
180
+ </p>
181
+ <p className="mt-1">Are you sure you want to delete this chat?</p>
182
+ </div>
183
+ </DialogDescription>
184
+ <div className="px-5 pb-4 bg-bolt-elements-background-depth-2 flex gap-2 justify-end">
185
+ <DialogButton type="secondary" onClick={closeDialog}>
186
+ Cancel
187
+ </DialogButton>
188
+ <DialogButton
189
+ type="danger"
190
+ onClick={(event) => {
191
+ deleteItem(event, dialogContent.item);
192
+ closeDialog();
193
+ }}
194
+ >
195
+ Delete
196
+ </DialogButton>
197
+ </div>
198
+ </>
199
+ )}
200
+ </Dialog>
201
+ </DialogRoot>
202
+ </div>
203
+ <div className="flex items-center border-t border-bolt-elements-borderColor p-4">
204
+ <ThemeSwitch className="ml-auto" />
205
+ </div>
206
+ </div>
207
+ </motion.div>
208
+ );
209
+ };
app/components/sidebar/date-binning.ts ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { format, isAfter, isThisWeek, isThisYear, isToday, isYesterday, subDays } from 'date-fns';
2
+ import type { ChatHistoryItem } from '~/lib/persistence';
3
+
4
+ type Bin = { category: string; items: ChatHistoryItem[] };
5
+
6
+ export function binDates(_list: ChatHistoryItem[]) {
7
+ const list = _list.toSorted((a, b) => Date.parse(b.timestamp) - Date.parse(a.timestamp));
8
+
9
+ const binLookup: Record<string, Bin> = {};
10
+ const bins: Array<Bin> = [];
11
+
12
+ list.forEach((item) => {
13
+ const category = dateCategory(new Date(item.timestamp));
14
+
15
+ if (!(category in binLookup)) {
16
+ const bin = {
17
+ category,
18
+ items: [item],
19
+ };
20
+
21
+ binLookup[category] = bin;
22
+
23
+ bins.push(bin);
24
+ } else {
25
+ binLookup[category].items.push(item);
26
+ }
27
+ });
28
+
29
+ return bins;
30
+ }
31
+
32
+ function dateCategory(date: Date) {
33
+ if (isToday(date)) {
34
+ return 'Today';
35
+ }
36
+
37
+ if (isYesterday(date)) {
38
+ return 'Yesterday';
39
+ }
40
+
41
+ if (isThisWeek(date)) {
42
+ // e.g., "Monday"
43
+ return format(date, 'eeee');
44
+ }
45
+
46
+ const thirtyDaysAgo = subDays(new Date(), 30);
47
+
48
+ if (isAfter(date, thirtyDaysAgo)) {
49
+ return 'Last 30 Days';
50
+ }
51
+
52
+ if (isThisYear(date)) {
53
+ // e.g., "July"
54
+ return format(date, 'MMMM');
55
+ }
56
+
57
+ // e.g., "July 2023"
58
+ return format(date, 'MMMM yyyy');
59
+ }