codacus commited on
Commit
8067bb6
·
2 Parent(s): 7fd364d 2af32b0

Merge branch 'main' into ui-background-rays

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .env.example +24 -0
  2. .github/ISSUE_TEMPLATE/bug_report.yml +10 -0
  3. .github/workflows/docs.yaml +33 -0
  4. .github/workflows/stale.yml +25 -0
  5. .gitignore +5 -0
  6. .husky/commit-msg +0 -7
  7. .husky/pre-commit +20 -0
  8. CONTRIBUTING.md +18 -2
  9. Dockerfile +18 -2
  10. FAQ.md +54 -0
  11. README.md +44 -56
  12. app/components/chat/APIKeyManager.tsx +30 -12
  13. app/components/chat/Artifact.tsx +37 -3
  14. app/components/chat/BaseChat.module.scss +104 -0
  15. app/components/chat/BaseChat.tsx +333 -121
  16. app/components/chat/Chat.client.tsx +272 -192
  17. app/components/chat/ExamplePrompts.tsx +36 -0
  18. app/components/chat/FilePreview.tsx +35 -0
  19. app/components/chat/ImportFolderButton.tsx +164 -0
  20. app/components/chat/Markdown.spec.ts +48 -0
  21. app/components/chat/Markdown.tsx +45 -1
  22. app/components/chat/Messages.client.tsx +54 -1
  23. app/components/chat/ModelSelector.tsx +63 -0
  24. app/components/chat/SendButton.client.tsx +3 -2
  25. app/components/chat/SpeechRecognition.tsx +28 -0
  26. app/components/chat/UserMessage.tsx +38 -6
  27. app/components/chat/chatExportAndImport/ExportChatButton.tsx +13 -0
  28. app/components/chat/chatExportAndImport/ImportButtons.tsx +71 -0
  29. app/components/header/Header.tsx +13 -11
  30. app/components/header/HeaderActionButtons.client.tsx +4 -1
  31. app/components/sidebar/HistoryItem.tsx +102 -39
  32. app/components/sidebar/Menu.client.tsx +47 -10
  33. app/components/ui/Tooltip.tsx +73 -0
  34. app/components/workbench/EditorPanel.tsx +6 -169
  35. app/components/workbench/FileTree.tsx +1 -1
  36. app/components/workbench/Preview.tsx +234 -12
  37. app/components/workbench/Workbench.client.tsx +24 -11
  38. app/components/workbench/terminal/Terminal.tsx +65 -62
  39. app/components/workbench/terminal/TerminalTabs.tsx +186 -0
  40. app/entry.server.tsx +1 -1
  41. app/lib/.server/llm/api-key.ts +30 -15
  42. app/lib/.server/llm/model.ts +64 -26
  43. app/lib/.server/llm/prompts.ts +2 -2
  44. app/lib/.server/llm/stream-text.ts +44 -24
  45. app/lib/hooks/index.ts +2 -0
  46. app/lib/hooks/useEditChatDescription.ts +163 -0
  47. app/lib/hooks/usePromptEnhancer.ts +19 -18
  48. app/lib/hooks/useSearchFilter.ts +52 -0
  49. app/lib/hooks/useViewport.ts +18 -0
  50. app/lib/persistence/ChatDescription.client.tsx +64 -2
.env.example CHANGED
@@ -5,6 +5,12 @@
5
  # You only need this environment variable set if you want to use Groq models
6
  GROQ_API_KEY=
7
 
 
 
 
 
 
 
8
  # Get your Open AI API Key by following these instructions -
9
  # https://help.openai.com/en/articles/4936850-where-do-i-find-my-openai-api-key
10
  # You only need this environment variable set if you want to use GPT models
@@ -32,17 +38,27 @@ OLLAMA_API_BASE_URL=
32
  # You only need this environment variable set if you want to use OpenAI Like models
33
  OPENAI_LIKE_API_BASE_URL=
34
 
 
 
 
35
  # You only need this environment variable set if you want to use DeepSeek models through their API
36
  DEEPSEEK_API_KEY=
37
 
38
  # Get your OpenAI Like API Key
39
  OPENAI_LIKE_API_KEY=
40
 
 
 
 
41
  # Get your Mistral API Key by following these instructions -
42
  # https://console.mistral.ai/api-keys/
43
  # You only need this environment variable set if you want to use Mistral models
44
  MISTRAL_API_KEY=
45
 
 
 
 
 
46
 
47
  # Get LMStudio Base URL from LM Studio Developer Console
48
  # Make sure to enable CORS
@@ -56,3 +72,11 @@ XAI_API_KEY=
56
 
57
  # Include this environment variable if you want more logging for debugging locally
58
  VITE_LOG_LEVEL=debug
 
 
 
 
 
 
 
 
 
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
 
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
 
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 CHANGED
@@ -56,6 +56,16 @@ body:
56
  - OS: [e.g. macOS, Windows, Linux]
57
  - Browser: [e.g. Chrome, Safari, Firefox]
58
  - Version: [e.g. 91.1]
 
 
 
 
 
 
 
 
 
 
59
  - type: textarea
60
  id: additional
61
  attributes:
 
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:
.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 CHANGED
@@ -22,13 +22,18 @@ dist-ssr
22
  *.sln
23
  *.sw?
24
 
 
25
  /.cache
26
  /build
27
  .env.local
28
  .env
 
29
  *.vars
30
  .wrangler
31
  _worker.bundle
32
 
33
  Modelfile
34
  modelfiles
 
 
 
 
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/commit-msg DELETED
@@ -1,7 +0,0 @@
1
- #!/usr/bin/env sh
2
-
3
- . "$(dirname "$0")/_/husky.sh"
4
-
5
- npx commitlint --edit $1
6
-
7
- exit 0
 
 
 
 
 
 
 
 
.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..."
CONTRIBUTING.md CHANGED
@@ -1,6 +1,6 @@
1
- # Contributing to Bolt.new Fork
2
 
3
- First off, thank you for considering contributing to Bolt.new! This fork aims to expand the capabilities of the original project by integrating multiple LLM providers and enhancing functionality. Every contribution helps make Bolt.new a better tool for developers worldwide.
4
 
5
  ## 📋 Table of Contents
6
  - [Code of Conduct](#code-of-conduct)
@@ -53,6 +53,8 @@ We're looking for dedicated contributors to help maintain and grow this project.
53
  - Comment complex logic
54
  - Keep functions focused and small
55
  - Use meaningful variable names
 
 
56
 
57
  ## Development Setup
58
 
@@ -72,6 +74,7 @@ pnpm install
72
  - Add your LLM API keys (only set the ones you plan to use):
73
  ```bash
74
  GROQ_API_KEY=XXX
 
75
  OPENAI_API_KEY=XXX
76
  ANTHROPIC_API_KEY=XXX
77
  ...
@@ -80,6 +83,19 @@ ANTHROPIC_API_KEY=XXX
80
  ```bash
81
  VITE_LOG_LEVEL=debug
82
  ```
 
 
 
 
 
 
 
 
 
 
 
 
 
83
  **Important**: Never commit your `.env.local` file to version control. It's already included in .gitignore.
84
 
85
  ### 🚀 Running the Development Server
 
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)
 
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
 
 
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
  ...
 
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
Dockerfile CHANGED
@@ -19,21 +19,29 @@ 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 OPENAI_API_KEY
23
  ARG ANTHROPIC_API_KEY
24
  ARG OPEN_ROUTER_API_KEY
25
  ARG GOOGLE_GENERATIVE_AI_API_KEY
26
  ARG OLLAMA_API_BASE_URL
 
 
27
  ARG VITE_LOG_LEVEL=debug
 
28
 
29
  ENV WRANGLER_SEND_METRICS=false \
30
  GROQ_API_KEY=${GROQ_API_KEY} \
 
31
  OPENAI_API_KEY=${OPENAI_API_KEY} \
32
  ANTHROPIC_API_KEY=${ANTHROPIC_API_KEY} \
33
  OPEN_ROUTER_API_KEY=${OPEN_ROUTER_API_KEY} \
34
  GOOGLE_GENERATIVE_AI_API_KEY=${GOOGLE_GENERATIVE_AI_API_KEY} \
35
  OLLAMA_API_BASE_URL=${OLLAMA_API_BASE_URL} \
36
- VITE_LOG_LEVEL=${VITE_LOG_LEVEL}
 
 
 
37
 
38
  # Pre-configure wrangler to disable metrics
39
  RUN mkdir -p /root/.config/.wrangler && \
@@ -48,20 +56,28 @@ FROM base AS bolt-ai-development
48
 
49
  # Define the same environment variables for development
50
  ARG GROQ_API_KEY
 
51
  ARG OPENAI_API_KEY
52
  ARG ANTHROPIC_API_KEY
53
  ARG OPEN_ROUTER_API_KEY
54
  ARG GOOGLE_GENERATIVE_AI_API_KEY
55
  ARG OLLAMA_API_BASE_URL
 
 
56
  ARG VITE_LOG_LEVEL=debug
 
57
 
58
  ENV GROQ_API_KEY=${GROQ_API_KEY} \
 
59
  OPENAI_API_KEY=${OPENAI_API_KEY} \
60
  ANTHROPIC_API_KEY=${ANTHROPIC_API_KEY} \
61
  OPEN_ROUTER_API_KEY=${OPEN_ROUTER_API_KEY} \
62
  GOOGLE_GENERATIVE_AI_API_KEY=${GOOGLE_GENERATIVE_AI_API_KEY} \
63
  OLLAMA_API_BASE_URL=${OLLAMA_API_BASE_URL} \
64
- VITE_LOG_LEVEL=${VITE_LOG_LEVEL}
 
 
 
65
 
66
  RUN mkdir -p ${WORKDIR}/run
67
  CMD pnpm run dev --host
 
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 && \
 
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!
README.md CHANGED
@@ -1,10 +1,17 @@
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
4
 
5
- This fork of Bolt.new allows you to choose the LLM that you use for each prompt! Currently, you can use OpenAI, Anthropic, Ollama, OpenRouter, Gemini, or Groq models - and it is easily extended to use any other model supported by the Vercel AI SDK! See the instructions below for running this locally and extending it to include more models.
6
 
7
- # Requested Additions to this Fork - Feel Free to Contribute!!
 
 
 
 
 
 
 
8
 
9
  - ✅ OpenRouter Integration (@coleam00)
10
  - ✅ Gemini Integration (@jonathands)
@@ -20,28 +27,33 @@ This fork of Bolt.new allows you to choose the LLM that you use for each prompt!
20
  - ✅ Publish projects directly to GitHub (@goncaloalves)
21
  - ✅ Ability to enter API keys in the UI (@ali00209)
22
  - ✅ xAI Grok Beta Integration (@milutinke)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
23
  - ⬜ **HIGH PRIORITY** - Prevent Bolt from rewriting files as often (file locking and diffs)
24
  - ⬜ **HIGH PRIORITY** - Better prompting for smaller LLMs (code window sometimes doesn't start)
25
- - ⬜ **HIGH PRIORITY** Load local projects into the app
26
- - ⬜ **HIGH PRIORITY** - Attach images to prompts
27
  - ⬜ **HIGH PRIORITY** - Run agents in the backend as opposed to a single model call
28
- - ⬜ LM Studio Integration
29
- - ⬜ Together Integration
30
- - ⬜ Azure Open AI API Integration
31
- - ⬜ HuggingFace Integration
32
- - ⬜ Perplexity Integration
33
- - ⬜ Vertex AI Integration
34
- - ⬜ Cohere Integration
35
  - ⬜ Deploy directly to Vercel/Netlify/other similar platforms
36
- - ⬜ Ability to revert code to earlier version
37
- - ⬜ Prompt caching
38
- - ⬜ Better prompt enhancing
39
  - ⬜ Have LLM plan the project in a MD file for better results/transparency
40
  - ⬜ VSCode Integration with git-like confirmations
41
  - ⬜ Upload documents for knowledge - UI design templates, a code base to reference coding style, etc.
42
  - ⬜ Voice prompting
 
 
 
43
 
44
- # Bolt.new: AI-Powered Full-Stack Web Development in the Browser
45
 
46
  Bolt.new is an AI-powered web development agent that allows you to prompt, run, edit, and deploy full-stack applications directly from your browser—no local setup required. If you're here to build your own AI-powered web dev agent using the Bolt open source codebase, [click here to get started!](./CONTRIBUTING.md)
47
 
@@ -116,6 +128,13 @@ Optionally, you can set the debug level:
116
  VITE_LOG_LEVEL=debug
117
  ```
118
 
 
 
 
 
 
 
 
119
  **Important**: Never commit your `.env.local` file to version control. It's already included in .gitignore.
120
 
121
  ## Run with Docker
@@ -183,40 +202,6 @@ sudo npm install -g pnpm
183
  ```bash
184
  pnpm run dev
185
  ```
186
-
187
- ## Super Important Note on Running Ollama Models
188
-
189
- Ollama models by default only have 2048 tokens for their context window. Even for large models that can easily handle way more.
190
- This is not a large enough window to handle the Bolt.new/oTToDev prompt! You have to create a version of any model you want
191
- to use where you specify a larger context window. Luckily it's super easy to do that.
192
-
193
- All you have to do is:
194
-
195
- - Create a file called "Modelfile" (no file extension) anywhere on your computer
196
- - Put in the two lines:
197
-
198
- ```
199
- FROM [Ollama model ID such as qwen2.5-coder:7b]
200
- PARAMETER num_ctx 32768
201
- ```
202
-
203
- - Run the command:
204
-
205
- ```
206
- ollama create -f Modelfile [your new model ID, can be whatever you want (example: qwen2.5-coder-extra-ctx:7b)]
207
- ```
208
-
209
- Now you have a new Ollama model that isn't heavily limited in the context length like Ollama models are by default for some reason.
210
- You'll see this new model in the list of Ollama models along with all the others you pulled!
211
-
212
- ## Adding New LLMs:
213
-
214
- 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.
215
-
216
- 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!
217
-
218
- 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!
219
-
220
  ## Available Scripts
221
 
222
  - `pnpm run dev`: Starts the development server.
@@ -227,6 +212,7 @@ When you add a new model to the MODEL_LIST array, it will immediately be availab
227
  - `pnpm run typecheck`: Runs TypeScript type checking.
228
  - `pnpm run typegen`: Generates TypeScript types using Wrangler.
229
  - `pnpm run deploy`: Builds the project and deploys it to Cloudflare Pages.
 
230
 
231
  ## Development
232
 
@@ -238,14 +224,16 @@ pnpm run dev
238
 
239
  This will start the Remix Vite development server. 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.
240
 
241
- ## Tips and Tricks
 
 
242
 
243
- Here are some tips to get the most out of Bolt.new:
244
 
245
- - **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.
246
 
247
- - **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.
248
 
249
- - **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 Bolt understand the foundation of your project and ensure everything is wired up right before building out more advanced functionality.
250
 
251
- - **Batch simple instructions**: Save time by combining simple instructions into one message. For example, you can ask Bolt 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.
 
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
+ This fork of Bolt.new (oTToDev) allows you to choose the LLM that you use for each prompt! Currently, you can use OpenAI, Anthropic, Ollama, OpenRouter, Gemini, LMStudio, Mistral, xAI, HuggingFace, DeepSeek, or Groq models - and it is easily extended to use any other model supported by the Vercel AI SDK! See the instructions below for running this locally and extending it to include more models.
6
 
7
+ Check the [oTToDev Docs](https://coleam00.github.io/bolt.new-any-llm/) for more information.
8
+
9
+ ## Join the community for oTToDev!
10
+
11
+ https://thinktank.ottomator.ai
12
+
13
+
14
+ ## Requested Additions - Feel Free to Contribute!
15
 
16
  - ✅ OpenRouter Integration (@coleam00)
17
  - ✅ Gemini Integration (@jonathands)
 
27
  - ✅ Publish projects directly to GitHub (@goncaloalves)
28
  - ✅ Ability to enter API keys in the UI (@ali00209)
29
  - ✅ xAI Grok Beta Integration (@milutinke)
30
+ - ✅ LM Studio Integration (@karrot0)
31
+ - ✅ HuggingFace Integration (@ahsan3219)
32
+ - ✅ Bolt terminal to see the output of LLM run commands (@thecodacus)
33
+ - ✅ Streaming of code output (@thecodacus)
34
+ - ✅ Ability to revert code to earlier version (@wonderwhy-er)
35
+ - ✅ Cohere Integration (@hasanraiyan)
36
+ - ✅ Dynamic model max token length (@hasanraiyan)
37
+ - ✅ Better prompt enhancing (@SujalXplores)
38
+ - ✅ Prompt caching (@SujalXplores)
39
+ - ✅ Load local projects into the app (@wonderwhy-er)
40
+ - ✅ Together Integration (@mouimet-infinisoft)
41
+ - ✅ Mobile friendly (@qwikode)
42
+ - ✅ Better prompt enhancing (@SujalXplores)
43
+ - ✅ Attach images to prompts (@atrokhym)
44
  - ⬜ **HIGH PRIORITY** - Prevent Bolt from rewriting files as often (file locking and diffs)
45
  - ⬜ **HIGH PRIORITY** - Better prompting for smaller LLMs (code window sometimes doesn't start)
 
 
46
  - ⬜ **HIGH PRIORITY** - Run agents in the backend as opposed to a single model call
 
 
 
 
 
 
 
47
  - ⬜ Deploy directly to Vercel/Netlify/other similar platforms
 
 
 
48
  - ⬜ Have LLM plan the project in a MD file for better results/transparency
49
  - ⬜ VSCode Integration with git-like confirmations
50
  - ⬜ Upload documents for knowledge - UI design templates, a code base to reference coding style, etc.
51
  - ⬜ Voice prompting
52
+ - ⬜ Azure Open AI API Integration
53
+ - ⬜ Perplexity Integration
54
+ - ⬜ Vertex AI Integration
55
 
56
+ ## Bolt.new: AI-Powered Full-Stack Web Development in the Browser
57
 
58
  Bolt.new is an AI-powered web development agent that allows you to prompt, run, edit, and deploy full-stack applications directly from your browser—no local setup required. If you're here to build your own AI-powered web dev agent using the Bolt open source codebase, [click here to get started!](./CONTRIBUTING.md)
59
 
 
128
  VITE_LOG_LEVEL=debug
129
  ```
130
 
131
+ And if using Ollama set the DEFAULT_NUM_CTX, the example below uses 8K context and ollama running on localhost port 11434:
132
+
133
+ ```
134
+ OLLAMA_API_BASE_URL=http://localhost:11434
135
+ DEFAULT_NUM_CTX=8192
136
+ ```
137
+
138
  **Important**: Never commit your `.env.local` file to version control. It's already included in .gitignore.
139
 
140
  ## Run with Docker
 
202
  ```bash
203
  pnpm run dev
204
  ```
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
205
  ## Available Scripts
206
 
207
  - `pnpm run dev`: Starts the development server.
 
212
  - `pnpm run typecheck`: Runs TypeScript type checking.
213
  - `pnpm run typegen`: Generates TypeScript types using Wrangler.
214
  - `pnpm run deploy`: Builds the project and deploys it to Cloudflare Pages.
215
+ - `pnpm run lint:fix`: Runs the linter and automatically fixes issues according to your ESLint configuration.
216
 
217
  ## Development
218
 
 
224
 
225
  This will start the Remix Vite development server. 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.
226
 
227
+ ## How do I contribute to oTToDev?
228
+
229
+ [Please check out our dedicated page for contributing to oTToDev here!](CONTRIBUTING.md)
230
 
231
+ ## What are the future plans for oTToDev?
232
 
233
+ [Check out our Roadmap here!](https://roadmap.sh/r/ottodev-roadmap-2ovzo)
234
 
235
+ Lot more updates to this roadmap coming soon!
236
 
237
+ ## FAQ
238
 
239
+ [Please check out our dedicated page for FAQ's related to oTToDev here!](FAQ.md)
app/components/chat/APIKeyManager.tsx CHANGED
@@ -1,12 +1,16 @@
1
  import React, { useState } from 'react';
2
  import { IconButton } from '~/components/ui/IconButton';
 
3
 
4
  interface APIKeyManagerProps {
5
- provider: string;
6
  apiKey: string;
7
  setApiKey: (key: string) => void;
 
 
8
  }
9
 
 
10
  export const APIKeyManager: React.FC<APIKeyManagerProps> = ({ provider, apiKey, setApiKey }) => {
11
  const [isEditing, setIsEditing] = useState(false);
12
  const [tempKey, setTempKey] = useState(apiKey);
@@ -17,15 +21,29 @@ export const APIKeyManager: React.FC<APIKeyManagerProps> = ({ provider, apiKey,
17
  };
18
 
19
  return (
20
- <div className="flex items-center gap-2 mt-2 mb-2">
21
- <span className="text-sm text-bolt-elements-textSecondary">{provider} API Key:</span>
 
 
 
 
 
 
 
 
 
 
 
 
 
22
  {isEditing ? (
23
- <>
24
  <input
25
  type="password"
26
  value={tempKey}
 
27
  onChange={(e) => setTempKey(e.target.value)}
28
- className="flex-1 p-1 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"
29
  />
30
  <IconButton onClick={handleSave} title="Save API Key">
31
  <div className="i-ph:check" />
@@ -33,15 +51,15 @@ export const APIKeyManager: React.FC<APIKeyManagerProps> = ({ provider, apiKey,
33
  <IconButton onClick={() => setIsEditing(false)} title="Cancel">
34
  <div className="i-ph:x" />
35
  </IconButton>
36
- </>
37
  ) : (
38
  <>
39
- <span className="flex-1 text-sm text-bolt-elements-textPrimary">
40
- {apiKey ? '••••••••' : 'Not set (will still work if set in .env file)'}
41
- </span>
42
- <IconButton onClick={() => setIsEditing(true)} title="Edit API Key">
43
- <div className="i-ph:pencil-simple" />
44
- </IconButton>
45
  </>
46
  )}
47
  </div>
 
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);
 
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" />
 
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>
app/components/chat/Artifact.tsx CHANGED
@@ -7,6 +7,7 @@ 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
 
11
  const highlighterOptions = {
12
  langs: ['shell'],
@@ -27,6 +28,7 @@ interface ArtifactProps {
27
  export const Artifact = memo(({ messageId }: ArtifactProps) => {
28
  const userToggledActions = useRef(false);
29
  const [showActions, setShowActions] = useState(false);
 
30
 
31
  const artifacts = useStore(workbenchStore.artifacts);
32
  const artifact = artifacts[messageId];
@@ -46,6 +48,14 @@ export const Artifact = memo(({ messageId }: ArtifactProps) => {
46
  if (actions.length && !showActions && !userToggledActions.current) {
47
  setShowActions(true);
48
  }
 
 
 
 
 
 
 
 
49
  }, [actions]);
50
 
51
  return (
@@ -58,6 +68,18 @@ export const Artifact = memo(({ messageId }: ArtifactProps) => {
58
  workbenchStore.showWorkbench.set(!showWorkbench);
59
  }}
60
  >
 
 
 
 
 
 
 
 
 
 
 
 
61
  <div className="px-5 p-3.5 w-full text-left">
62
  <div className="w-full text-bolt-elements-textPrimary font-medium leading-5 text-sm">{artifact?.title}</div>
63
  <div className="w-full w-full text-bolt-elements-textSecondary text-xs mt-0.5">Click to open Workbench</div>
@@ -65,7 +87,7 @@ export const Artifact = memo(({ messageId }: ArtifactProps) => {
65
  </button>
66
  <div className="bg-bolt-elements-artifacts-borderColor w-[1px]" />
67
  <AnimatePresence>
68
- {actions.length && (
69
  <motion.button
70
  initial={{ width: 0 }}
71
  animate={{ width: 'auto' }}
@@ -82,7 +104,7 @@ export const Artifact = memo(({ messageId }: ArtifactProps) => {
82
  </AnimatePresence>
83
  </div>
84
  <AnimatePresence>
85
- {showActions && actions.length > 0 && (
86
  <motion.div
87
  className="actions"
88
  initial={{ height: 0 }}
@@ -91,6 +113,7 @@ export const Artifact = memo(({ messageId }: ArtifactProps) => {
91
  transition={{ duration: 0.15 }}
92
  >
93
  <div className="bg-bolt-elements-artifacts-borderColor h-[1px]" />
 
94
  <div className="p-5 text-left bg-bolt-elements-actions-background">
95
  <ActionList actions={actions} />
96
  </div>
@@ -129,6 +152,14 @@ const actionVariants = {
129
  visible: { opacity: 1, y: 0 },
130
  };
131
 
 
 
 
 
 
 
 
 
132
  const ActionList = memo(({ actions }: ActionListProps) => {
133
  return (
134
  <motion.div initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }} transition={{ duration: 0.15 }}>
@@ -169,7 +200,10 @@ const ActionList = memo(({ actions }: ActionListProps) => {
169
  {type === 'file' ? (
170
  <div>
171
  Create{' '}
172
- <code className="bg-bolt-elements-artifacts-inlineCode-background text-bolt-elements-artifacts-inlineCode-text px-1.5 py-1 rounded-md">
 
 
 
173
  {action.filePath}
174
  </code>
175
  </div>
 
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'],
 
28
  export const Artifact = memo(({ messageId }: ArtifactProps) => {
29
  const userToggledActions = useRef(false);
30
  const [showActions, setShowActions] = useState(false);
31
+ const [allActionFinished, setAllActionFinished] = useState(false);
32
 
33
  const artifacts = useStore(workbenchStore.artifacts);
34
  const artifact = artifacts[messageId];
 
48
  if (actions.length && !showActions && !userToggledActions.current) {
49
  setShowActions(true);
50
  }
51
+
52
+ if (actions.length !== 0 && artifact.type === 'bundled') {
53
+ const finished = !actions.find((action) => action.status !== 'complete');
54
+
55
+ if (finished != allActionFinished) {
56
+ setAllActionFinished(finished);
57
+ }
58
+ }
59
  }, [actions]);
60
 
61
  return (
 
68
  workbenchStore.showWorkbench.set(!showWorkbench);
69
  }}
70
  >
71
+ {artifact.type == 'bundled' && (
72
+ <>
73
+ <div className="p-4">
74
+ {allActionFinished ? (
75
+ <div className={'i-ph:files-light'} style={{ fontSize: '2rem' }}></div>
76
+ ) : (
77
+ <div className={'i-svg-spinners:90-ring-with-bg'} style={{ fontSize: '2rem' }}></div>
78
+ )}
79
+ </div>
80
+ <div className="bg-bolt-elements-artifacts-borderColor w-[1px]" />
81
+ </>
82
+ )}
83
  <div className="px-5 p-3.5 w-full text-left">
84
  <div className="w-full text-bolt-elements-textPrimary font-medium leading-5 text-sm">{artifact?.title}</div>
85
  <div className="w-full w-full text-bolt-elements-textSecondary text-xs mt-0.5">Click to open Workbench</div>
 
87
  </button>
88
  <div className="bg-bolt-elements-artifacts-borderColor w-[1px]" />
89
  <AnimatePresence>
90
+ {actions.length && artifact.type !== 'bundled' && (
91
  <motion.button
92
  initial={{ width: 0 }}
93
  animate={{ width: 'auto' }}
 
104
  </AnimatePresence>
105
  </div>
106
  <AnimatePresence>
107
+ {artifact.type !== 'bundled' && showActions && actions.length > 0 && (
108
  <motion.div
109
  className="actions"
110
  initial={{ height: 0 }}
 
113
  transition={{ duration: 0.15 }}
114
  >
115
  <div className="bg-bolt-elements-artifacts-borderColor h-[1px]" />
116
+
117
  <div className="p-5 text-left bg-bolt-elements-actions-background">
118
  <ActionList actions={actions} />
119
  </div>
 
152
  visible: { opacity: 1, y: 0 },
153
  };
154
 
155
+ function openArtifactInWorkbench(filePath: any) {
156
+ if (workbenchStore.currentView.get() !== 'code') {
157
+ workbenchStore.currentView.set('code');
158
+ }
159
+
160
+ workbenchStore.setSelectedFile(`${WORK_DIR}/${filePath}`);
161
+ }
162
+
163
  const ActionList = memo(({ actions }: ActionListProps) => {
164
  return (
165
  <motion.div initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }} transition={{ duration: 0.15 }}>
 
200
  {type === 'file' ? (
201
  <div>
202
  Create{' '}
203
+ <code
204
+ 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"
205
+ onClick={() => openArtifactInWorkbench(action.filePath)}
206
+ >
207
  {action.filePath}
208
  </code>
209
  </div>
app/components/chat/BaseChat.module.scss CHANGED
@@ -17,3 +17,107 @@
17
  .Chat {
18
  opacity: 1;
19
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 CHANGED
@@ -1,74 +1,30 @@
1
- // @ts-nocheck
2
- // Preventing TS checks with files presented in the video for a better presentation.
 
 
3
  import type { Message } from 'ai';
4
- import React, { type RefCallback, useEffect } from 'react';
5
  import { ClientOnly } from 'remix-utils/client-only';
6
  import { Menu } from '~/components/sidebar/Menu.client';
7
  import { IconButton } from '~/components/ui/IconButton';
8
  import { Workbench } from '~/components/workbench/Workbench.client';
9
  import { classNames } from '~/utils/classNames';
10
- import { MODEL_LIST, DEFAULT_PROVIDER } from '~/utils/constants';
11
  import { Messages } from './Messages.client';
12
  import { SendButton } from './SendButton.client';
13
- import { useState } from 'react';
14
  import { APIKeyManager } from './APIKeyManager';
15
  import Cookies from 'js-cookie';
 
16
 
17
  import styles from './BaseChat.module.scss';
 
 
 
 
18
 
19
- const EXAMPLE_PROMPTS = [
20
- { text: 'Build a todo app in React using Tailwind' },
21
- { text: 'Build a simple blog using Astro' },
22
- { text: 'Create a cookie consent form using Material UI' },
23
- { text: 'Make a space invaders game' },
24
- { text: 'How do I center a div?' },
25
- ];
26
-
27
- const providerList = [...new Set(MODEL_LIST.map((model) => model.provider))];
28
-
29
- const ModelSelector = ({ model, setModel, provider, setProvider, modelList, providerList }) => {
30
- return (
31
- <div className="mb-2 flex gap-2">
32
- <select
33
- value={provider}
34
- onChange={(e) => {
35
- setProvider(e.target.value);
36
- const firstModel = [...modelList].find((m) => m.provider == e.target.value);
37
- setModel(firstModel ? firstModel.name : '');
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) => (
42
- <option key={provider} value={provider}>
43
- {provider}
44
- </option>
45
- ))}
46
- <option key="Ollama" value="Ollama">
47
- Ollama
48
- </option>
49
- <option key="OpenAILike" value="OpenAILike">
50
- OpenAILike
51
- </option>
52
- <option key="LMStudio" value="LMStudio">
53
- LMStudio
54
- </option>
55
- </select>
56
- <select
57
- value={model}
58
- onChange={(e) => setModel(e.target.value)}
59
- 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"
60
- >
61
- {[...modelList]
62
- .filter((e) => e.provider == provider && e.name)
63
- .map((modelOption) => (
64
- <option key={modelOption.name} value={modelOption.name}>
65
- {modelOption.label}
66
- </option>
67
- ))}
68
- </select>
69
- </div>
70
- );
71
- };
72
 
73
  const TEXTAREA_MIN_HEIGHT = 76;
74
 
@@ -80,17 +36,24 @@ interface BaseChatProps {
80
  chatStarted?: boolean;
81
  isStreaming?: boolean;
82
  messages?: Message[];
 
83
  enhancingPrompt?: boolean;
84
  promptEnhanced?: boolean;
85
  input?: string;
86
  model?: string;
87
  setModel?: (model: string) => void;
88
- provider?: string;
89
- setProvider?: (provider: string) => void;
90
  handleStop?: () => void;
91
  sendMessage?: (event: React.UIEvent, messageInput?: string) => void;
92
  handleInputChange?: (event: React.ChangeEvent<HTMLTextAreaElement>) => void;
93
  enhancePrompt?: () => void;
 
 
 
 
 
 
94
  }
95
 
96
  export const BaseChat = React.forwardRef<HTMLDivElement, BaseChatProps>(
@@ -102,45 +65,129 @@ export const BaseChat = React.forwardRef<HTMLDivElement, BaseChatProps>(
102
  showChat = true,
103
  chatStarted = false,
104
  isStreaming = false,
105
- enhancingPrompt = false,
106
- promptEnhanced = false,
107
- messages,
108
- input = '',
109
  model,
110
  setModel,
111
  provider,
112
  setProvider,
113
- sendMessage,
 
114
  handleInputChange,
 
115
  enhancePrompt,
 
116
  handleStop,
 
 
 
 
 
 
 
117
  },
118
  ref,
119
  ) => {
120
  const TEXTAREA_MAX_HEIGHT = chatStarted ? 400 : 200;
121
  const [apiKeys, setApiKeys] = useState<Record<string, string>>({});
 
 
 
 
 
122
 
 
123
  useEffect(() => {
124
  // Load API keys from cookies on component mount
125
  try {
126
  const storedApiKeys = Cookies.get('apiKeys');
 
127
  if (storedApiKeys) {
128
  const parsedKeys = JSON.parse(storedApiKeys);
 
129
  if (typeof parsedKeys === 'object' && parsedKeys !== null) {
130
  setApiKeys(parsedKeys);
131
  }
132
  }
133
  } catch (error) {
134
  console.error('Error loading API keys from cookies:', error);
 
135
  // Clear invalid cookie data
136
  Cookies.remove('apiKeys');
137
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
138
  }, []);
139
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
140
  const updateApiKey = (provider: string, key: string) => {
141
  try {
142
  const updatedApiKeys = { ...apiKeys, [provider]: key };
143
  setApiKeys(updatedApiKeys);
 
144
  // Save updated API keys to cookies with 30 day expiry and secure settings
145
  Cookies.set('apiKeys', JSON.stringify(updatedApiKeys), {
146
  expires: 30, // 30 days
@@ -153,27 +200,86 @@ export const BaseChat = React.forwardRef<HTMLDivElement, BaseChatProps>(
153
  }
154
  };
155
 
156
- return (
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
157
  <div
158
  ref={ref}
159
  className={classNames(styles.BaseChat, 'relative flex h-full w-full overflow-hidden')}
160
  data-chat-visible={showChat}
161
  >
 
 
 
 
 
 
 
162
  <ClientOnly>{() => <Menu />}</ClientOnly>
163
- <div ref={scrollRef} className="flex overflow-y-auto w-full h-full">
164
- <div className={classNames(styles.Chat, 'flex flex-col flex-grow min-w-[var(--chat-min-width)] h-full')}>
165
  {!chatStarted && (
166
- <div id="intro" className="mt-[26vh] max-w-chat mx-auto text-center">
167
- <h1 className="text-6xl font-bold text-bolt-elements-textPrimary mb-4 animate-fade-in">
168
  Where ideas begin
169
  </h1>
170
- <p className="text-xl mb-8 text-bolt-elements-textSecondary animate-fade-in animation-delay-200">
171
  Bring ideas to life in seconds or get help on existing projects.
172
  </p>
173
  </div>
174
  )}
175
  <div
176
- className={classNames('pt-6 px-6', {
177
  'h-full flex flex-col': chatStarted,
178
  })}
179
  >
@@ -182,7 +288,7 @@ export const BaseChat = React.forwardRef<HTMLDivElement, BaseChatProps>(
182
  return chatStarted ? (
183
  <Messages
184
  ref={messageRef}
185
- className="flex flex-col w-full flex-1 max-w-chat px-4 pb-6 mx-auto z-1"
186
  messages={messages}
187
  isStreaming={isStreaming}
188
  />
@@ -190,31 +296,125 @@ export const BaseChat = React.forwardRef<HTMLDivElement, BaseChatProps>(
190
  }}
191
  </ClientOnly>
192
  <div
193
- className={classNames('relative w-full max-w-chat mx-auto z-prompt', {
194
- 'sticky bottom-0': chatStarted,
195
- })}
 
 
 
196
  >
197
- <ModelSelector
198
- model={model}
199
- setModel={setModel}
200
- modelList={MODEL_LIST}
201
- provider={provider}
202
- setProvider={setProvider}
203
- providerList={providerList}
204
- />
205
- <APIKeyManager
206
- provider={provider}
207
- apiKey={apiKeys[provider] || ''}
208
- setApiKey={(key) => updateApiKey(provider, key)}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
209
  />
210
  <div
211
  className={classNames(
212
- 'shadow-lg border border-bolt-elements-borderColor bg-bolt-elements-prompt-background backdrop-filter backdrop-blur-[8px] rounded-lg overflow-hidden transition-all',
213
  )}
214
  >
215
  <textarea
216
  ref={textareaRef}
217
- className={`w-full pl-4 pt-4 pr-16 focus:outline-none focus:ring-2 focus:ring-bolt-elements-focus resize-none text-md text-bolt-elements-textPrimary placeholder-bolt-elements-textTertiary bg-transparent transition-all`}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
218
  onKeyDown={(event) => {
219
  if (event.key === 'Enter') {
220
  if (event.shiftKey) {
@@ -223,13 +423,19 @@ export const BaseChat = React.forwardRef<HTMLDivElement, BaseChatProps>(
223
 
224
  event.preventDefault();
225
 
226
- sendMessage?.(event);
 
 
 
 
 
227
  }
228
  }}
229
  value={input}
230
  onChange={(event) => {
231
  handleInputChange?.(event);
232
  }}
 
233
  style={{
234
  minHeight: TEXTAREA_MIN_HEIGHT,
235
  maxHeight: TEXTAREA_MAX_HEIGHT,
@@ -240,7 +446,7 @@ export const BaseChat = React.forwardRef<HTMLDivElement, BaseChatProps>(
240
  <ClientOnly>
241
  {() => (
242
  <SendButton
243
- show={input.length > 0 || isStreaming}
244
  isStreaming={isStreaming}
245
  onClick={(event) => {
246
  if (isStreaming) {
@@ -248,21 +454,28 @@ export const BaseChat = React.forwardRef<HTMLDivElement, BaseChatProps>(
248
  return;
249
  }
250
 
251
- sendMessage?.(event);
 
 
252
  }}
253
  />
254
  )}
255
  </ClientOnly>
256
  <div className="flex justify-between items-center text-sm p-4 pt-2">
257
  <div className="flex gap-1 items-center">
 
 
 
258
  <IconButton
259
  title="Enhance prompt"
260
  disabled={input.length === 0 || enhancingPrompt}
261
- className={classNames('transition-all', {
262
- 'opacity-100!': enhancingPrompt,
263
- 'text-bolt-elements-item-contentAccent! pr-1.5 enabled:hover:bg-bolt-elements-item-backgroundAccent!':
264
- promptEnhanced,
265
- })}
 
 
266
  onClick={() => enhancePrompt?.()}
267
  >
268
  {enhancingPrompt ? (
@@ -277,43 +490,42 @@ export const BaseChat = React.forwardRef<HTMLDivElement, BaseChatProps>(
277
  </>
278
  )}
279
  </IconButton>
 
 
 
 
 
 
 
 
280
  </div>
281
  {input.length > 3 ? (
282
  <div className="text-xs text-bolt-elements-textTertiary">
283
  Use <kbd className="kdb px-1.5 py-0.5 rounded bg-bolt-elements-background-depth-2">Shift</kbd> +{' '}
284
- <kbd className="kdb px-1.5 py-0.5 rounded bg-bolt-elements-background-depth-2">Return</kbd> for
285
- a new line
286
  </div>
287
  ) : null}
288
  </div>
289
  </div>
290
- <div className="bg-bolt-elements-background-depth-1 pb-6">{/* Ghost Element */}</div>
291
  </div>
292
  </div>
293
- {!chatStarted && (
294
- <div id="examples" className="relative w-full max-w-xl mx-auto mt-8 flex justify-center">
295
- <div className="flex flex-col space-y-2 [mask-image:linear-gradient(to_bottom,black_0%,transparent_180%)] hover:[mask-image:none]">
296
- {EXAMPLE_PROMPTS.map((examplePrompt, index) => {
297
- return (
298
- <button
299
- key={index}
300
- onClick={(event) => {
301
- sendMessage?.(event, examplePrompt.text);
302
- }}
303
- className="group flex items-center w-full gap-2 justify-center bg-transparent text-bolt-elements-textTertiary hover:text-bolt-elements-textPrimary transition-theme"
304
- >
305
- {examplePrompt.text}
306
- <div className="i-ph:arrow-bend-down-left" />
307
- </button>
308
- );
309
- })}
310
- </div>
311
- </div>
312
- )}
313
  </div>
314
  <ClientOnly>{() => <Workbench chatStarted={chatStarted} isStreaming={isStreaming} />}</ClientOnly>
315
  </div>
316
  </div>
317
  );
 
 
318
  },
319
  );
 
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
 
 
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>(
 
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
 
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(styles.BaseChat, 'relative flex h-full w-full overflow-hidden')}
259
  data-chat-visible={showChat}
260
  >
261
+ <div className={classNames(styles.RayContainer)}>
262
+ <div className={classNames(styles.LightRayOne)}></div>
263
+ <div className={classNames(styles.LightRayTwo)}></div>
264
+ <div className={classNames(styles.LightRayThree)}></div>
265
+ <div className={classNames(styles.LightRayFour)}></div>
266
+ <div className={classNames(styles.LightRayFive)}></div>
267
+ </div>
268
  <ClientOnly>{() => <Menu />}</ClientOnly>
269
+ <div ref={scrollRef} className="flex flex-col lg:flex-row overflow-y-auto w-full h-full">
270
+ <div className={classNames(styles.Chat, 'flex flex-col flex-grow lg:min-w-[var(--chat-min-width)] h-full')}>
271
  {!chatStarted && (
272
+ <div id="intro" className="mt-[26vh] max-w-chat mx-auto text-center px-4 lg:px-0">
273
+ <h1 className="text-3xl lg:text-6xl font-bold text-bolt-elements-textPrimary mb-4 animate-fade-in">
274
  Where ideas begin
275
  </h1>
276
+ <p className="text-md lg:text-xl mb-8 text-bolt-elements-textSecondary animate-fade-in animation-delay-200">
277
  Bring ideas to life in seconds or get help on existing projects.
278
  </p>
279
  </div>
280
  )}
281
  <div
282
+ className={classNames('pt-6 px-2 sm:px-6', {
283
  'h-full flex flex-col': chatStarted,
284
  })}
285
  >
 
288
  return chatStarted ? (
289
  <Messages
290
  ref={messageRef}
291
+ className="flex flex-col w-full flex-1 max-w-chat pb-6 mx-auto z-1"
292
  messages={messages}
293
  isStreaming={isStreaming}
294
  />
 
296
  }}
297
  </ClientOnly>
298
  <div
299
+ className={classNames(
300
+ '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',
301
+ {
302
+ 'sticky bottom-2': chatStarted,
303
+ },
304
+ )}
305
  >
306
+ <svg className={classNames(styles.PromptEffectContainer)}>
307
+ <defs>
308
+ <linearGradient
309
+ id="line-gradient"
310
+ x1="20%"
311
+ y1="0%"
312
+ x2="-14%"
313
+ y2="10%"
314
+ gradientUnits="userSpaceOnUse"
315
+ gradientTransform="rotate(-45)"
316
+ >
317
+ <stop offset="0%" stopColor="#1488fc" stopOpacity="0%"></stop>
318
+ <stop offset="40%" stopColor="#1488fc" stopOpacity="80%"></stop>
319
+ <stop offset="50%" stopColor="#1488fc" stopOpacity="80%"></stop>
320
+ <stop offset="100%" stopColor="#1488fc" stopOpacity="0%"></stop>
321
+ </linearGradient>
322
+ <linearGradient id="shine-gradient">
323
+ <stop offset="0%" stopColor="white" stopOpacity="0%"></stop>
324
+ <stop offset="40%" stopColor="#8adaff" stopOpacity="80%"></stop>
325
+ <stop offset="50%" stopColor="#8adaff" stopOpacity="80%"></stop>
326
+ <stop offset="100%" stopColor="white" stopOpacity="0%"></stop>
327
+ </linearGradient>
328
+ </defs>
329
+ <rect className={classNames(styles.PromptEffectLine)} pathLength="100" strokeLinecap="round"></rect>
330
+ <rect className={classNames(styles.PromptShine)} x="48" y="24" width="70" height="1"></rect>
331
+ </svg>
332
+ <div>
333
+ <div className="flex justify-between items-center mb-2">
334
+ <button
335
+ onClick={() => setIsModelSettingsCollapsed(!isModelSettingsCollapsed)}
336
+ className={classNames('flex items-center gap-2 p-2 rounded-lg transition-all', {
337
+ 'bg-bolt-elements-item-backgroundAccent text-bolt-elements-item-contentAccent':
338
+ isModelSettingsCollapsed,
339
+ 'bg-bolt-elements-item-backgroundDefault text-bolt-elements-item-contentDefault':
340
+ !isModelSettingsCollapsed,
341
+ })}
342
+ >
343
+ <div className={`i-ph:caret-${isModelSettingsCollapsed ? 'right' : 'down'} text-lg`} />
344
+ <span>Model Settings</span>
345
+ </button>
346
+ </div>
347
+
348
+ <div className={isModelSettingsCollapsed ? 'hidden' : ''}>
349
+ <ModelSelector
350
+ key={provider?.name + ':' + modelList.length}
351
+ model={model}
352
+ setModel={setModel}
353
+ modelList={modelList}
354
+ provider={provider}
355
+ setProvider={setProvider}
356
+ providerList={PROVIDER_LIST}
357
+ apiKeys={apiKeys}
358
+ />
359
+ {provider && (
360
+ <APIKeyManager
361
+ provider={provider}
362
+ apiKey={apiKeys[provider.name] || ''}
363
+ setApiKey={(key) => updateApiKey(provider.name, key)}
364
+ />
365
+ )}
366
+ </div>
367
+ </div>
368
+ <FilePreview
369
+ files={uploadedFiles}
370
+ imageDataList={imageDataList}
371
+ onRemove={(index) => {
372
+ setUploadedFiles?.(uploadedFiles.filter((_, i) => i !== index));
373
+ setImageDataList?.(imageDataList.filter((_, i) => i !== index));
374
+ }}
375
  />
376
  <div
377
  className={classNames(
378
+ 'relative shadow-xs border border-bolt-elements-borderColor backdrop-blur rounded-lg',
379
  )}
380
  >
381
  <textarea
382
  ref={textareaRef}
383
+ className={classNames(
384
+ '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',
385
+ 'transition-all duration-200',
386
+ 'hover:border-bolt-elements-focus',
387
+ )}
388
+ onDragEnter={(e) => {
389
+ e.preventDefault();
390
+ e.currentTarget.style.border = '2px solid #1488fc';
391
+ }}
392
+ onDragOver={(e) => {
393
+ e.preventDefault();
394
+ e.currentTarget.style.border = '2px solid #1488fc';
395
+ }}
396
+ onDragLeave={(e) => {
397
+ e.preventDefault();
398
+ e.currentTarget.style.border = '1px solid var(--bolt-elements-borderColor)';
399
+ }}
400
+ onDrop={(e) => {
401
+ e.preventDefault();
402
+ e.currentTarget.style.border = '1px solid var(--bolt-elements-borderColor)';
403
+
404
+ const files = Array.from(e.dataTransfer.files);
405
+ files.forEach((file) => {
406
+ if (file.type.startsWith('image/')) {
407
+ const reader = new FileReader();
408
+
409
+ reader.onload = (e) => {
410
+ const base64Image = e.target?.result as string;
411
+ setUploadedFiles?.([...uploadedFiles, file]);
412
+ setImageDataList?.([...imageDataList, base64Image]);
413
+ };
414
+ reader.readAsDataURL(file);
415
+ }
416
+ });
417
+ }}
418
  onKeyDown={(event) => {
419
  if (event.key === 'Enter') {
420
  if (event.shiftKey) {
 
423
 
424
  event.preventDefault();
425
 
426
+ if (isStreaming) {
427
+ handleStop?.();
428
+ return;
429
+ }
430
+
431
+ handleSendMessage?.(event);
432
  }
433
  }}
434
  value={input}
435
  onChange={(event) => {
436
  handleInputChange?.(event);
437
  }}
438
+ onPaste={handlePaste}
439
  style={{
440
  minHeight: TEXTAREA_MIN_HEIGHT,
441
  maxHeight: TEXTAREA_MAX_HEIGHT,
 
446
  <ClientOnly>
447
  {() => (
448
  <SendButton
449
+ show={input.length > 0 || isStreaming || uploadedFiles.length > 0}
450
  isStreaming={isStreaming}
451
  onClick={(event) => {
452
  if (isStreaming) {
 
454
  return;
455
  }
456
 
457
+ if (input.length > 0 || uploadedFiles.length > 0) {
458
+ handleSendMessage?.(event);
459
+ }
460
  }}
461
  />
462
  )}
463
  </ClientOnly>
464
  <div className="flex justify-between items-center text-sm p-4 pt-2">
465
  <div className="flex gap-1 items-center">
466
+ <IconButton title="Upload file" className="transition-all" onClick={() => handleFileUpload()}>
467
+ <div className="i-ph:paperclip text-xl"></div>
468
+ </IconButton>
469
  <IconButton
470
  title="Enhance prompt"
471
  disabled={input.length === 0 || enhancingPrompt}
472
+ className={classNames(
473
+ 'transition-all',
474
+ enhancingPrompt ? 'opacity-100' : '',
475
+ promptEnhanced ? 'text-bolt-elements-item-contentAccent' : '',
476
+ promptEnhanced ? 'pr-1.5' : '',
477
+ promptEnhanced ? 'enabled:hover:bg-bolt-elements-item-backgroundAccent' : '',
478
+ )}
479
  onClick={() => enhancePrompt?.()}
480
  >
481
  {enhancingPrompt ? (
 
490
  </>
491
  )}
492
  </IconButton>
493
+
494
+ <SpeechRecognitionButton
495
+ isListening={isListening}
496
+ onStart={startListening}
497
+ onStop={stopListening}
498
+ disabled={isStreaming}
499
+ />
500
+ {chatStarted && <ClientOnly>{() => <ExportChatButton exportChat={exportChat} />}</ClientOnly>}
501
  </div>
502
  {input.length > 3 ? (
503
  <div className="text-xs text-bolt-elements-textTertiary">
504
  Use <kbd className="kdb px-1.5 py-0.5 rounded bg-bolt-elements-background-depth-2">Shift</kbd> +{' '}
505
+ <kbd className="kdb px-1.5 py-0.5 rounded bg-bolt-elements-background-depth-2">Return</kbd> a
506
+ new line
507
  </div>
508
  ) : null}
509
  </div>
510
  </div>
 
511
  </div>
512
  </div>
513
+ {!chatStarted && ImportButtons(importChat)}
514
+ {!chatStarted &&
515
+ ExamplePrompts((event, messageInput) => {
516
+ if (isStreaming) {
517
+ handleStop?.();
518
+ return;
519
+ }
520
+
521
+ handleSendMessage?.(event, messageInput);
522
+ })}
 
 
 
 
 
 
 
 
 
 
523
  </div>
524
  <ClientOnly>{() => <Workbench chatStarted={chatStarted} isStreaming={isStreaming} />}</ClientOnly>
525
  </div>
526
  </div>
527
  );
528
+
529
+ return <Tooltip.Provider delayDuration={200}>{baseChat}</Tooltip.Provider>;
530
  },
531
  );
app/components/chat/Chat.client.tsx CHANGED
@@ -1,21 +1,24 @@
1
- // @ts-nocheck
2
- // Preventing TS checks with files presented in the video for a better presentation.
 
 
3
  import { useStore } from '@nanostores/react';
4
  import type { Message } from 'ai';
5
  import { useChat } from 'ai/react';
6
  import { useAnimate } from 'framer-motion';
7
- import { memo, useEffect, useRef, useState } from 'react';
8
  import { cssTransition, toast, ToastContainer } from 'react-toastify';
9
  import { useMessageParser, usePromptEnhancer, useShortcuts, useSnapScroll } from '~/lib/hooks';
10
- import { useChatHistory } from '~/lib/persistence';
11
  import { chatStore } from '~/lib/stores/chat';
12
  import { workbenchStore } from '~/lib/stores/workbench';
13
- import { fileModificationsToHTML } from '~/utils/diff';
14
- import { DEFAULT_MODEL, DEFAULT_PROVIDER } from '~/utils/constants';
15
  import { cubicEasingFn } from '~/utils/easings';
16
  import { createScopedLogger, renderLogger } from '~/utils/logger';
17
  import { BaseChat } from './BaseChat';
18
  import Cookies from 'js-cookie';
 
 
19
 
20
  const toastAnimation = cssTransition({
21
  enter: 'animated fadeInRight',
@@ -27,11 +30,20 @@ const logger = createScopedLogger('Chat');
27
  export function Chat() {
28
  renderLogger.trace('Chat');
29
 
30
- const { ready, initialMessages, storeMessageHistory } = useChatHistory();
 
31
 
32
  return (
33
  <>
34
- {ready && <ChatImpl initialMessages={initialMessages} storeMessageHistory={storeMessageHistory} />}
 
 
 
 
 
 
 
 
35
  <ToastContainer
36
  closeButton={({ closeToast }) => {
37
  return (
@@ -66,213 +78,281 @@ export function Chat() {
66
  interface ChatProps {
67
  initialMessages: Message[];
68
  storeMessageHistory: (messages: Message[]) => Promise<void>;
 
 
 
69
  }
70
 
71
- export const ChatImpl = memo(({ initialMessages, storeMessageHistory }: ChatProps) => {
72
- useShortcuts();
73
-
74
- const textareaRef = useRef<HTMLTextAreaElement>(null);
75
-
76
- const [chatStarted, setChatStarted] = useState(initialMessages.length > 0);
77
- const [model, setModel] = useState(() => {
78
- const savedModel = Cookies.get('selectedModel');
79
- return savedModel || DEFAULT_MODEL;
80
- });
81
- const [provider, setProvider] = useState(() => {
82
- const savedProvider = Cookies.get('selectedProvider');
83
- return savedProvider || DEFAULT_PROVIDER;
84
- });
85
-
86
- const { showChat } = useStore(chatStore);
87
-
88
- const [animationScope, animate] = useAnimate();
89
-
90
- const [apiKeys, setApiKeys] = useState<Record<string, string>>({});
91
-
92
- const { messages, isLoading, input, handleInputChange, setInput, stop, append } = useChat({
93
- api: '/api/chat',
94
- body: {
95
- apiKeys,
96
- },
97
- onError: (error) => {
98
- logger.error('Request failed\n\n', error);
99
- toast.error('There was an error processing your request');
100
- },
101
- onFinish: () => {
102
- logger.debug('Finished streaming');
103
- },
104
- initialMessages,
105
- });
106
-
107
- const { enhancingPrompt, promptEnhanced, enhancePrompt, resetEnhancer } = usePromptEnhancer();
108
- const { parsedMessages, parseMessages } = useMessageParser();
109
-
110
- const TEXTAREA_MAX_HEIGHT = chatStarted ? 400 : 200;
111
-
112
- useEffect(() => {
113
- chatStore.setKey('started', initialMessages.length > 0);
114
- }, []);
115
-
116
- useEffect(() => {
117
- parseMessages(messages, isLoading);
118
-
119
- if (messages.length > initialMessages.length) {
120
- storeMessageHistory(messages).catch((error) => toast.error(error.message));
121
- }
122
- }, [messages, isLoading, parseMessages]);
123
 
124
- const scrollTextArea = () => {
125
- const textarea = textareaRef.current;
126
 
127
- if (textarea) {
128
- textarea.scrollTop = textarea.scrollHeight;
129
- }
130
- };
131
 
132
- const abort = () => {
133
- stop();
134
- chatStore.setKey('aborted', true);
135
- workbenchStore.abortAllActions();
136
- };
137
 
138
- useEffect(() => {
139
- const textarea = textareaRef.current;
140
 
141
- if (textarea) {
142
- textarea.style.height = 'auto';
 
 
143
 
144
- const scrollHeight = textarea.scrollHeight;
 
145
 
146
- textarea.style.height = `${Math.min(scrollHeight, TEXTAREA_MAX_HEIGHT)}px`;
147
- textarea.style.overflowY = scrollHeight > TEXTAREA_MAX_HEIGHT ? 'auto' : 'hidden';
148
- }
149
- }, [input, textareaRef]);
150
 
151
- const runAnimation = async () => {
152
- if (chatStarted) {
153
- return;
154
- }
 
155
 
156
- await Promise.all([
157
- animate('#examples', { opacity: 0, display: 'none' }, { duration: 0.1 }),
158
- animate('#intro', { opacity: 0, flex: 1 }, { duration: 0.2, ease: cubicEasingFn }),
159
- ]);
160
 
161
- chatStore.setKey('started', true);
 
162
 
163
- setChatStarted(true);
164
- };
165
 
166
- const sendMessage = async (_event: React.UIEvent, messageInput?: string) => {
167
- const _input = messageInput || input;
 
 
168
 
169
- if (_input.length === 0 || isLoading) {
170
- return;
171
- }
 
172
 
173
- /**
174
- * @note (delm) Usually saving files shouldn't take long but it may take longer if there
175
- * many unsaved files. In that case we need to block user input and show an indicator
176
- * of some kind so the user is aware that something is happening. But I consider the
177
- * happy case to be no unsaved files and I would expect users to save their changes
178
- * before they send another message.
179
- */
180
- await workbenchStore.saveAllFiles();
181
 
182
- const fileModifications = workbenchStore.getFileModifcations();
183
 
184
- chatStore.setKey('aborted', false);
 
185
 
186
- runAnimation();
 
187
 
188
- if (fileModifications !== undefined) {
189
- const diff = fileModificationsToHTML(fileModifications);
 
190
 
191
  /**
192
- * If we have file modifications we append a new user message manually since we have to prefix
193
- * the user input with the file modifications and we don't want the new user input to appear
194
- * in the prompt. Using `append` is almost the same as `handleSubmit` except that we have to
195
- * manually reset the input and we'd have to manually pass in file attachments. However, those
196
- * aren't relevant here.
197
  */
198
- append({ role: 'user', content: `[Model: ${model}]\n\n[Provider: ${provider}]\n\n${diff}\n\n${_input}` });
199
-
200
- /**
201
- * After sending a new message we reset all modifications since the model
202
- * should now be aware of all the changes.
203
- */
204
- workbenchStore.resetAllFileModifications();
205
- } else {
206
- append({ role: 'user', content: `[Model: ${model}]\n\n[Provider: ${provider}]\n\n${_input}` });
207
- }
208
-
209
- setInput('');
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
210
 
211
- resetEnhancer();
212
-
213
- textareaRef.current?.blur();
214
- };
215
-
216
- const [messageRef, scrollRef] = useSnapScroll();
217
-
218
- useEffect(() => {
219
- const storedApiKeys = Cookies.get('apiKeys');
220
- if (storedApiKeys) {
221
- setApiKeys(JSON.parse(storedApiKeys));
222
- }
223
- }, []);
224
-
225
- const handleModelChange = (newModel: string) => {
226
- setModel(newModel);
227
- Cookies.set('selectedModel', newModel, { expires: 30 });
228
- };
229
 
230
- const handleProviderChange = (newProvider: string) => {
231
- setProvider(newProvider);
232
- Cookies.set('selectedProvider', newProvider, { expires: 30 });
233
- };
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
234
 
235
- return (
236
- <BaseChat
237
- ref={animationScope}
238
- textareaRef={textareaRef}
239
- input={input}
240
- showChat={showChat}
241
- chatStarted={chatStarted}
242
- isStreaming={isLoading}
243
- enhancingPrompt={enhancingPrompt}
244
- promptEnhanced={promptEnhanced}
245
- sendMessage={sendMessage}
246
- model={model}
247
- setModel={handleModelChange}
248
- provider={provider}
249
- setProvider={handleProviderChange}
250
- messageRef={messageRef}
251
- scrollRef={scrollRef}
252
- handleInputChange={handleInputChange}
253
- handleStop={abort}
254
- messages={messages.map((message, i) => {
255
- if (message.role === 'user') {
256
- return message;
257
- }
258
-
259
- return {
260
- ...message,
261
- content: parsedMessages[i] || '',
262
- };
263
- })}
264
- enhancePrompt={() => {
265
- enhancePrompt(
266
- input,
267
- (input) => {
268
- setInput(input);
269
- scrollTextArea();
270
- },
271
- model,
272
- provider,
273
- apiKeys,
274
- );
275
- }}
276
- />
277
- );
278
- });
 
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',
 
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 (
 
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/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" type="bundled">
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.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 CHANGED
@@ -68,7 +68,51 @@ export const Markdown = memo(({ children, html = false, limitedMarkdown = false
68
  remarkPlugins={remarkPlugins(limitedMarkdown)}
69
  rehypePlugins={rehypePlugins(html)}
70
  >
71
- {children}
72
  </ReactMarkdown>
73
  );
74
  });
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 CHANGED
@@ -3,6 +3,11 @@ import React from 'react';
3
  import { classNames } from '~/utils/classNames';
4
  import { AssistantMessage } from './AssistantMessage';
5
  import { UserMessage } from './UserMessage';
 
 
 
 
 
6
 
7
  interface MessagesProps {
8
  id?: string;
@@ -13,12 +18,33 @@ interface MessagesProps {
13
 
14
  export const Messages = React.forwardRef<HTMLDivElement, MessagesProps>((props: MessagesProps, ref) => {
15
  const { id, isStreaming = false, messages = [] } = props;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16
 
17
  return (
18
  <div id={id} ref={ref} className={props.className}>
19
  {messages.length > 0
20
  ? messages.map((message, index) => {
21
- const { role, content } = message;
22
  const isUserMessage = role === 'user';
23
  const isFirst = index === 0;
24
  const isLast = index === messages.length - 1;
@@ -41,6 +67,33 @@ export const Messages = React.forwardRef<HTMLDivElement, MessagesProps>((props:
41
  <div className="grid grid-col-1 w-full">
42
  {isUserMessage ? <UserMessage content={content} /> : <AssistantMessage content={content} />}
43
  </div>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
44
  </div>
45
  );
46
  })
 
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;
 
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;
 
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
  })
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 CHANGED
@@ -4,11 +4,12 @@ interface SendButtonProps {
4
  show: boolean;
5
  isStreaming?: boolean;
6
  onClick?: (event: React.MouseEvent<HTMLButtonElement, MouseEvent>) => void;
 
7
  }
8
 
9
  const customEasingFn = cubicBezier(0.4, 0, 0.2, 1);
10
 
11
- export function SendButton({ show, isStreaming, onClick }: SendButtonProps) {
12
  return (
13
  <AnimatePresence>
14
  {show ? (
@@ -30,4 +31,4 @@ export function SendButton({ show, isStreaming, onClick }: SendButtonProps) {
30
  ) : null}
31
  </AnimatePresence>
32
  );
33
- }
 
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 ? (
 
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 CHANGED
@@ -1,21 +1,53 @@
1
- // @ts-nocheck
2
- // Preventing TS checks with files presented in the video for a better presentation.
3
- import { modificationsRegex } from '~/utils/diff';
 
4
  import { MODEL_REGEX, PROVIDER_REGEX } from '~/utils/constants';
5
  import { Markdown } from './Markdown';
6
 
7
  interface UserMessageProps {
8
- content: string;
9
  }
10
 
11
  export function UserMessage({ content }: UserMessageProps) {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
12
  return (
13
  <div className="overflow-hidden pt-[4px]">
14
- <Markdown limitedMarkdown>{sanitizeUserMessage(content)}</Markdown>
15
  </div>
16
  );
17
  }
18
 
19
  function sanitizeUserMessage(content: string) {
20
- return content.replace(modificationsRegex, '').replace(MODEL_REGEX, 'Using: $1').replace(PROVIDER_REGEX, ' ($1)\n\n').trim();
21
  }
 
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/header/Header.tsx CHANGED
@@ -21,17 +21,19 @@ export function Header() {
21
  <span className="i-bolt:logo-text?mask w-[46px] inline-block" />
22
  </a>
23
  </div>
24
- <span className="flex-1 px-4 truncate text-center text-bolt-elements-textPrimary">
25
- <ClientOnly>{() => <ChatDescription />}</ClientOnly>
26
- </span>
27
- {chat.started && (
28
- <ClientOnly>
29
- {() => (
30
- <div className="mr-1">
31
- <HeaderActionButtons />
32
- </div>
33
- )}
34
- </ClientOnly>
 
 
35
  )}
36
  </header>
37
  );
 
21
  <span className="i-bolt:logo-text?mask w-[46px] inline-block" />
22
  </a>
23
  </div>
24
+ {chat.started && ( // Display ChatDescription and HeaderActionButtons only when the chat has started.
25
+ <>
26
+ <span className="flex-1 px-4 truncate text-center text-bolt-elements-textPrimary">
27
+ <ClientOnly>{() => <ChatDescription />}</ClientOnly>
28
+ </span>
29
+ <ClientOnly>
30
+ {() => (
31
+ <div className="mr-1">
32
+ <HeaderActionButtons />
33
+ </div>
34
+ )}
35
+ </ClientOnly>
36
+ </>
37
  )}
38
  </header>
39
  );
app/components/header/HeaderActionButtons.client.tsx CHANGED
@@ -1,4 +1,5 @@
1
  import { useStore } from '@nanostores/react';
 
2
  import { chatStore } from '~/lib/stores/chat';
3
  import { workbenchStore } from '~/lib/stores/workbench';
4
  import { classNames } from '~/utils/classNames';
@@ -9,6 +10,8 @@ export function HeaderActionButtons({}: HeaderActionButtonsProps) {
9
  const showWorkbench = useStore(workbenchStore.showWorkbench);
10
  const { showChat } = useStore(chatStore);
11
 
 
 
12
  const canHideChat = showWorkbench || !showChat;
13
 
14
  return (
@@ -16,7 +19,7 @@ export function HeaderActionButtons({}: HeaderActionButtonsProps) {
16
  <div className="flex border border-bolt-elements-borderColor rounded-md overflow-hidden">
17
  <Button
18
  active={showChat}
19
- disabled={!canHideChat}
20
  onClick={() => {
21
  if (canHideChat) {
22
  chatStore.setKey('showChat', !showChat);
 
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';
 
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 (
 
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);
app/components/sidebar/HistoryItem.tsx CHANGED
@@ -1,64 +1,127 @@
 
 
1
  import * as Dialog from '@radix-ui/react-dialog';
2
- import { useEffect, useRef, useState } from 'react';
3
  import { type ChatHistoryItem } from '~/lib/persistence';
 
 
4
 
5
  interface HistoryItemProps {
6
  item: ChatHistoryItem;
7
  onDelete?: (event: React.UIEvent) => void;
 
 
8
  }
9
 
10
- export function HistoryItem({ item, onDelete }: HistoryItemProps) {
11
- const [hovering, setHovering] = useState(false);
12
- const hoverRef = useRef<HTMLDivElement>(null);
13
 
14
- useEffect(() => {
15
- let timeout: NodeJS.Timeout | undefined;
 
 
 
 
16
 
17
- function mouseEnter() {
18
- setHovering(true);
19
-
20
- if (timeout) {
21
- clearTimeout(timeout);
22
- }
23
- }
24
-
25
- function mouseLeave() {
26
- setHovering(false);
27
- }
28
-
29
- hoverRef.current?.addEventListener('mouseenter', mouseEnter);
30
- hoverRef.current?.addEventListener('mouseleave', mouseLeave);
31
-
32
- return () => {
33
- hoverRef.current?.removeEventListener('mouseenter', mouseEnter);
34
- hoverRef.current?.removeEventListener('mouseleave', mouseLeave);
35
- };
36
- }, []);
37
 
38
  return (
39
  <div
40
- ref={hoverRef}
41
- className="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"
 
 
42
  >
43
- <a href={`/chat/${item.urlId}`} className="flex w-full relative truncate block">
44
- {item.description}
45
- <div className="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 to-transparent w-10 flex justify-end group-hover:w-15 group-hover:from-45%">
46
- {hovering && (
47
- <div className="flex items-center p-1 text-bolt-elements-textSecondary hover:text-bolt-elements-item-contentDanger">
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
48
  <Dialog.Trigger asChild>
49
- <button
50
- className="i-ph:trash scale-110"
 
 
51
  onClick={(event) => {
52
- // we prevent the default so we don't trigger the anchor above
53
  event.preventDefault();
54
  onDelete?.(event);
55
  }}
56
  />
57
  </Dialog.Trigger>
58
  </div>
59
- )}
60
- </div>
61
- </a>
62
  </div>
63
  );
64
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 CHANGED
@@ -2,13 +2,13 @@ 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 { IconButton } from '~/components/ui/IconButton';
6
  import { ThemeSwitch } from '~/components/ui/ThemeSwitch';
7
- import { db, deleteById, getAll, chatId, type ChatHistoryItem } from '~/lib/persistence';
8
  import { cubicEasingFn } from '~/utils/easings';
9
  import { logger } from '~/utils/logger';
10
  import { HistoryItem } from './HistoryItem';
11
  import { binDates } from './date-binning';
 
12
 
13
  const menuVariants = {
14
  closed: {
@@ -33,12 +33,18 @@ const menuVariants = {
33
 
34
  type DialogContent = { type: 'delete'; item: ChatHistoryItem } | null;
35
 
36
- export function Menu() {
 
37
  const menuRef = useRef<HTMLDivElement>(null);
38
  const [list, setList] = useState<ChatHistoryItem[]>([]);
39
  const [open, setOpen] = useState(false);
40
  const [dialogContent, setDialogContent] = useState<DialogContent>(null);
41
 
 
 
 
 
 
42
  const loadEntries = useCallback(() => {
43
  if (db) {
44
  getAll(db)
@@ -99,17 +105,27 @@ export function Menu() {
99
  };
100
  }, []);
101
 
 
 
 
 
 
 
 
 
 
 
102
  return (
103
  <motion.div
104
  ref={menuRef}
105
  initial="closed"
106
  animate={open ? 'open' : 'closed'}
107
  variants={menuVariants}
108
- className="flex 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"
109
  >
110
  <div className="flex items-center h-[var(--header-height)]">{/* Placeholder */}</div>
111
  <div className="flex-1 flex flex-col h-full w-full overflow-hidden">
112
- <div className="p-4">
113
  <a
114
  href="/"
115
  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"
@@ -118,17 +134,38 @@ export function Menu() {
118
  Start new chat
119
  </a>
120
  </div>
 
 
 
 
 
 
 
 
 
 
 
121
  <div className="text-bolt-elements-textPrimary font-medium pl-6 pr-5 my-2">Your Chats</div>
122
- <div className="flex-1 overflow-scroll pl-4 pr-5 pb-5">
123
- {list.length === 0 && <div className="pl-2 text-bolt-elements-textTertiary">No previous conversations</div>}
 
 
 
 
124
  <DialogRoot open={dialogContent !== null}>
125
- {binDates(list).map(({ category, items }) => (
126
  <div key={category} className="mt-4 first:mt-0 space-y-1">
127
  <div className="text-bolt-elements-textTertiary sticky top-0 z-1 bg-bolt-elements-background-depth-2 pl-2 pt-2 pb-1">
128
  {category}
129
  </div>
130
  {items.map((item) => (
131
- <HistoryItem key={item.id} item={item} onDelete={() => setDialogContent({ type: 'delete', item })} />
 
 
 
 
 
 
132
  ))}
133
  </div>
134
  ))}
@@ -169,4 +206,4 @@ export function Menu() {
169
  </div>
170
  </motion.div>
171
  );
172
- }
 
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: {
 
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)
 
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"
 
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
  ))}
 
206
  </div>
207
  </motion.div>
208
  );
209
+ };
app/components/ui/Tooltip.tsx ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import * as Tooltip from '@radix-ui/react-tooltip';
2
+
3
+ interface TooltipProps {
4
+ tooltip: React.ReactNode;
5
+ children: React.ReactNode;
6
+ sideOffset?: number;
7
+ className?: string;
8
+ arrowClassName?: string;
9
+ tooltipStyle?: React.CSSProperties;
10
+ position?: 'top' | 'bottom' | 'left' | 'right';
11
+ maxWidth?: number;
12
+ delay?: number;
13
+ }
14
+
15
+ const WithTooltip = ({
16
+ tooltip,
17
+ children,
18
+ sideOffset = 5,
19
+ className = '',
20
+ arrowClassName = '',
21
+ tooltipStyle = {},
22
+ position = 'top',
23
+ maxWidth = 250,
24
+ delay = 0,
25
+ }: TooltipProps) => {
26
+ return (
27
+ <Tooltip.Root delayDuration={delay}>
28
+ <Tooltip.Trigger asChild>{children}</Tooltip.Trigger>
29
+ <Tooltip.Portal>
30
+ <Tooltip.Content
31
+ side={position}
32
+ className={`
33
+ z-[2000]
34
+ px-2.5
35
+ py-1.5
36
+ max-h-[300px]
37
+ select-none
38
+ rounded-md
39
+ bg-bolt-elements-background-depth-3
40
+ text-bolt-elements-textPrimary
41
+ text-sm
42
+ leading-tight
43
+ shadow-lg
44
+ animate-in
45
+ fade-in-0
46
+ zoom-in-95
47
+ data-[state=closed]:animate-out
48
+ data-[state=closed]:fade-out-0
49
+ data-[state=closed]:zoom-out-95
50
+ ${className}
51
+ `}
52
+ sideOffset={sideOffset}
53
+ style={{
54
+ maxWidth,
55
+ ...tooltipStyle,
56
+ }}
57
+ >
58
+ <div className="break-words">{tooltip}</div>
59
+ <Tooltip.Arrow
60
+ className={`
61
+ fill-bolt-elements-background-depth-3
62
+ ${arrowClassName}
63
+ `}
64
+ width={12}
65
+ height={6}
66
+ />
67
+ </Tooltip.Content>
68
+ </Tooltip.Portal>
69
+ </Tooltip.Root>
70
+ );
71
+ };
72
+
73
+ export default WithTooltip;
app/components/workbench/EditorPanel.tsx CHANGED
@@ -1,6 +1,6 @@
1
  import { useStore } from '@nanostores/react';
2
- import { memo, useEffect, useMemo, useRef, useState } from 'react';
3
- import { Panel, PanelGroup, PanelResizeHandle, type ImperativePanelHandle } from 'react-resizable-panels';
4
  import {
5
  CodeMirrorEditor,
6
  type EditorDocument,
@@ -9,20 +9,17 @@ import {
9
  type OnSaveCallback as OnEditorSave,
10
  type OnScrollCallback as OnEditorScroll,
11
  } from '~/components/editor/codemirror/CodeMirrorEditor';
12
- import { IconButton } from '~/components/ui/IconButton';
13
  import { PanelHeader } from '~/components/ui/PanelHeader';
14
  import { PanelHeaderButton } from '~/components/ui/PanelHeaderButton';
15
- import { shortcutEventEmitter } from '~/lib/hooks';
16
  import type { FileMap } from '~/lib/stores/files';
17
  import { themeStore } from '~/lib/stores/theme';
18
- import { workbenchStore } from '~/lib/stores/workbench';
19
- import { classNames } from '~/utils/classNames';
20
  import { WORK_DIR } from '~/utils/constants';
21
- import { logger, renderLogger } from '~/utils/logger';
22
  import { isMobile } from '~/utils/mobile';
23
  import { FileBreadcrumb } from './FileBreadcrumb';
24
  import { FileTree } from './FileTree';
25
- import { Terminal, type TerminalRef } from './terminal/Terminal';
 
26
 
27
  interface EditorPanelProps {
28
  files?: FileMap;
@@ -37,8 +34,6 @@ interface EditorPanelProps {
37
  onFileReset?: () => void;
38
  }
39
 
40
- const MAX_TERMINALS = 3;
41
- const DEFAULT_TERMINAL_SIZE = 25;
42
  const DEFAULT_EDITOR_SIZE = 100 - DEFAULT_TERMINAL_SIZE;
43
 
44
  const editorSettings: EditorSettings = { tabSize: 2 };
@@ -61,13 +56,6 @@ export const EditorPanel = memo(
61
  const theme = useStore(themeStore);
62
  const showTerminal = useStore(workbenchStore.showTerminal);
63
 
64
- const terminalRefs = useRef<Array<TerminalRef | null>>([]);
65
- const terminalPanelRef = useRef<ImperativePanelHandle>(null);
66
- const terminalToggledByShortcut = useRef(false);
67
-
68
- const [activeTerminal, setActiveTerminal] = useState(0);
69
- const [terminalCount, setTerminalCount] = useState(1);
70
-
71
  const activeFileSegments = useMemo(() => {
72
  if (!editorDocument) {
73
  return undefined;
@@ -80,48 +68,6 @@ export const EditorPanel = memo(
80
  return editorDocument !== undefined && unsavedFiles?.has(editorDocument.filePath);
81
  }, [editorDocument, unsavedFiles]);
82
 
83
- useEffect(() => {
84
- const unsubscribeFromEventEmitter = shortcutEventEmitter.on('toggleTerminal', () => {
85
- terminalToggledByShortcut.current = true;
86
- });
87
-
88
- const unsubscribeFromThemeStore = themeStore.subscribe(() => {
89
- for (const ref of Object.values(terminalRefs.current)) {
90
- ref?.reloadStyles();
91
- }
92
- });
93
-
94
- return () => {
95
- unsubscribeFromEventEmitter();
96
- unsubscribeFromThemeStore();
97
- };
98
- }, []);
99
-
100
- useEffect(() => {
101
- const { current: terminal } = terminalPanelRef;
102
-
103
- if (!terminal) {
104
- return;
105
- }
106
-
107
- const isCollapsed = terminal.isCollapsed();
108
-
109
- if (!showTerminal && !isCollapsed) {
110
- terminal.collapse();
111
- } else if (showTerminal && isCollapsed) {
112
- terminal.resize(DEFAULT_TERMINAL_SIZE);
113
- }
114
-
115
- terminalToggledByShortcut.current = false;
116
- }, [showTerminal]);
117
-
118
- const addTerminal = () => {
119
- if (terminalCount < MAX_TERMINALS) {
120
- setTerminalCount(terminalCount + 1);
121
- setActiveTerminal(terminalCount);
122
- }
123
- };
124
-
125
  return (
126
  <PanelGroup direction="vertical">
127
  <Panel defaultSize={showTerminal ? DEFAULT_EDITOR_SIZE : 100} minSize={20}>
@@ -180,116 +126,7 @@ export const EditorPanel = memo(
180
  </PanelGroup>
181
  </Panel>
182
  <PanelResizeHandle />
183
- <Panel
184
- ref={terminalPanelRef}
185
- defaultSize={showTerminal ? DEFAULT_TERMINAL_SIZE : 0}
186
- minSize={10}
187
- collapsible
188
- onExpand={() => {
189
- if (!terminalToggledByShortcut.current) {
190
- workbenchStore.toggleTerminal(true);
191
- }
192
- }}
193
- onCollapse={() => {
194
- if (!terminalToggledByShortcut.current) {
195
- workbenchStore.toggleTerminal(false);
196
- }
197
- }}
198
- >
199
- <div className="h-full">
200
- <div className="bg-bolt-elements-terminals-background h-full flex flex-col">
201
- <div className="flex items-center bg-bolt-elements-background-depth-2 border-y border-bolt-elements-borderColor gap-1.5 min-h-[34px] p-2">
202
- {Array.from({ length: terminalCount + 1 }, (_, index) => {
203
- const isActive = activeTerminal === index;
204
-
205
- return (
206
- <>
207
- {index == 0 ? (
208
- <button
209
- key={index}
210
- className={classNames(
211
- 'flex items-center text-sm cursor-pointer gap-1.5 px-3 py-2 h-full whitespace-nowrap rounded-full',
212
- {
213
- 'bg-bolt-elements-terminals-buttonBackground text-bolt-elements-textSecondary hover:text-bolt-elements-textPrimary':
214
- isActive,
215
- 'bg-bolt-elements-background-depth-2 text-bolt-elements-textSecondary hover:bg-bolt-elements-terminals-buttonBackground':
216
- !isActive,
217
- },
218
- )}
219
- onClick={() => setActiveTerminal(index)}
220
- >
221
- <div className="i-ph:terminal-window-duotone text-lg" />
222
- Bolt Terminal
223
- </button>
224
- ) : (
225
- <>
226
- <button
227
- key={index}
228
- className={classNames(
229
- 'flex items-center text-sm cursor-pointer gap-1.5 px-3 py-2 h-full whitespace-nowrap rounded-full',
230
- {
231
- 'bg-bolt-elements-terminals-buttonBackground text-bolt-elements-textPrimary': isActive,
232
- 'bg-bolt-elements-background-depth-2 text-bolt-elements-textSecondary hover:bg-bolt-elements-terminals-buttonBackground':
233
- !isActive,
234
- },
235
- )}
236
- onClick={() => setActiveTerminal(index)}
237
- >
238
- <div className="i-ph:terminal-window-duotone text-lg" />
239
- Terminal {terminalCount > 1 && index}
240
- </button>
241
- </>
242
- )}
243
- </>
244
- );
245
- })}
246
- {terminalCount < MAX_TERMINALS && <IconButton icon="i-ph:plus" size="md" onClick={addTerminal} />}
247
- <IconButton
248
- className="ml-auto"
249
- icon="i-ph:caret-down"
250
- title="Close"
251
- size="md"
252
- onClick={() => workbenchStore.toggleTerminal(false)}
253
- />
254
- </div>
255
- {Array.from({ length: terminalCount + 1 }, (_, index) => {
256
- const isActive = activeTerminal === index;
257
- if (index == 0) {
258
- logger.info('Starting bolt terminal');
259
-
260
- return (
261
- <Terminal
262
- key={index}
263
- className={classNames('h-full overflow-hidden', {
264
- hidden: !isActive,
265
- })}
266
- ref={(ref) => {
267
- terminalRefs.current.push(ref);
268
- }}
269
- onTerminalReady={(terminal) => workbenchStore.attachBoltTerminal(terminal)}
270
- onTerminalResize={(cols, rows) => workbenchStore.onTerminalResize(cols, rows)}
271
- theme={theme}
272
- />
273
- );
274
- }
275
- return (
276
- <Terminal
277
- key={index}
278
- className={classNames('h-full overflow-hidden', {
279
- hidden: !isActive,
280
- })}
281
- ref={(ref) => {
282
- terminalRefs.current.push(ref);
283
- }}
284
- onTerminalReady={(terminal) => workbenchStore.attachTerminal(terminal)}
285
- onTerminalResize={(cols, rows) => workbenchStore.onTerminalResize(cols, rows)}
286
- theme={theme}
287
- />
288
- );
289
- })}
290
- </div>
291
- </div>
292
- </Panel>
293
  </PanelGroup>
294
  );
295
  },
 
1
  import { useStore } from '@nanostores/react';
2
+ import { memo, useMemo } from 'react';
3
+ import { Panel, PanelGroup, PanelResizeHandle } from 'react-resizable-panels';
4
  import {
5
  CodeMirrorEditor,
6
  type EditorDocument,
 
9
  type OnSaveCallback as OnEditorSave,
10
  type OnScrollCallback as OnEditorScroll,
11
  } from '~/components/editor/codemirror/CodeMirrorEditor';
 
12
  import { PanelHeader } from '~/components/ui/PanelHeader';
13
  import { PanelHeaderButton } from '~/components/ui/PanelHeaderButton';
 
14
  import type { FileMap } from '~/lib/stores/files';
15
  import { themeStore } from '~/lib/stores/theme';
 
 
16
  import { WORK_DIR } from '~/utils/constants';
17
+ import { renderLogger } from '~/utils/logger';
18
  import { isMobile } from '~/utils/mobile';
19
  import { FileBreadcrumb } from './FileBreadcrumb';
20
  import { FileTree } from './FileTree';
21
+ import { DEFAULT_TERMINAL_SIZE, TerminalTabs } from './terminal/TerminalTabs';
22
+ import { workbenchStore } from '~/lib/stores/workbench';
23
 
24
  interface EditorPanelProps {
25
  files?: FileMap;
 
34
  onFileReset?: () => void;
35
  }
36
 
 
 
37
  const DEFAULT_EDITOR_SIZE = 100 - DEFAULT_TERMINAL_SIZE;
38
 
39
  const editorSettings: EditorSettings = { tabSize: 2 };
 
56
  const theme = useStore(themeStore);
57
  const showTerminal = useStore(workbenchStore.showTerminal);
58
 
 
 
 
 
 
 
 
59
  const activeFileSegments = useMemo(() => {
60
  if (!editorDocument) {
61
  return undefined;
 
68
  return editorDocument !== undefined && unsavedFiles?.has(editorDocument.filePath);
69
  }, [editorDocument, unsavedFiles]);
70
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
71
  return (
72
  <PanelGroup direction="vertical">
73
  <Panel defaultSize={showTerminal ? DEFAULT_EDITOR_SIZE : 100} minSize={20}>
 
126
  </PanelGroup>
127
  </Panel>
128
  <PanelResizeHandle />
129
+ <TerminalTabs />
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
130
  </PanelGroup>
131
  );
132
  },
app/components/workbench/FileTree.tsx CHANGED
@@ -111,7 +111,7 @@ export const FileTree = memo(
111
  };
112
 
113
  return (
114
- <div className={classNames('text-sm', className)}>
115
  {filteredFileList.map((fileOrFolder) => {
116
  switch (fileOrFolder.kind) {
117
  case 'file': {
 
111
  };
112
 
113
  return (
114
+ <div className={classNames('text-sm', className, 'overflow-y-auto')}>
115
  {filteredFileList.map((fileOrFolder) => {
116
  switch (fileOrFolder.kind) {
117
  case 'file': {
app/components/workbench/Preview.tsx CHANGED
@@ -4,11 +4,16 @@ import { IconButton } from '~/components/ui/IconButton';
4
  import { workbenchStore } from '~/lib/stores/workbench';
5
  import { PortDropdown } from './PortDropdown';
6
 
 
 
7
  export const Preview = memo(() => {
8
  const iframeRef = useRef<HTMLIFrameElement>(null);
 
9
  const inputRef = useRef<HTMLInputElement>(null);
 
10
  const [activePreviewIndex, setActivePreviewIndex] = useState(0);
11
  const [isPortDropdownOpen, setIsPortDropdownOpen] = useState(false);
 
12
  const hasSelectedPreview = useRef(false);
13
  const previews = useStore(workbenchStore.previews);
14
  const activePreview = previews[activePreviewIndex];
@@ -16,6 +21,23 @@ export const Preview = memo(() => {
16
  const [url, setUrl] = useState('');
17
  const [iframeUrl, setIframeUrl] = useState<string | undefined>();
18
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19
  useEffect(() => {
20
  if (!activePreview) {
21
  setUrl('');
@@ -25,10 +47,9 @@ export const Preview = memo(() => {
25
  }
26
 
27
  const { baseUrl } = activePreview;
28
-
29
  setUrl(baseUrl);
30
  setIframeUrl(baseUrl);
31
- }, [activePreview, iframeUrl]);
32
 
33
  const validateUrl = useCallback(
34
  (value: string) => {
@@ -56,14 +77,13 @@ export const Preview = memo(() => {
56
  [],
57
  );
58
 
59
- // when previews change, display the lowest port if user hasn't selected a preview
60
  useEffect(() => {
61
  if (previews.length > 1 && !hasSelectedPreview.current) {
62
  const minPortIndex = previews.reduce(findMinPortIndex, 0);
63
-
64
  setActivePreviewIndex(minPortIndex);
65
  }
66
- }, [previews]);
67
 
68
  const reloadPreview = () => {
69
  if (iframeRef.current) {
@@ -71,13 +91,134 @@ export const Preview = memo(() => {
71
  }
72
  };
73
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
74
  return (
75
- <div className="w-full h-full flex flex-col">
76
  {isPortDropdownOpen && (
77
  <div className="z-iframe-overlay w-full h-full absolute" onClick={() => setIsPortDropdownOpen(false)} />
78
  )}
79
  <div className="bg-bolt-elements-background-depth-2 p-2 flex items-center gap-1.5">
80
  <IconButton icon="i-ph:arrow-clockwise" onClick={reloadPreview} />
 
81
  <div
82
  className="flex items-center gap-1 flex-grow bg-bolt-elements-preview-addressBar-background border border-bolt-elements-borderColor text-bolt-elements-preview-addressBar-text rounded-full px-3 py-1 text-sm hover:bg-bolt-elements-preview-addressBar-backgroundHover hover:focus-within:bg-bolt-elements-preview-addressBar-backgroundActive focus-within:bg-bolt-elements-preview-addressBar-backgroundActive
83
  focus-within-border-bolt-elements-borderColorActive focus-within:text-bolt-elements-preview-addressBar-textActive"
@@ -101,6 +242,7 @@ export const Preview = memo(() => {
101
  }}
102
  />
103
  </div>
 
104
  {previews.length > 1 && (
105
  <PortDropdown
106
  activePreviewIndex={activePreviewIndex}
@@ -111,13 +253,93 @@ export const Preview = memo(() => {
111
  previews={previews}
112
  />
113
  )}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
114
  </div>
115
- <div className="flex-1 border-t border-bolt-elements-borderColor">
116
- {activePreview ? (
117
- <iframe ref={iframeRef} className="border-none w-full h-full bg-white" src={iframeUrl} />
118
- ) : (
119
- <div className="flex w-full h-full justify-center items-center bg-white">No preview available</div>
120
- )}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
121
  </div>
122
  </div>
123
  );
 
4
  import { workbenchStore } from '~/lib/stores/workbench';
5
  import { PortDropdown } from './PortDropdown';
6
 
7
+ type ResizeSide = 'left' | 'right' | null;
8
+
9
  export const Preview = memo(() => {
10
  const iframeRef = useRef<HTMLIFrameElement>(null);
11
+ const containerRef = useRef<HTMLDivElement>(null);
12
  const inputRef = useRef<HTMLInputElement>(null);
13
+
14
  const [activePreviewIndex, setActivePreviewIndex] = useState(0);
15
  const [isPortDropdownOpen, setIsPortDropdownOpen] = useState(false);
16
+ const [isFullscreen, setIsFullscreen] = useState(false);
17
  const hasSelectedPreview = useRef(false);
18
  const previews = useStore(workbenchStore.previews);
19
  const activePreview = previews[activePreviewIndex];
 
21
  const [url, setUrl] = useState('');
22
  const [iframeUrl, setIframeUrl] = useState<string | undefined>();
23
 
24
+ // Toggle between responsive mode and device mode
25
+ const [isDeviceModeOn, setIsDeviceModeOn] = useState(false);
26
+
27
+ // Use percentage for width
28
+ const [widthPercent, setWidthPercent] = useState<number>(37.5); // 375px assuming 1000px window width initially
29
+
30
+ const resizingState = useRef({
31
+ isResizing: false,
32
+ side: null as ResizeSide,
33
+ startX: 0,
34
+ startWidthPercent: 37.5,
35
+ windowWidth: window.innerWidth,
36
+ });
37
+
38
+ // Define the scaling factor
39
+ const SCALING_FACTOR = 2; // Adjust this value to increase/decrease sensitivity
40
+
41
  useEffect(() => {
42
  if (!activePreview) {
43
  setUrl('');
 
47
  }
48
 
49
  const { baseUrl } = activePreview;
 
50
  setUrl(baseUrl);
51
  setIframeUrl(baseUrl);
52
+ }, [activePreview]);
53
 
54
  const validateUrl = useCallback(
55
  (value: string) => {
 
77
  [],
78
  );
79
 
80
+ // When previews change, display the lowest port if user hasn't selected a preview
81
  useEffect(() => {
82
  if (previews.length > 1 && !hasSelectedPreview.current) {
83
  const minPortIndex = previews.reduce(findMinPortIndex, 0);
 
84
  setActivePreviewIndex(minPortIndex);
85
  }
86
+ }, [previews, findMinPortIndex]);
87
 
88
  const reloadPreview = () => {
89
  if (iframeRef.current) {
 
91
  }
92
  };
93
 
94
+ const toggleFullscreen = async () => {
95
+ if (!isFullscreen && containerRef.current) {
96
+ await containerRef.current.requestFullscreen();
97
+ } else if (document.fullscreenElement) {
98
+ await document.exitFullscreen();
99
+ }
100
+ };
101
+
102
+ useEffect(() => {
103
+ const handleFullscreenChange = () => {
104
+ setIsFullscreen(!!document.fullscreenElement);
105
+ };
106
+
107
+ document.addEventListener('fullscreenchange', handleFullscreenChange);
108
+
109
+ return () => {
110
+ document.removeEventListener('fullscreenchange', handleFullscreenChange);
111
+ };
112
+ }, []);
113
+
114
+ const toggleDeviceMode = () => {
115
+ setIsDeviceModeOn((prev) => !prev);
116
+ };
117
+
118
+ const startResizing = (e: React.MouseEvent, side: ResizeSide) => {
119
+ if (!isDeviceModeOn) {
120
+ return;
121
+ }
122
+
123
+ // Prevent text selection
124
+ document.body.style.userSelect = 'none';
125
+
126
+ resizingState.current.isResizing = true;
127
+ resizingState.current.side = side;
128
+ resizingState.current.startX = e.clientX;
129
+ resizingState.current.startWidthPercent = widthPercent;
130
+ resizingState.current.windowWidth = window.innerWidth;
131
+
132
+ document.addEventListener('mousemove', onMouseMove);
133
+ document.addEventListener('mouseup', onMouseUp);
134
+
135
+ e.preventDefault(); // Prevent any text selection on mousedown
136
+ };
137
+
138
+ const onMouseMove = (e: MouseEvent) => {
139
+ if (!resizingState.current.isResizing) {
140
+ return;
141
+ }
142
+
143
+ const dx = e.clientX - resizingState.current.startX;
144
+ const windowWidth = resizingState.current.windowWidth;
145
+
146
+ // Apply scaling factor to increase sensitivity
147
+ const dxPercent = (dx / windowWidth) * 100 * SCALING_FACTOR;
148
+
149
+ let newWidthPercent = resizingState.current.startWidthPercent;
150
+
151
+ if (resizingState.current.side === 'right') {
152
+ newWidthPercent = resizingState.current.startWidthPercent + dxPercent;
153
+ } else if (resizingState.current.side === 'left') {
154
+ newWidthPercent = resizingState.current.startWidthPercent - dxPercent;
155
+ }
156
+
157
+ // Clamp the width between 10% and 90%
158
+ newWidthPercent = Math.max(10, Math.min(newWidthPercent, 90));
159
+
160
+ setWidthPercent(newWidthPercent);
161
+ };
162
+
163
+ const onMouseUp = () => {
164
+ resizingState.current.isResizing = false;
165
+ resizingState.current.side = null;
166
+ document.removeEventListener('mousemove', onMouseMove);
167
+ document.removeEventListener('mouseup', onMouseUp);
168
+
169
+ // Restore text selection
170
+ document.body.style.userSelect = '';
171
+ };
172
+
173
+ // Handle window resize to ensure widthPercent remains valid
174
+ useEffect(() => {
175
+ const handleWindowResize = () => {
176
+ /*
177
+ * Optional: Adjust widthPercent if necessary
178
+ * For now, since widthPercent is relative, no action is needed
179
+ */
180
+ };
181
+
182
+ window.addEventListener('resize', handleWindowResize);
183
+
184
+ return () => {
185
+ window.removeEventListener('resize', handleWindowResize);
186
+ };
187
+ }, []);
188
+
189
+ // A small helper component for the handle's "grip" icon
190
+ const GripIcon = () => (
191
+ <div
192
+ style={{
193
+ display: 'flex',
194
+ justifyContent: 'center',
195
+ alignItems: 'center',
196
+ height: '100%',
197
+ pointerEvents: 'none',
198
+ }}
199
+ >
200
+ <div
201
+ style={{
202
+ color: 'rgba(0,0,0,0.5)',
203
+ fontSize: '10px',
204
+ lineHeight: '5px',
205
+ userSelect: 'none',
206
+ marginLeft: '1px',
207
+ }}
208
+ >
209
+ ••• •••
210
+ </div>
211
+ </div>
212
+ );
213
+
214
  return (
215
+ <div ref={containerRef} className="w-full h-full flex flex-col relative">
216
  {isPortDropdownOpen && (
217
  <div className="z-iframe-overlay w-full h-full absolute" onClick={() => setIsPortDropdownOpen(false)} />
218
  )}
219
  <div className="bg-bolt-elements-background-depth-2 p-2 flex items-center gap-1.5">
220
  <IconButton icon="i-ph:arrow-clockwise" onClick={reloadPreview} />
221
+
222
  <div
223
  className="flex items-center gap-1 flex-grow bg-bolt-elements-preview-addressBar-background border border-bolt-elements-borderColor text-bolt-elements-preview-addressBar-text rounded-full px-3 py-1 text-sm hover:bg-bolt-elements-preview-addressBar-backgroundHover hover:focus-within:bg-bolt-elements-preview-addressBar-backgroundActive focus-within:bg-bolt-elements-preview-addressBar-backgroundActive
224
  focus-within-border-bolt-elements-borderColorActive focus-within:text-bolt-elements-preview-addressBar-textActive"
 
242
  }}
243
  />
244
  </div>
245
+
246
  {previews.length > 1 && (
247
  <PortDropdown
248
  activePreviewIndex={activePreviewIndex}
 
253
  previews={previews}
254
  />
255
  )}
256
+
257
+ {/* Device mode toggle button */}
258
+ <IconButton
259
+ icon="i-ph:devices"
260
+ onClick={toggleDeviceMode}
261
+ title={isDeviceModeOn ? 'Switch to Responsive Mode' : 'Switch to Device Mode'}
262
+ />
263
+
264
+ {/* Fullscreen toggle button */}
265
+ <IconButton
266
+ icon={isFullscreen ? 'i-ph:arrows-in' : 'i-ph:arrows-out'}
267
+ onClick={toggleFullscreen}
268
+ title={isFullscreen ? 'Exit Full Screen' : 'Full Screen'}
269
+ />
270
  </div>
271
+
272
+ <div className="flex-1 border-t border-bolt-elements-borderColor flex justify-center items-center overflow-auto">
273
+ <div
274
+ style={{
275
+ width: isDeviceModeOn ? `${widthPercent}%` : '100%',
276
+ height: '100%', // Always full height
277
+ overflow: 'visible',
278
+ background: '#fff',
279
+ position: 'relative',
280
+ display: 'flex',
281
+ }}
282
+ >
283
+ {activePreview ? (
284
+ <iframe ref={iframeRef} className="border-none w-full h-full bg-white" src={iframeUrl} allowFullScreen />
285
+ ) : (
286
+ <div className="flex w-full h-full justify-center items-center bg-white">No preview available</div>
287
+ )}
288
+
289
+ {isDeviceModeOn && (
290
+ <>
291
+ {/* Left handle */}
292
+ <div
293
+ onMouseDown={(e) => startResizing(e, 'left')}
294
+ style={{
295
+ position: 'absolute',
296
+ top: 0,
297
+ left: 0,
298
+ width: '15px',
299
+ marginLeft: '-15px',
300
+ height: '100%',
301
+ cursor: 'ew-resize',
302
+ background: 'rgba(255,255,255,.2)',
303
+ display: 'flex',
304
+ alignItems: 'center',
305
+ justifyContent: 'center',
306
+ transition: 'background 0.2s',
307
+ userSelect: 'none',
308
+ }}
309
+ onMouseOver={(e) => (e.currentTarget.style.background = 'rgba(255,255,255,.5)')}
310
+ onMouseOut={(e) => (e.currentTarget.style.background = 'rgba(255,255,255,.2)')}
311
+ title="Drag to resize width"
312
+ >
313
+ <GripIcon />
314
+ </div>
315
+
316
+ {/* Right handle */}
317
+ <div
318
+ onMouseDown={(e) => startResizing(e, 'right')}
319
+ style={{
320
+ position: 'absolute',
321
+ top: 0,
322
+ right: 0,
323
+ width: '15px',
324
+ marginRight: '-15px',
325
+ height: '100%',
326
+ cursor: 'ew-resize',
327
+ background: 'rgba(255,255,255,.2)',
328
+ display: 'flex',
329
+ alignItems: 'center',
330
+ justifyContent: 'center',
331
+ transition: 'background 0.2s',
332
+ userSelect: 'none',
333
+ }}
334
+ onMouseOver={(e) => (e.currentTarget.style.background = 'rgba(255,255,255,.5)')}
335
+ onMouseOut={(e) => (e.currentTarget.style.background = 'rgba(255,255,255,.2)')}
336
+ title="Drag to resize width"
337
+ >
338
+ <GripIcon />
339
+ </div>
340
+ </>
341
+ )}
342
+ </div>
343
  </div>
344
  </div>
345
  );
app/components/workbench/Workbench.client.tsx CHANGED
@@ -16,6 +16,7 @@ import { cubicEasingFn } from '~/utils/easings';
16
  import { renderLogger } from '~/utils/logger';
17
  import { EditorPanel } from './EditorPanel';
18
  import { Preview } from './Preview';
 
19
 
20
  interface WorkspaceProps {
21
  chatStarted?: boolean;
@@ -65,6 +66,8 @@ export const Workbench = memo(({ chatStarted, isStreaming }: WorkspaceProps) =>
65
  const files = useStore(workbenchStore.files);
66
  const selectedView = useStore(workbenchStore.currentView);
67
 
 
 
68
  const setSelectedView = (view: WorkbenchViewType) => {
69
  workbenchStore.currentView.set(view);
70
  };
@@ -128,18 +131,20 @@ export const Workbench = memo(({ chatStarted, isStreaming }: WorkspaceProps) =>
128
  className={classNames(
129
  'fixed top-[calc(var(--header-height)+1.5rem)] bottom-6 w-[var(--workbench-inner-width)] mr-4 z-0 transition-[left,width] duration-200 bolt-ease-cubic-bezier',
130
  {
 
 
131
  'left-[var(--workbench-left)]': showWorkbench,
132
  'left-[100%]': !showWorkbench,
133
  },
134
  )}
135
  >
136
- <div className="absolute inset-0 px-6">
137
  <div className="h-full flex flex-col bg-bolt-elements-background-depth-2 border border-bolt-elements-borderColor shadow-sm rounded-lg overflow-hidden">
138
  <div className="flex items-center px-3 py-2 border-b border-bolt-elements-borderColor">
139
  <Slider selected={selectedView} options={sliderOptions} setSelected={setSelectedView} />
140
  <div className="ml-auto" />
141
  {selectedView === 'code' && (
142
- <>
143
  <PanelHeaderButton
144
  className="mr-1 text-sm"
145
  onClick={() => {
@@ -165,29 +170,37 @@ export const Workbench = memo(({ chatStarted, isStreaming }: WorkspaceProps) =>
165
  <PanelHeaderButton
166
  className="mr-1 text-sm"
167
  onClick={() => {
168
- const repoName = prompt("Please enter a name for your new GitHub repository:", "bolt-generated-project");
 
 
 
 
169
  if (!repoName) {
170
- alert("Repository name is required. Push to GitHub cancelled.");
171
  return;
172
  }
173
- const githubUsername = prompt("Please enter your GitHub username:");
 
 
174
  if (!githubUsername) {
175
- alert("GitHub username is required. Push to GitHub cancelled.");
176
  return;
177
  }
178
- const githubToken = prompt("Please enter your GitHub personal access token:");
 
 
179
  if (!githubToken) {
180
- alert("GitHub token is required. Push to GitHub cancelled.");
181
  return;
182
  }
183
-
184
- workbenchStore.pushToGitHub(repoName, githubUsername, githubToken);
185
  }}
186
  >
187
  <div className="i-ph:github-logo" />
188
  Push to GitHub
189
  </PanelHeaderButton>
190
- </>
191
  )}
192
  <IconButton
193
  icon="i-ph:x-circle"
 
16
  import { renderLogger } from '~/utils/logger';
17
  import { EditorPanel } from './EditorPanel';
18
  import { Preview } from './Preview';
19
+ import useViewport from '~/lib/hooks';
20
 
21
  interface WorkspaceProps {
22
  chatStarted?: boolean;
 
66
  const files = useStore(workbenchStore.files);
67
  const selectedView = useStore(workbenchStore.currentView);
68
 
69
+ const isSmallViewport = useViewport(1024);
70
+
71
  const setSelectedView = (view: WorkbenchViewType) => {
72
  workbenchStore.currentView.set(view);
73
  };
 
131
  className={classNames(
132
  'fixed top-[calc(var(--header-height)+1.5rem)] bottom-6 w-[var(--workbench-inner-width)] mr-4 z-0 transition-[left,width] duration-200 bolt-ease-cubic-bezier',
133
  {
134
+ 'w-full': isSmallViewport,
135
+ 'left-0': showWorkbench && isSmallViewport,
136
  'left-[var(--workbench-left)]': showWorkbench,
137
  'left-[100%]': !showWorkbench,
138
  },
139
  )}
140
  >
141
+ <div className="absolute inset-0 px-2 lg:px-6">
142
  <div className="h-full flex flex-col bg-bolt-elements-background-depth-2 border border-bolt-elements-borderColor shadow-sm rounded-lg overflow-hidden">
143
  <div className="flex items-center px-3 py-2 border-b border-bolt-elements-borderColor">
144
  <Slider selected={selectedView} options={sliderOptions} setSelected={setSelectedView} />
145
  <div className="ml-auto" />
146
  {selectedView === 'code' && (
147
+ <div className="flex overflow-y-auto">
148
  <PanelHeaderButton
149
  className="mr-1 text-sm"
150
  onClick={() => {
 
170
  <PanelHeaderButton
171
  className="mr-1 text-sm"
172
  onClick={() => {
173
+ const repoName = prompt(
174
+ 'Please enter a name for your new GitHub repository:',
175
+ 'bolt-generated-project',
176
+ );
177
+
178
  if (!repoName) {
179
+ alert('Repository name is required. Push to GitHub cancelled.');
180
  return;
181
  }
182
+
183
+ const githubUsername = prompt('Please enter your GitHub username:');
184
+
185
  if (!githubUsername) {
186
+ alert('GitHub username is required. Push to GitHub cancelled.');
187
  return;
188
  }
189
+
190
+ const githubToken = prompt('Please enter your GitHub personal access token:');
191
+
192
  if (!githubToken) {
193
+ alert('GitHub token is required. Push to GitHub cancelled.');
194
  return;
195
  }
196
+
197
+ workbenchStore.pushToGitHub(repoName, githubUsername, githubToken);
198
  }}
199
  >
200
  <div className="i-ph:github-logo" />
201
  Push to GitHub
202
  </PanelHeaderButton>
203
+ </div>
204
  )}
205
  <IconButton
206
  icon="i-ph:x-circle"
app/components/workbench/terminal/Terminal.tsx CHANGED
@@ -16,71 +16,74 @@ export interface TerminalProps {
16
  className?: string;
17
  theme: Theme;
18
  readonly?: boolean;
 
19
  onTerminalReady?: (terminal: XTerm) => void;
20
  onTerminalResize?: (cols: number, rows: number) => void;
21
  }
22
 
23
  export const Terminal = memo(
24
- forwardRef<TerminalRef, TerminalProps>(({ className, theme, readonly, onTerminalReady, onTerminalResize }, ref) => {
25
- const terminalElementRef = useRef<HTMLDivElement>(null);
26
- const terminalRef = useRef<XTerm>();
27
-
28
- useEffect(() => {
29
- const element = terminalElementRef.current!;
30
-
31
- const fitAddon = new FitAddon();
32
- const webLinksAddon = new WebLinksAddon();
33
-
34
- const terminal = new XTerm({
35
- cursorBlink: true,
36
- convertEol: true,
37
- disableStdin: readonly,
38
- theme: getTerminalTheme(readonly ? { cursor: '#00000000' } : {}),
39
- fontSize: 12,
40
- fontFamily: 'Menlo, courier-new, courier, monospace',
41
- });
42
-
43
- terminalRef.current = terminal;
44
-
45
- terminal.loadAddon(fitAddon);
46
- terminal.loadAddon(webLinksAddon);
47
- terminal.open(element);
48
-
49
- const resizeObserver = new ResizeObserver(() => {
50
- fitAddon.fit();
51
- onTerminalResize?.(terminal.cols, terminal.rows);
52
- });
53
-
54
- resizeObserver.observe(element);
55
-
56
- logger.info('Attach terminal');
57
-
58
- onTerminalReady?.(terminal);
59
-
60
- return () => {
61
- resizeObserver.disconnect();
62
- terminal.dispose();
63
- };
64
- }, []);
65
-
66
- useEffect(() => {
67
- const terminal = terminalRef.current!;
68
-
69
- // we render a transparent cursor in case the terminal is readonly
70
- terminal.options.theme = getTerminalTheme(readonly ? { cursor: '#00000000' } : {});
71
-
72
- terminal.options.disableStdin = readonly;
73
- }, [theme, readonly]);
74
-
75
- useImperativeHandle(ref, () => {
76
- return {
77
- reloadStyles: () => {
78
- const terminal = terminalRef.current!;
79
- terminal.options.theme = getTerminalTheme(readonly ? { cursor: '#00000000' } : {});
80
- },
81
- };
82
- }, []);
83
-
84
- return <div className={className} ref={terminalElementRef} />;
85
- }),
 
 
86
  );
 
16
  className?: string;
17
  theme: Theme;
18
  readonly?: boolean;
19
+ id: string;
20
  onTerminalReady?: (terminal: XTerm) => void;
21
  onTerminalResize?: (cols: number, rows: number) => void;
22
  }
23
 
24
  export const Terminal = memo(
25
+ forwardRef<TerminalRef, TerminalProps>(
26
+ ({ className, theme, readonly, id, onTerminalReady, onTerminalResize }, ref) => {
27
+ const terminalElementRef = useRef<HTMLDivElement>(null);
28
+ const terminalRef = useRef<XTerm>();
29
+
30
+ useEffect(() => {
31
+ const element = terminalElementRef.current!;
32
+
33
+ const fitAddon = new FitAddon();
34
+ const webLinksAddon = new WebLinksAddon();
35
+
36
+ const terminal = new XTerm({
37
+ cursorBlink: true,
38
+ convertEol: true,
39
+ disableStdin: readonly,
40
+ theme: getTerminalTheme(readonly ? { cursor: '#00000000' } : {}),
41
+ fontSize: 12,
42
+ fontFamily: 'Menlo, courier-new, courier, monospace',
43
+ });
44
+
45
+ terminalRef.current = terminal;
46
+
47
+ terminal.loadAddon(fitAddon);
48
+ terminal.loadAddon(webLinksAddon);
49
+ terminal.open(element);
50
+
51
+ const resizeObserver = new ResizeObserver(() => {
52
+ fitAddon.fit();
53
+ onTerminalResize?.(terminal.cols, terminal.rows);
54
+ });
55
+
56
+ resizeObserver.observe(element);
57
+
58
+ logger.debug(`Attach [${id}]`);
59
+
60
+ onTerminalReady?.(terminal);
61
+
62
+ return () => {
63
+ resizeObserver.disconnect();
64
+ terminal.dispose();
65
+ };
66
+ }, []);
67
+
68
+ useEffect(() => {
69
+ const terminal = terminalRef.current!;
70
+
71
+ // we render a transparent cursor in case the terminal is readonly
72
+ terminal.options.theme = getTerminalTheme(readonly ? { cursor: '#00000000' } : {});
73
+
74
+ terminal.options.disableStdin = readonly;
75
+ }, [theme, readonly]);
76
+
77
+ useImperativeHandle(ref, () => {
78
+ return {
79
+ reloadStyles: () => {
80
+ const terminal = terminalRef.current!;
81
+ terminal.options.theme = getTerminalTheme(readonly ? { cursor: '#00000000' } : {});
82
+ },
83
+ };
84
+ }, []);
85
+
86
+ return <div className={className} ref={terminalElementRef} />;
87
+ },
88
+ ),
89
  );
app/components/workbench/terminal/TerminalTabs.tsx ADDED
@@ -0,0 +1,186 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { useStore } from '@nanostores/react';
2
+ import React, { memo, useEffect, useRef, useState } from 'react';
3
+ import { Panel, type ImperativePanelHandle } from 'react-resizable-panels';
4
+ import { IconButton } from '~/components/ui/IconButton';
5
+ import { shortcutEventEmitter } from '~/lib/hooks';
6
+ import { themeStore } from '~/lib/stores/theme';
7
+ import { workbenchStore } from '~/lib/stores/workbench';
8
+ import { classNames } from '~/utils/classNames';
9
+ import { Terminal, type TerminalRef } from './Terminal';
10
+ import { createScopedLogger } from '~/utils/logger';
11
+
12
+ const logger = createScopedLogger('Terminal');
13
+
14
+ const MAX_TERMINALS = 3;
15
+ export const DEFAULT_TERMINAL_SIZE = 25;
16
+
17
+ export const TerminalTabs = memo(() => {
18
+ const showTerminal = useStore(workbenchStore.showTerminal);
19
+ const theme = useStore(themeStore);
20
+
21
+ const terminalRefs = useRef<Array<TerminalRef | null>>([]);
22
+ const terminalPanelRef = useRef<ImperativePanelHandle>(null);
23
+ const terminalToggledByShortcut = useRef(false);
24
+
25
+ const [activeTerminal, setActiveTerminal] = useState(0);
26
+ const [terminalCount, setTerminalCount] = useState(1);
27
+
28
+ const addTerminal = () => {
29
+ if (terminalCount < MAX_TERMINALS) {
30
+ setTerminalCount(terminalCount + 1);
31
+ setActiveTerminal(terminalCount);
32
+ }
33
+ };
34
+
35
+ useEffect(() => {
36
+ const { current: terminal } = terminalPanelRef;
37
+
38
+ if (!terminal) {
39
+ return;
40
+ }
41
+
42
+ const isCollapsed = terminal.isCollapsed();
43
+
44
+ if (!showTerminal && !isCollapsed) {
45
+ terminal.collapse();
46
+ } else if (showTerminal && isCollapsed) {
47
+ terminal.resize(DEFAULT_TERMINAL_SIZE);
48
+ }
49
+
50
+ terminalToggledByShortcut.current = false;
51
+ }, [showTerminal]);
52
+
53
+ useEffect(() => {
54
+ const unsubscribeFromEventEmitter = shortcutEventEmitter.on('toggleTerminal', () => {
55
+ terminalToggledByShortcut.current = true;
56
+ });
57
+
58
+ const unsubscribeFromThemeStore = themeStore.subscribe(() => {
59
+ for (const ref of Object.values(terminalRefs.current)) {
60
+ ref?.reloadStyles();
61
+ }
62
+ });
63
+
64
+ return () => {
65
+ unsubscribeFromEventEmitter();
66
+ unsubscribeFromThemeStore();
67
+ };
68
+ }, []);
69
+
70
+ return (
71
+ <Panel
72
+ ref={terminalPanelRef}
73
+ defaultSize={showTerminal ? DEFAULT_TERMINAL_SIZE : 0}
74
+ minSize={10}
75
+ collapsible
76
+ onExpand={() => {
77
+ if (!terminalToggledByShortcut.current) {
78
+ workbenchStore.toggleTerminal(true);
79
+ }
80
+ }}
81
+ onCollapse={() => {
82
+ if (!terminalToggledByShortcut.current) {
83
+ workbenchStore.toggleTerminal(false);
84
+ }
85
+ }}
86
+ >
87
+ <div className="h-full">
88
+ <div className="bg-bolt-elements-terminals-background h-full flex flex-col">
89
+ <div className="flex items-center bg-bolt-elements-background-depth-2 border-y border-bolt-elements-borderColor gap-1.5 min-h-[34px] p-2">
90
+ {Array.from({ length: terminalCount + 1 }, (_, index) => {
91
+ const isActive = activeTerminal === index;
92
+
93
+ return (
94
+ <React.Fragment key={index}>
95
+ {index == 0 ? (
96
+ <button
97
+ key={index}
98
+ className={classNames(
99
+ 'flex items-center text-sm cursor-pointer gap-1.5 px-3 py-2 h-full whitespace-nowrap rounded-full',
100
+ {
101
+ 'bg-bolt-elements-terminals-buttonBackground text-bolt-elements-textSecondary hover:text-bolt-elements-textPrimary':
102
+ isActive,
103
+ 'bg-bolt-elements-background-depth-2 text-bolt-elements-textSecondary hover:bg-bolt-elements-terminals-buttonBackground':
104
+ !isActive,
105
+ },
106
+ )}
107
+ onClick={() => setActiveTerminal(index)}
108
+ >
109
+ <div className="i-ph:terminal-window-duotone text-lg" />
110
+ Bolt Terminal
111
+ </button>
112
+ ) : (
113
+ <React.Fragment>
114
+ <button
115
+ key={index}
116
+ className={classNames(
117
+ 'flex items-center text-sm cursor-pointer gap-1.5 px-3 py-2 h-full whitespace-nowrap rounded-full',
118
+ {
119
+ 'bg-bolt-elements-terminals-buttonBackground text-bolt-elements-textPrimary': isActive,
120
+ 'bg-bolt-elements-background-depth-2 text-bolt-elements-textSecondary hover:bg-bolt-elements-terminals-buttonBackground':
121
+ !isActive,
122
+ },
123
+ )}
124
+ onClick={() => setActiveTerminal(index)}
125
+ >
126
+ <div className="i-ph:terminal-window-duotone text-lg" />
127
+ Terminal {terminalCount > 1 && index}
128
+ </button>
129
+ </React.Fragment>
130
+ )}
131
+ </React.Fragment>
132
+ );
133
+ })}
134
+ {terminalCount < MAX_TERMINALS && <IconButton icon="i-ph:plus" size="md" onClick={addTerminal} />}
135
+ <IconButton
136
+ className="ml-auto"
137
+ icon="i-ph:caret-down"
138
+ title="Close"
139
+ size="md"
140
+ onClick={() => workbenchStore.toggleTerminal(false)}
141
+ />
142
+ </div>
143
+ {Array.from({ length: terminalCount + 1 }, (_, index) => {
144
+ const isActive = activeTerminal === index;
145
+
146
+ logger.debug(`Starting bolt terminal [${index}]`);
147
+
148
+ if (index == 0) {
149
+ return (
150
+ <Terminal
151
+ key={index}
152
+ id={`terminal_${index}`}
153
+ className={classNames('h-full overflow-hidden', {
154
+ hidden: !isActive,
155
+ })}
156
+ ref={(ref) => {
157
+ terminalRefs.current.push(ref);
158
+ }}
159
+ onTerminalReady={(terminal) => workbenchStore.attachBoltTerminal(terminal)}
160
+ onTerminalResize={(cols, rows) => workbenchStore.onTerminalResize(cols, rows)}
161
+ theme={theme}
162
+ />
163
+ );
164
+ } else {
165
+ return (
166
+ <Terminal
167
+ key={index}
168
+ id={`terminal_${index}`}
169
+ className={classNames('h-full overflow-hidden', {
170
+ hidden: !isActive,
171
+ })}
172
+ ref={(ref) => {
173
+ terminalRefs.current.push(ref);
174
+ }}
175
+ onTerminalReady={(terminal) => workbenchStore.attachTerminal(terminal)}
176
+ onTerminalResize={(cols, rows) => workbenchStore.onTerminalResize(cols, rows)}
177
+ theme={theme}
178
+ />
179
+ );
180
+ }
181
+ })}
182
+ </div>
183
+ </div>
184
+ </Panel>
185
+ );
186
+ });
app/entry.server.tsx CHANGED
@@ -43,7 +43,7 @@ export default async function handleRequest(
43
  .read()
44
  .then(({ done, value }) => {
45
  if (done) {
46
- controller.enqueue(new Uint8Array(new TextEncoder().encode(`</div></body></html>`)));
47
  controller.close();
48
 
49
  return;
 
43
  .read()
44
  .then(({ done, value }) => {
45
  if (done) {
46
+ controller.enqueue(new Uint8Array(new TextEncoder().encode('</div></body></html>')));
47
  controller.close();
48
 
49
  return;
app/lib/.server/llm/api-key.ts CHANGED
@@ -1,5 +1,7 @@
1
- // @ts-nocheck
2
- // Preventing TS checks with files presented in the video for a better presentation.
 
 
3
  import { env } from 'node:process';
4
 
5
  export function getAPIKey(cloudflareEnv: Env, provider: string, userApiKeys?: Record<string, string>) {
@@ -23,34 +25,47 @@ export function getAPIKey(cloudflareEnv: Env, provider: string, userApiKeys?: Re
23
  return env.GOOGLE_GENERATIVE_AI_API_KEY || cloudflareEnv.GOOGLE_GENERATIVE_AI_API_KEY;
24
  case 'Groq':
25
  return env.GROQ_API_KEY || cloudflareEnv.GROQ_API_KEY;
 
 
26
  case 'OpenRouter':
27
  return env.OPEN_ROUTER_API_KEY || cloudflareEnv.OPEN_ROUTER_API_KEY;
28
  case 'Deepseek':
29
- return env.DEEPSEEK_API_KEY || cloudflareEnv.DEEPSEEK_API_KEY
30
  case 'Mistral':
31
- return env.MISTRAL_API_KEY || cloudflareEnv.MISTRAL_API_KEY;
32
- case "OpenAILike":
33
  return env.OPENAI_LIKE_API_KEY || cloudflareEnv.OPENAI_LIKE_API_KEY;
34
- case "xAI":
 
 
35
  return env.XAI_API_KEY || cloudflareEnv.XAI_API_KEY;
 
 
 
 
36
  default:
37
- return "";
38
  }
39
  }
40
 
41
  export function getBaseURL(cloudflareEnv: Env, provider: string) {
42
  switch (provider) {
 
 
43
  case 'OpenAILike':
44
  return env.OPENAI_LIKE_API_BASE_URL || cloudflareEnv.OPENAI_LIKE_API_BASE_URL;
45
  case 'LMStudio':
46
- return env.LMSTUDIO_API_BASE_URL || cloudflareEnv.LMSTUDIO_API_BASE_URL || "http://localhost:1234";
47
- case 'Ollama':
48
- let baseUrl = env.OLLAMA_API_BASE_URL || cloudflareEnv.OLLAMA_API_BASE_URL || "http://localhost:11434";
49
- if (env.RUNNING_IN_DOCKER === 'true') {
50
- baseUrl = baseUrl.replace("localhost", "host.docker.internal");
51
- }
52
- return baseUrl;
 
 
 
53
  default:
54
- return "";
55
  }
56
  }
 
1
+ /*
2
+ * @ts-nocheck
3
+ * Preventing TS checks with files presented in the video for a better presentation.
4
+ */
5
  import { env } from 'node:process';
6
 
7
  export function getAPIKey(cloudflareEnv: Env, provider: string, userApiKeys?: Record<string, string>) {
 
25
  return env.GOOGLE_GENERATIVE_AI_API_KEY || cloudflareEnv.GOOGLE_GENERATIVE_AI_API_KEY;
26
  case 'Groq':
27
  return env.GROQ_API_KEY || cloudflareEnv.GROQ_API_KEY;
28
+ case 'HuggingFace':
29
+ return env.HuggingFace_API_KEY || cloudflareEnv.HuggingFace_API_KEY;
30
  case 'OpenRouter':
31
  return env.OPEN_ROUTER_API_KEY || cloudflareEnv.OPEN_ROUTER_API_KEY;
32
  case 'Deepseek':
33
+ return env.DEEPSEEK_API_KEY || cloudflareEnv.DEEPSEEK_API_KEY;
34
  case 'Mistral':
35
+ return env.MISTRAL_API_KEY || cloudflareEnv.MISTRAL_API_KEY;
36
+ case 'OpenAILike':
37
  return env.OPENAI_LIKE_API_KEY || cloudflareEnv.OPENAI_LIKE_API_KEY;
38
+ case 'Together':
39
+ return env.TOGETHER_API_KEY || cloudflareEnv.TOGETHER_API_KEY;
40
+ case 'xAI':
41
  return env.XAI_API_KEY || cloudflareEnv.XAI_API_KEY;
42
+ case 'Cohere':
43
+ return env.COHERE_API_KEY;
44
+ case 'AzureOpenAI':
45
+ return env.AZURE_OPENAI_API_KEY;
46
  default:
47
+ return '';
48
  }
49
  }
50
 
51
  export function getBaseURL(cloudflareEnv: Env, provider: string) {
52
  switch (provider) {
53
+ case 'Together':
54
+ return env.TOGETHER_API_BASE_URL || cloudflareEnv.TOGETHER_API_BASE_URL || 'https://api.together.xyz/v1';
55
  case 'OpenAILike':
56
  return env.OPENAI_LIKE_API_BASE_URL || cloudflareEnv.OPENAI_LIKE_API_BASE_URL;
57
  case 'LMStudio':
58
+ return env.LMSTUDIO_API_BASE_URL || cloudflareEnv.LMSTUDIO_API_BASE_URL || 'http://localhost:1234';
59
+ case 'Ollama': {
60
+ let baseUrl = env.OLLAMA_API_BASE_URL || cloudflareEnv.OLLAMA_API_BASE_URL || 'http://localhost:11434';
61
+
62
+ if (env.RUNNING_IN_DOCKER === 'true') {
63
+ baseUrl = baseUrl.replace('localhost', 'host.docker.internal');
64
+ }
65
+
66
+ return baseUrl;
67
+ }
68
  default:
69
+ return '';
70
  }
71
  }
app/lib/.server/llm/model.ts CHANGED
@@ -1,22 +1,29 @@
1
- // @ts-nocheck
2
- // Preventing TS checks with files presented in the video for a better presentation.
 
 
3
  import { getAPIKey, getBaseURL } from '~/lib/.server/llm/api-key';
4
  import { createAnthropic } from '@ai-sdk/anthropic';
5
  import { createOpenAI } from '@ai-sdk/openai';
6
  import { createGoogleGenerativeAI } from '@ai-sdk/google';
7
  import { ollama } from 'ollama-ai-provider';
8
- import { createOpenRouter } from "@openrouter/ai-sdk-provider";
9
- import { mistral } from '@ai-sdk/mistral';
10
  import { createMistral } from '@ai-sdk/mistral';
 
 
11
 
12
- export function getAnthropicModel(apiKey: string, model: string) {
 
 
 
 
13
  const anthropic = createAnthropic({
14
  apiKey,
15
  });
16
 
17
  return anthropic(model);
18
  }
19
- export function getOpenAILikeModel(baseURL:string,apiKey: string, model: string) {
20
  const openai = createOpenAI({
21
  baseURL,
22
  apiKey,
@@ -24,7 +31,16 @@ export function getOpenAILikeModel(baseURL:string,apiKey: string, model: string)
24
 
25
  return openai(model);
26
  }
27
- export function getOpenAIModel(apiKey: string, model: string) {
 
 
 
 
 
 
 
 
 
28
  const openai = createOpenAI({
29
  apiKey,
30
  });
@@ -32,23 +48,23 @@ export function getOpenAIModel(apiKey: string, model: string) {
32
  return openai(model);
33
  }
34
 
35
- export function getMistralModel(apiKey: string, model: string) {
36
  const mistral = createMistral({
37
- apiKey
38
  });
39
 
40
  return mistral(model);
41
  }
42
 
43
- export function getGoogleModel(apiKey: string, model: string) {
44
- const google = createGoogleGenerativeAI(
45
  apiKey,
46
- );
47
 
48
  return google(model);
49
  }
50
 
51
- export function getGroqModel(apiKey: string, model: string) {
52
  const openai = createOpenAI({
53
  baseURL: 'https://api.groq.com/openai/v1',
54
  apiKey,
@@ -57,16 +73,26 @@ export function getGroqModel(apiKey: string, model: string) {
57
  return openai(model);
58
  }
59
 
60
- export function getOllamaModel(baseURL: string, model: string) {
61
- let Ollama = ollama(model, {
62
- numCtx: 32768,
 
63
  });
64
 
65
- Ollama.config.baseURL = `${baseURL}/api`;
66
- return Ollama;
67
  }
68
 
69
- export function getDeepseekModel(apiKey: string, model: string){
 
 
 
 
 
 
 
 
 
 
70
  const openai = createOpenAI({
71
  baseURL: 'https://api.deepseek.com/beta',
72
  apiKey,
@@ -75,9 +101,9 @@ export function getDeepseekModel(apiKey: string, model: string){
75
  return openai(model);
76
  }
77
 
78
- export function getOpenRouterModel(apiKey: string, model: string) {
79
  const openRouter = createOpenRouter({
80
- apiKey
81
  });
82
 
83
  return openRouter.chat(model);
@@ -86,13 +112,13 @@ export function getOpenRouterModel(apiKey: string, model: string) {
86
  export function getLMStudioModel(baseURL: string, model: string) {
87
  const lmstudio = createOpenAI({
88
  baseUrl: `${baseURL}/v1`,
89
- apiKey: "",
90
  });
91
 
92
  return lmstudio(model);
93
  }
94
 
95
- export function getXAIModel(apiKey: string, model: string) {
96
  const openai = createOpenAI({
97
  baseURL: 'https://api.x.ai/v1',
98
  apiKey,
@@ -100,8 +126,14 @@ export function getXAIModel(apiKey: string, model: string) {
100
 
101
  return openai(model);
102
  }
 
103
  export function getModel(provider: string, model: string, env: Env, apiKeys?: Record<string, string>) {
104
- const apiKey = getAPIKey(env, provider, apiKeys);
 
 
 
 
 
105
  const baseURL = getBaseURL(env, provider);
106
 
107
  switch (provider) {
@@ -111,20 +143,26 @@ export function getModel(provider: string, model: string, env: Env, apiKeys?: Re
111
  return getOpenAIModel(apiKey, model);
112
  case 'Groq':
113
  return getGroqModel(apiKey, model);
 
 
114
  case 'OpenRouter':
115
  return getOpenRouterModel(apiKey, model);
116
  case 'Google':
117
  return getGoogleModel(apiKey, model);
118
  case 'OpenAILike':
119
- return getOpenAILikeModel(baseURL,apiKey, model);
 
 
120
  case 'Deepseek':
121
  return getDeepseekModel(apiKey, model);
122
  case 'Mistral':
123
- return getMistralModel(apiKey, model);
124
  case 'LMStudio':
125
  return getLMStudioModel(baseURL, model);
126
  case 'xAI':
127
  return getXAIModel(apiKey, model);
 
 
128
  default:
129
  return getOllamaModel(baseURL, model);
130
  }
 
1
+ /*
2
+ * @ts-nocheck
3
+ * Preventing TS checks with files presented in the video for a better presentation.
4
+ */
5
  import { getAPIKey, getBaseURL } from '~/lib/.server/llm/api-key';
6
  import { createAnthropic } from '@ai-sdk/anthropic';
7
  import { createOpenAI } from '@ai-sdk/openai';
8
  import { createGoogleGenerativeAI } from '@ai-sdk/google';
9
  import { ollama } from 'ollama-ai-provider';
10
+ import { createOpenRouter } from '@openrouter/ai-sdk-provider';
 
11
  import { createMistral } from '@ai-sdk/mistral';
12
+ import { createCohere } from '@ai-sdk/cohere';
13
+ import type { LanguageModelV1 } from 'ai';
14
 
15
+ export const DEFAULT_NUM_CTX = process.env.DEFAULT_NUM_CTX ? parseInt(process.env.DEFAULT_NUM_CTX, 10) : 32768;
16
+
17
+ type OptionalApiKey = string | undefined;
18
+
19
+ export function getAnthropicModel(apiKey: OptionalApiKey, model: string) {
20
  const anthropic = createAnthropic({
21
  apiKey,
22
  });
23
 
24
  return anthropic(model);
25
  }
26
+ export function getOpenAILikeModel(baseURL: string, apiKey: OptionalApiKey, model: string) {
27
  const openai = createOpenAI({
28
  baseURL,
29
  apiKey,
 
31
 
32
  return openai(model);
33
  }
34
+
35
+ export function getCohereAIModel(apiKey: OptionalApiKey, model: string) {
36
+ const cohere = createCohere({
37
+ apiKey,
38
+ });
39
+
40
+ return cohere(model);
41
+ }
42
+
43
+ export function getOpenAIModel(apiKey: OptionalApiKey, model: string) {
44
  const openai = createOpenAI({
45
  apiKey,
46
  });
 
48
  return openai(model);
49
  }
50
 
51
+ export function getMistralModel(apiKey: OptionalApiKey, model: string) {
52
  const mistral = createMistral({
53
+ apiKey,
54
  });
55
 
56
  return mistral(model);
57
  }
58
 
59
+ export function getGoogleModel(apiKey: OptionalApiKey, model: string) {
60
+ const google = createGoogleGenerativeAI({
61
  apiKey,
62
+ });
63
 
64
  return google(model);
65
  }
66
 
67
+ export function getGroqModel(apiKey: OptionalApiKey, model: string) {
68
  const openai = createOpenAI({
69
  baseURL: 'https://api.groq.com/openai/v1',
70
  apiKey,
 
73
  return openai(model);
74
  }
75
 
76
+ export function getHuggingFaceModel(apiKey: OptionalApiKey, model: string) {
77
+ const openai = createOpenAI({
78
+ baseURL: 'https://api-inference.huggingface.co/v1/',
79
+ apiKey,
80
  });
81
 
82
+ return openai(model);
 
83
  }
84
 
85
+ export function getOllamaModel(baseURL: string, model: string) {
86
+ const ollamaInstance = ollama(model, {
87
+ numCtx: DEFAULT_NUM_CTX,
88
+ }) as LanguageModelV1 & { config: any };
89
+
90
+ ollamaInstance.config.baseURL = `${baseURL}/api`;
91
+
92
+ return ollamaInstance;
93
+ }
94
+
95
+ export function getDeepseekModel(apiKey: OptionalApiKey, model: string) {
96
  const openai = createOpenAI({
97
  baseURL: 'https://api.deepseek.com/beta',
98
  apiKey,
 
101
  return openai(model);
102
  }
103
 
104
+ export function getOpenRouterModel(apiKey: OptionalApiKey, model: string) {
105
  const openRouter = createOpenRouter({
106
+ apiKey,
107
  });
108
 
109
  return openRouter.chat(model);
 
112
  export function getLMStudioModel(baseURL: string, model: string) {
113
  const lmstudio = createOpenAI({
114
  baseUrl: `${baseURL}/v1`,
115
+ apiKey: '',
116
  });
117
 
118
  return lmstudio(model);
119
  }
120
 
121
+ export function getXAIModel(apiKey: OptionalApiKey, model: string) {
122
  const openai = createOpenAI({
123
  baseURL: 'https://api.x.ai/v1',
124
  apiKey,
 
126
 
127
  return openai(model);
128
  }
129
+
130
  export function getModel(provider: string, model: string, env: Env, apiKeys?: Record<string, string>) {
131
+ /*
132
+ * let apiKey; // Declare first
133
+ * let baseURL;
134
+ */
135
+
136
+ const apiKey = getAPIKey(env, provider, apiKeys); // Then assign
137
  const baseURL = getBaseURL(env, provider);
138
 
139
  switch (provider) {
 
143
  return getOpenAIModel(apiKey, model);
144
  case 'Groq':
145
  return getGroqModel(apiKey, model);
146
+ case 'HuggingFace':
147
+ return getHuggingFaceModel(apiKey, model);
148
  case 'OpenRouter':
149
  return getOpenRouterModel(apiKey, model);
150
  case 'Google':
151
  return getGoogleModel(apiKey, model);
152
  case 'OpenAILike':
153
+ return getOpenAILikeModel(baseURL, apiKey, model);
154
+ case 'Together':
155
+ return getOpenAILikeModel(baseURL, apiKey, model);
156
  case 'Deepseek':
157
  return getDeepseekModel(apiKey, model);
158
  case 'Mistral':
159
+ return getMistralModel(apiKey, model);
160
  case 'LMStudio':
161
  return getLMStudioModel(baseURL, model);
162
  case 'xAI':
163
  return getXAIModel(apiKey, model);
164
+ case 'Cohere':
165
+ return getCohereAIModel(apiKey, model);
166
  default:
167
  return getOllamaModel(baseURL, model);
168
  }
app/lib/.server/llm/prompts.ts CHANGED
@@ -88,7 +88,7 @@ You are Bolt, an expert AI assistant and exceptional senior software developer w
88
  Example:
89
 
90
  <${MODIFICATIONS_TAG_NAME}>
91
- <diff path="/home/project/src/main.js">
92
  @@ -2,7 +2,10 @@
93
  return a + b;
94
  }
@@ -103,7 +103,7 @@ You are Bolt, an expert AI assistant and exceptional senior software developer w
103
  +
104
  +console.log('The End');
105
  </diff>
106
- <file path="/home/project/package.json">
107
  // full file content here
108
  </file>
109
  </${MODIFICATIONS_TAG_NAME}>
 
88
  Example:
89
 
90
  <${MODIFICATIONS_TAG_NAME}>
91
+ <diff path="${WORK_DIR}/src/main.js">
92
  @@ -2,7 +2,10 @@
93
  return a + b;
94
  }
 
103
  +
104
  +console.log('The End');
105
  </diff>
106
+ <file path="${WORK_DIR}/package.json">
107
  // full file content here
108
  </file>
109
  </${MODIFICATIONS_TAG_NAME}>
app/lib/.server/llm/stream-text.ts CHANGED
@@ -1,10 +1,8 @@
1
- // @ts-nocheck
2
- // Preventing TS checks with files presented in the video for a better presentation.
3
- import { streamText as _streamText, convertToCoreMessages } from 'ai';
4
  import { getModel } from '~/lib/.server/llm/model';
5
  import { MAX_TOKENS } from './constants';
6
  import { getSystemPrompt } from './prompts';
7
- import { MODEL_LIST, DEFAULT_MODEL, DEFAULT_PROVIDER, MODEL_REGEX, PROVIDER_REGEX } from '~/utils/constants';
8
 
9
  interface ToolResult<Name extends string, Args, Result> {
10
  toolCallId: string;
@@ -25,32 +23,50 @@ export type Messages = Message[];
25
  export type StreamingOptions = Omit<Parameters<typeof _streamText>[0], 'model'>;
26
 
27
  function extractPropertiesFromMessage(message: Message): { model: string; provider: string; content: string } {
28
- // Extract model
29
- const modelMatch = message.content.match(MODEL_REGEX);
 
 
 
 
 
 
 
 
 
30
  const model = modelMatch ? modelMatch[1] : DEFAULT_MODEL;
31
 
32
- // Extract provider
33
- const providerMatch = message.content.match(PROVIDER_REGEX);
34
- const provider = providerMatch ? providerMatch[1] : DEFAULT_PROVIDER;
 
 
 
 
 
 
 
 
 
 
 
35
 
36
- // Remove model and provider lines from content
37
- const cleanedContent = message.content
38
- .replace(MODEL_REGEX, '')
39
- .replace(PROVIDER_REGEX, '')
40
- .trim();
41
 
42
  return { model, provider, content: cleanedContent };
43
  }
44
 
45
- export function streamText(
46
- messages: Messages,
47
- env: Env,
48
  options?: StreamingOptions,
49
- apiKeys?: Record<string, string>
50
  ) {
51
  let currentModel = DEFAULT_MODEL;
52
- let currentProvider = DEFAULT_PROVIDER;
53
-
54
  const processedMessages = messages.map((message) => {
55
  if (message.role === 'user') {
56
  const { model, provider, content } = extractPropertiesFromMessage(message);
@@ -64,14 +80,18 @@ export function streamText(
64
  return { ...message, content };
65
  }
66
 
67
- return message; // No changes for non-user messages
68
  });
69
 
 
 
 
 
70
  return _streamText({
71
- model: getModel(currentProvider, currentModel, env, apiKeys),
72
  system: getSystemPrompt(),
73
- maxTokens: MAX_TOKENS,
74
- messages: convertToCoreMessages(processedMessages),
75
  ...options,
76
  });
77
  }
 
1
+ import { convertToCoreMessages, streamText as _streamText } from 'ai';
 
 
2
  import { getModel } from '~/lib/.server/llm/model';
3
  import { MAX_TOKENS } from './constants';
4
  import { getSystemPrompt } from './prompts';
5
+ import { DEFAULT_MODEL, DEFAULT_PROVIDER, getModelList, MODEL_REGEX, PROVIDER_REGEX } from '~/utils/constants';
6
 
7
  interface ToolResult<Name extends string, Args, Result> {
8
  toolCallId: string;
 
23
  export type StreamingOptions = Omit<Parameters<typeof _streamText>[0], 'model'>;
24
 
25
  function extractPropertiesFromMessage(message: Message): { model: string; provider: string; content: string } {
26
+ const textContent = Array.isArray(message.content)
27
+ ? message.content.find((item) => item.type === 'text')?.text || ''
28
+ : message.content;
29
+
30
+ const modelMatch = textContent.match(MODEL_REGEX);
31
+ const providerMatch = textContent.match(PROVIDER_REGEX);
32
+
33
+ /*
34
+ * Extract model
35
+ * const modelMatch = message.content.match(MODEL_REGEX);
36
+ */
37
  const model = modelMatch ? modelMatch[1] : DEFAULT_MODEL;
38
 
39
+ /*
40
+ * Extract provider
41
+ * const providerMatch = message.content.match(PROVIDER_REGEX);
42
+ */
43
+ const provider = providerMatch ? providerMatch[1] : DEFAULT_PROVIDER.name;
44
+
45
+ const cleanedContent = Array.isArray(message.content)
46
+ ? message.content.map((item) => {
47
+ if (item.type === 'text') {
48
+ return {
49
+ type: 'text',
50
+ text: item.text?.replace(MODEL_REGEX, '').replace(PROVIDER_REGEX, ''),
51
+ };
52
+ }
53
 
54
+ return item; // Preserve image_url and other types as is
55
+ })
56
+ : textContent.replace(MODEL_REGEX, '').replace(PROVIDER_REGEX, '');
 
 
57
 
58
  return { model, provider, content: cleanedContent };
59
  }
60
 
61
+ export async function streamText(
62
+ messages: Messages,
63
+ env: Env,
64
  options?: StreamingOptions,
65
+ apiKeys?: Record<string, string>,
66
  ) {
67
  let currentModel = DEFAULT_MODEL;
68
+ let currentProvider = DEFAULT_PROVIDER.name;
69
+ const MODEL_LIST = await getModelList(apiKeys || {});
70
  const processedMessages = messages.map((message) => {
71
  if (message.role === 'user') {
72
  const { model, provider, content } = extractPropertiesFromMessage(message);
 
80
  return { ...message, content };
81
  }
82
 
83
+ return message;
84
  });
85
 
86
+ const modelDetails = MODEL_LIST.find((m) => m.name === currentModel);
87
+
88
+ const dynamicMaxTokens = modelDetails && modelDetails.maxTokenAllowed ? modelDetails.maxTokenAllowed : MAX_TOKENS;
89
+
90
  return _streamText({
91
+ model: getModel(currentProvider, currentModel, env, apiKeys) as any,
92
  system: getSystemPrompt(),
93
+ maxTokens: dynamicMaxTokens,
94
+ messages: convertToCoreMessages(processedMessages as any),
95
  ...options,
96
  });
97
  }
app/lib/hooks/index.ts CHANGED
@@ -2,3 +2,5 @@ export * from './useMessageParser';
2
  export * from './usePromptEnhancer';
3
  export * from './useShortcuts';
4
  export * from './useSnapScroll';
 
 
 
2
  export * from './usePromptEnhancer';
3
  export * from './useShortcuts';
4
  export * from './useSnapScroll';
5
+ export * from './useEditChatDescription';
6
+ export { default } from './useViewport';
app/lib/hooks/useEditChatDescription.ts ADDED
@@ -0,0 +1,163 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { useStore } from '@nanostores/react';
2
+ import { useCallback, useEffect, useState } from 'react';
3
+ import { toast } from 'react-toastify';
4
+ import {
5
+ chatId as chatIdStore,
6
+ description as descriptionStore,
7
+ db,
8
+ updateChatDescription,
9
+ getMessages,
10
+ } from '~/lib/persistence';
11
+
12
+ interface EditChatDescriptionOptions {
13
+ initialDescription?: string;
14
+ customChatId?: string;
15
+ syncWithGlobalStore?: boolean;
16
+ }
17
+
18
+ type EditChatDescriptionHook = {
19
+ editing: boolean;
20
+ handleChange: (e: React.ChangeEvent<HTMLInputElement>) => void;
21
+ handleBlur: () => Promise<void>;
22
+ handleSubmit: (event: React.FormEvent) => Promise<void>;
23
+ handleKeyDown: (event: React.KeyboardEvent<HTMLInputElement>) => Promise<void>;
24
+ currentDescription: string;
25
+ toggleEditMode: () => void;
26
+ };
27
+
28
+ /**
29
+ * Hook to manage the state and behavior for editing chat descriptions.
30
+ *
31
+ * Offers functions to:
32
+ * - Switch between edit and view modes.
33
+ * - Manage input changes, blur, and form submission events.
34
+ * - Save updates to IndexedDB and optionally to the global application state.
35
+ *
36
+ * @param {Object} options
37
+ * @param {string} options.initialDescription - The current chat description.
38
+ * @param {string} options.customChatId - Optional ID for updating the description via the sidebar.
39
+ * @param {boolean} options.syncWithGlobalStore - Flag to indicate global description store synchronization.
40
+ * @returns {EditChatDescriptionHook} Methods and state for managing description edits.
41
+ */
42
+ export function useEditChatDescription({
43
+ initialDescription = descriptionStore.get()!,
44
+ customChatId,
45
+ syncWithGlobalStore,
46
+ }: EditChatDescriptionOptions): EditChatDescriptionHook {
47
+ const chatIdFromStore = useStore(chatIdStore);
48
+ const [editing, setEditing] = useState(false);
49
+ const [currentDescription, setCurrentDescription] = useState(initialDescription);
50
+
51
+ const [chatId, setChatId] = useState<string>();
52
+
53
+ useEffect(() => {
54
+ setChatId(customChatId || chatIdFromStore);
55
+ }, [customChatId, chatIdFromStore]);
56
+ useEffect(() => {
57
+ setCurrentDescription(initialDescription);
58
+ }, [initialDescription]);
59
+
60
+ const toggleEditMode = useCallback(() => setEditing((prev) => !prev), []);
61
+
62
+ const handleChange = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
63
+ setCurrentDescription(e.target.value);
64
+ }, []);
65
+
66
+ const fetchLatestDescription = useCallback(async () => {
67
+ if (!db || !chatId) {
68
+ return initialDescription;
69
+ }
70
+
71
+ try {
72
+ const chat = await getMessages(db, chatId);
73
+ return chat?.description || initialDescription;
74
+ } catch (error) {
75
+ console.error('Failed to fetch latest description:', error);
76
+ return initialDescription;
77
+ }
78
+ }, [db, chatId, initialDescription]);
79
+
80
+ const handleBlur = useCallback(async () => {
81
+ const latestDescription = await fetchLatestDescription();
82
+ setCurrentDescription(latestDescription);
83
+ toggleEditMode();
84
+ }, [fetchLatestDescription, toggleEditMode]);
85
+
86
+ const isValidDescription = useCallback((desc: string): boolean => {
87
+ const trimmedDesc = desc.trim();
88
+
89
+ if (trimmedDesc === initialDescription) {
90
+ toggleEditMode();
91
+ return false; // No change, skip validation
92
+ }
93
+
94
+ const lengthValid = trimmedDesc.length > 0 && trimmedDesc.length <= 100;
95
+ const characterValid = /^[a-zA-Z0-9\s]+$/.test(trimmedDesc);
96
+
97
+ if (!lengthValid) {
98
+ toast.error('Description must be between 1 and 100 characters.');
99
+ return false;
100
+ }
101
+
102
+ if (!characterValid) {
103
+ toast.error('Description can only contain alphanumeric characters and spaces.');
104
+ return false;
105
+ }
106
+
107
+ return true;
108
+ }, []);
109
+
110
+ const handleSubmit = useCallback(
111
+ async (event: React.FormEvent) => {
112
+ event.preventDefault();
113
+
114
+ if (!isValidDescription(currentDescription)) {
115
+ return;
116
+ }
117
+
118
+ try {
119
+ if (!db) {
120
+ toast.error('Chat persistence is not available');
121
+ return;
122
+ }
123
+
124
+ if (!chatId) {
125
+ toast.error('Chat Id is not available');
126
+ return;
127
+ }
128
+
129
+ await updateChatDescription(db, chatId, currentDescription);
130
+
131
+ if (syncWithGlobalStore) {
132
+ descriptionStore.set(currentDescription);
133
+ }
134
+
135
+ toast.success('Chat description updated successfully');
136
+ } catch (error) {
137
+ toast.error('Failed to update chat description: ' + (error as Error).message);
138
+ }
139
+
140
+ toggleEditMode();
141
+ },
142
+ [currentDescription, db, chatId, initialDescription, customChatId],
143
+ );
144
+
145
+ const handleKeyDown = useCallback(
146
+ async (e: React.KeyboardEvent<HTMLInputElement>) => {
147
+ if (e.key === 'Escape') {
148
+ await handleBlur();
149
+ }
150
+ },
151
+ [handleBlur],
152
+ );
153
+
154
+ return {
155
+ editing,
156
+ handleChange,
157
+ handleBlur,
158
+ handleSubmit,
159
+ handleKeyDown,
160
+ currentDescription,
161
+ toggleEditMode,
162
+ };
163
+ }
app/lib/hooks/usePromptEnhancer.ts CHANGED
@@ -1,4 +1,5 @@
1
  import { useState } from 'react';
 
2
  import { createScopedLogger } from '~/utils/logger';
3
 
4
  const logger = createScopedLogger('usePromptEnhancement');
@@ -13,54 +14,54 @@ export function usePromptEnhancer() {
13
  };
14
 
15
  const enhancePrompt = async (
16
- input: string,
17
  setInput: (value: string) => void,
18
  model: string,
19
- provider: string,
20
- apiKeys?: Record<string, string>
21
  ) => {
22
  setEnhancingPrompt(true);
23
  setPromptEnhanced(false);
24
-
25
  const requestBody: any = {
26
  message: input,
27
  model,
28
  provider,
29
  };
30
-
31
  if (apiKeys) {
32
  requestBody.apiKeys = apiKeys;
33
  }
34
-
35
  const response = await fetch('/api/enhancer', {
36
  method: 'POST',
37
  body: JSON.stringify(requestBody),
38
  });
39
-
40
  const reader = response.body?.getReader();
41
-
42
  const originalInput = input;
43
-
44
  if (reader) {
45
  const decoder = new TextDecoder();
46
-
47
  let _input = '';
48
  let _error;
49
-
50
  try {
51
  setInput('');
52
-
53
  while (true) {
54
  const { value, done } = await reader.read();
55
-
56
  if (done) {
57
  break;
58
  }
59
-
60
  _input += decoder.decode(value);
61
-
62
  logger.trace('Set input', _input);
63
-
64
  setInput(_input);
65
  }
66
  } catch (error) {
@@ -70,10 +71,10 @@ export function usePromptEnhancer() {
70
  if (_error) {
71
  logger.error(_error);
72
  }
73
-
74
  setEnhancingPrompt(false);
75
  setPromptEnhanced(true);
76
-
77
  setTimeout(() => {
78
  setInput(_input);
79
  });
 
1
  import { useState } from 'react';
2
+ import type { ProviderInfo } from '~/types/model';
3
  import { createScopedLogger } from '~/utils/logger';
4
 
5
  const logger = createScopedLogger('usePromptEnhancement');
 
14
  };
15
 
16
  const enhancePrompt = async (
17
+ input: string,
18
  setInput: (value: string) => void,
19
  model: string,
20
+ provider: ProviderInfo,
21
+ apiKeys?: Record<string, string>,
22
  ) => {
23
  setEnhancingPrompt(true);
24
  setPromptEnhanced(false);
25
+
26
  const requestBody: any = {
27
  message: input,
28
  model,
29
  provider,
30
  };
31
+
32
  if (apiKeys) {
33
  requestBody.apiKeys = apiKeys;
34
  }
35
+
36
  const response = await fetch('/api/enhancer', {
37
  method: 'POST',
38
  body: JSON.stringify(requestBody),
39
  });
40
+
41
  const reader = response.body?.getReader();
42
+
43
  const originalInput = input;
44
+
45
  if (reader) {
46
  const decoder = new TextDecoder();
47
+
48
  let _input = '';
49
  let _error;
50
+
51
  try {
52
  setInput('');
53
+
54
  while (true) {
55
  const { value, done } = await reader.read();
56
+
57
  if (done) {
58
  break;
59
  }
60
+
61
  _input += decoder.decode(value);
62
+
63
  logger.trace('Set input', _input);
64
+
65
  setInput(_input);
66
  }
67
  } catch (error) {
 
71
  if (_error) {
72
  logger.error(_error);
73
  }
74
+
75
  setEnhancingPrompt(false);
76
  setPromptEnhanced(true);
77
+
78
  setTimeout(() => {
79
  setInput(_input);
80
  });
app/lib/hooks/useSearchFilter.ts ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { useState, useMemo, useCallback } from 'react';
2
+ import { debounce } from '~/utils/debounce';
3
+ import type { ChatHistoryItem } from '~/lib/persistence';
4
+
5
+ interface UseSearchFilterOptions {
6
+ items: ChatHistoryItem[];
7
+ searchFields?: (keyof ChatHistoryItem)[];
8
+ debounceMs?: number;
9
+ }
10
+
11
+ export function useSearchFilter({
12
+ items = [],
13
+ searchFields = ['description'],
14
+ debounceMs = 300,
15
+ }: UseSearchFilterOptions) {
16
+ const [searchQuery, setSearchQuery] = useState('');
17
+
18
+ const debouncedSetSearch = useCallback(debounce(setSearchQuery, debounceMs), []);
19
+
20
+ const handleSearchChange = useCallback(
21
+ (event: React.ChangeEvent<HTMLInputElement>) => {
22
+ debouncedSetSearch(event.target.value);
23
+ },
24
+ [debouncedSetSearch],
25
+ );
26
+
27
+ const filteredItems = useMemo(() => {
28
+ if (!searchQuery.trim()) {
29
+ return items;
30
+ }
31
+
32
+ const query = searchQuery.toLowerCase();
33
+
34
+ return items.filter((item) =>
35
+ searchFields.some((field) => {
36
+ const value = item[field];
37
+
38
+ if (typeof value === 'string') {
39
+ return value.toLowerCase().includes(query);
40
+ }
41
+
42
+ return false;
43
+ }),
44
+ );
45
+ }, [items, searchQuery, searchFields]);
46
+
47
+ return {
48
+ searchQuery,
49
+ filteredItems,
50
+ handleSearchChange,
51
+ };
52
+ }
app/lib/hooks/useViewport.ts ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { useState, useEffect } from 'react';
2
+
3
+ const useViewport = (threshold = 1024) => {
4
+ const [isSmallViewport, setIsSmallViewport] = useState(window.innerWidth < threshold);
5
+
6
+ useEffect(() => {
7
+ const handleResize = () => setIsSmallViewport(window.innerWidth < threshold);
8
+ window.addEventListener('resize', handleResize);
9
+
10
+ return () => {
11
+ window.removeEventListener('resize', handleResize);
12
+ };
13
+ }, [threshold]);
14
+
15
+ return isSmallViewport;
16
+ };
17
+
18
+ export default useViewport;
app/lib/persistence/ChatDescription.client.tsx CHANGED
@@ -1,6 +1,68 @@
1
  import { useStore } from '@nanostores/react';
2
- import { description } from './useChatHistory';
 
 
 
3
 
4
  export function ChatDescription() {
5
- return useStore(description);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6
  }
 
1
  import { useStore } from '@nanostores/react';
2
+ import { TooltipProvider } from '@radix-ui/react-tooltip';
3
+ import WithTooltip from '~/components/ui/Tooltip';
4
+ import { useEditChatDescription } from '~/lib/hooks';
5
+ import { description as descriptionStore } from '~/lib/persistence';
6
 
7
  export function ChatDescription() {
8
+ const initialDescription = useStore(descriptionStore)!;
9
+
10
+ const { editing, handleChange, handleBlur, handleSubmit, handleKeyDown, currentDescription, toggleEditMode } =
11
+ useEditChatDescription({
12
+ initialDescription,
13
+ syncWithGlobalStore: true,
14
+ });
15
+
16
+ if (!initialDescription) {
17
+ // doing this to prevent showing edit button until chat description is set
18
+ return null;
19
+ }
20
+
21
+ return (
22
+ <div className="flex items-center justify-center">
23
+ {editing ? (
24
+ <form onSubmit={handleSubmit} className="flex items-center justify-center">
25
+ <input
26
+ type="text"
27
+ className="bg-bolt-elements-background-depth-1 text-bolt-elements-textPrimary rounded px-2 mr-2 w-fit"
28
+ autoFocus
29
+ value={currentDescription}
30
+ onChange={handleChange}
31
+ onBlur={handleBlur}
32
+ onKeyDown={handleKeyDown}
33
+ style={{ width: `${Math.max(currentDescription.length * 8, 100)}px` }}
34
+ />
35
+ <TooltipProvider>
36
+ <WithTooltip tooltip="Save title">
37
+ <div className="flex justify-between items-center p-2 rounded-md bg-bolt-elements-item-backgroundAccent">
38
+ <button
39
+ type="submit"
40
+ className="i-ph:check-bold scale-110 hover:text-bolt-elements-item-contentAccent"
41
+ onMouseDown={handleSubmit}
42
+ />
43
+ </div>
44
+ </WithTooltip>
45
+ </TooltipProvider>
46
+ </form>
47
+ ) : (
48
+ <>
49
+ {currentDescription}
50
+ <TooltipProvider>
51
+ <WithTooltip tooltip="Rename chat">
52
+ <div className="flex justify-between items-center p-2 rounded-md bg-bolt-elements-item-backgroundAccent ml-2">
53
+ <button
54
+ type="button"
55
+ className="i-ph:pencil-fill scale-110 hover:text-bolt-elements-item-contentAccent"
56
+ onClick={(event) => {
57
+ event.preventDefault();
58
+ toggleEditMode();
59
+ }}
60
+ />
61
+ </div>
62
+ </WithTooltip>
63
+ </TooltipProvider>
64
+ </>
65
+ )}
66
+ </div>
67
+ );
68
  }