355 Commits

Author SHA1 Message Date
github-actions[bot]
1cf83454ed chore: release version 0.0.4 2024-12-31 17:17:50 +00:00
Anirban Kar
6494f5ac2e fix: updated logger and model caching minor bugfix #release (#895)
* fix: updated logger and model caching

* usage token stream issue fix

* minor changes

* updated starter template change to fix the app title

* starter template bigfix

* fixed hydretion errors and raw logs

* removed raw log

* made auto select template false by default

* more cleaner logs and updated logic to call dynamicModels only if not found in static models

* updated starter template instructions

* browser console log improved for firefox

* provider icons fix icons
2024-12-31 22:47:32 +05:30
Anirban Kar
389eedcac4 fix: better model loading ui feedback and model list update (#954)
* fix: better model loading feedback and model list update

* added load on providersettings  update
2024-12-31 19:22:46 +05:30
Eduard Ruzga
55cfd5d4ee fix: refresh model list after api key changes (#944) 2024-12-30 23:35:08 +05:30
Arsalaan Ahmed
e00264236e feat: added hyperbolic llm models (#943)
* Added Hyperbolic Models

* Fix: Fixed problem in connecting with hyperbolic models

* added dynamic models for hyperbolic

* removed logs
2024-12-30 23:26:33 +05:30
Eduard Ruzga
93c2a6e81d Merge pull request #939 from juanmcampos/fix-project-import-button
fix: import folder filtering
2024-12-30 19:39:27 +02:00
Eduard Ruzga
4c81cb02e1 fix: add defaults for LMStudio to work out of the box (#928) 2024-12-30 17:50:13 +05:30
Juan Manuel Campos Olvera
6e3b5dcbd7 fix: import folder filtering 2024-12-29 20:21:49 -06:00
Anirban Kar
4c81e154a0 feat: added Automatic Code Template Detection And Import (#867)
* initial setup

* updated template list

* added optional switch to control this feature

* removed some logs
2024-12-29 15:52:37 +05:30
Anirban Kar
3a36a4469a feat: redact file contents from chat and put latest files into system prompt (#904) 2024-12-29 15:36:31 +05:30
Eduard Ruzga
aecd9b1b40 fix: detect and remove markdown block syntax that llms sometimes hallucinate for file actions (#886)
* Clean out markdown syntax

* Remove identation removal

* Improve for streaming
2024-12-29 15:23:20 +05:30
Anirban Kar
4844db82fa ci: improved change-log generation script and cleaner release ci action (#896)
* build: improved-changelog

* added a better change log script

* improved changelog script

* improved change log script
2024-12-26 00:58:42 +05:30
Eduard Ruzga
7eee0386ff feat: catch errors from web container preview and show in actionable alert so user can send them to AI for fixing (#856)
* Catch errors from web container

* Show fix error popup on errors in preview

* Remove unneeded action type

* PR comments

* Cleanup urls in stacktrace

---------

Co-authored-by: Anirban Kar <thecodacus@gmail.com>
2024-12-25 03:05:44 +05:30
Anirban Kar
fc4f89f806 feat: add Starter template menu in homepage (#884)
* added icons and component

* updated unocss to add dynamic icons

* removed temp logs

* updated readme
2024-12-24 22:37:28 +05:30
Anirban Kar
8185fd56ca fix: check for updates does not look for commit.json now (#861) 2024-12-24 13:34:46 +05:30
Alex Parker
d673206952 docs: updated env.example of OLLAMA & LMSTUDIO base url (#877)
* correct OLLAMA_API_BASE_URL

* correct OLLAMA_API_BASE_URL

* correct OLLAMA_API_BASE_URL
2024-12-24 13:32:04 +05:30
Eduard Ruzga
79e7e75228 Merge pull request #797 from thecodacus/terminal-error-detection
feat: enhanced Terminal Error Handling and Alert System
2024-12-23 14:25:39 +02:00
Dustin Loring
1f938fca40 feat; data tab added to the settings
added a data tab to the settings
removed chat history
2024-12-22 06:20:14 -05:00
Anirban Kar
8b58c7a0fb fix: ollama provider module base url hotfix for docker (#863)
* fix: ollama base url hotfix

* cleanup logic
2024-12-22 01:25:48 +05:30
Anirban Kar
13b208df46 better osc code cleanup 2024-12-22 01:01:06 +05:30
Anirban Kar
d8943f9474 fix: provider menu dropdown fix (ghost providers) (#862) 2024-12-21 23:31:19 +05:30
Anirban Kar
47471e05d9 updated read me 2024-12-21 18:22:17 +05:30
Anirban Kar
28f0c3629d ignored alert on project reload 2024-12-21 17:44:18 +05:30
Anirban Kar
975e7d83fd Merge branch 'main' into terminal-error-detection 2024-12-21 16:14:46 +05:30
Anirban Kar
7295352a98 refactor: refactored LLM Providers: Adapting Modular Approach (#832)
* refactor: Refactoring Providers to have providers as modules

* updated package and lock file

* added grok model back

* updated registry system
2024-12-21 11:45:17 +05:30
Anirban Kar
63abf52000 fix hotfix for version metadata issue (#853) 2024-12-21 02:24:57 +05:30
Anirban Kar
df6925ac07 fix: add Message Processing Throttling to Prevent Browser Crashes (#848) 2024-12-21 02:13:29 +05:30
Anirban Kar
80d9800aa0 docs: updated download link (#850) 2024-12-21 01:52:45 +05:30
Anirban Kar
dbd24142ae ci: updated the docs ci to only trigger if any files changed in the docs folder (#849) 2024-12-21 01:09:44 +05:30
Cole Medin
7afd654210 Merge pull request #845 from dustinwloring1988/docs/updated-docs
docs: updated Docs
2024-12-20 13:37:16 -06:00
Anirban Kar
d8a277f0ac refactor: updated vite config to inject add version metadata into the app on build (#841)
* refactor: removes commit.json and used vite.config to load these variables

* updated precommit hook

* updated the pre start script

* updated the workflows
2024-12-21 01:03:28 +05:30
Dustin Loring
6145c603a1 Merge branch 'main' into docs/updated-docs 2024-12-20 14:21:50 -05:00
github-actions[bot]
56edbc4699 chore: update commit hash to ab5cde30a1 2024-12-20 19:17:25 +00:00
Dustin Loring
ab5cde30a1 docs: setup updated
docs: updated setup guide to have more detailed instructions
2024-12-20 14:17:12 -05:00
Dustin Loring
f2662c1c71 Merge branch 'main' into docs-setup-updated 2024-12-20 14:15:46 -05:00
Dustin Loring
ed5bad36ba docs: added info on both ways to set api keys 2024-12-20 10:02:06 -05:00
Dustin Loring
0c07bc9105 docs: added info on the Releases Page
Added the option to download from the Releases Page instead of git clone in the README
2024-12-20 09:50:47 -05:00
Dustin Loring
58db67683e docs: added info on updating using docker
Added docker-compose --profile development up --build  to the update section
2024-12-20 09:42:54 -05:00
Dustin Loring
7e70dc5d8e docs: updated Contributing
updated Contributing in the docs
updated Contributing and FAQ in the GitHub part as well
2024-12-20 09:37:34 -05:00
github-actions[bot]
2638c1a704 chore: update commit hash to 636f87f568 2024-12-19 20:17:35 +00:00
Dustin Loring
636f87f568 docs: faq style change, toc added to index
docs: updated style in FAQ
added: TOC to the index page
2024-12-19 15:17:21 -05:00
Dustin Loring
0733813af8 docs: updated style in faq
updated style in FAQ docs to be an accordion like style
added a TOC to the index page in the docs
2024-12-19 15:12:21 -05:00
github-actions[bot]
01599caf38 chore: update commit hash to 75ec49beb8 2024-12-19 18:08:12 +00:00
Dustin Loring
75ec49beb8 feat: providers list is now 2 columns
The providers list in the settings modal is now 2 columns allowing you to see more at once.
2024-12-19 13:07:58 -05:00
Dustin Loring
bbd9a17d3b Update ProvidersTab.tsx 2024-12-19 13:04:26 -05:00
Dustin Loring
a7551ecfcc Update ProvidersTab.tsx 2024-12-19 12:57:59 -05:00
Dustin Loring
db769e0c90 Merge branch 'main' into feat/improved-providers-list 2024-12-19 12:43:51 -05:00
github-actions[bot]
d4400a5704 chore: update commit hash to a53b10ff39 2024-12-19 15:53:04 +00:00
Anirban Kar
a53b10ff39 Merge pull request #800 from gokulkgm/xai-update
feat: add xAI grok-2-1212 model
2024-12-19 21:22:52 +05:30
github-actions[bot]
7e344aaa5c chore: update commit hash to 381d490f1f 2024-12-19 12:33:56 +00:00
Anirban Kar
381d490f1f Merge pull request #714 from kris1803/fix/described_by
fix: fixed console error for SettingsWIndow & Removed ts-nocheck
2024-12-19 18:03:46 +05:30
Anirban Kar
3e2fc32a46 Merge branch 'main' into fix/described_by 2024-12-19 18:02:43 +05:30
github-actions[bot]
1d716c0925 chore: update commit hash to de64007697 2024-12-19 11:25:23 +00:00
Dustin Loring
de64007697 docs: toc for readme
docs: added a TOC for the README
2024-12-19 06:25:11 -05:00
github-actions[bot]
906cc38e79 chore: update commit hash to 95dbcf1eb7 2024-12-19 09:20:48 +00:00
Anirban Kar
95dbcf1eb7 Merge pull request #789 from thecodacus/bolt-shell-race-condition
fix: added wait till terminal prompt for bolt shell execution
2024-12-19 14:50:37 +05:30
Anirban Kar
69c58c1410 Merge branch 'main' into bolt-shell-race-condition 2024-12-19 14:50:24 +05:30
Anirban Kar
602f65a4dc updated some text 2024-12-18 23:41:59 +05:30
Anirban Kar
1398344c11 docs: updated setup guide to have more detailed instructions 2024-12-18 23:34:41 +05:30
github-actions[bot]
296e5d9f77 chore: update commit hash to 50e6778784 2024-12-18 16:28:44 +00:00
Anirban Kar
50e6778784 Merge pull request #816 from thecodacus/env-file-fix
fix: fixed model not loading/working, even after baseUrl set in .env file
2024-12-18 21:58:32 +05:30
Anirban Kar
3fba4f0b61 Merge branch 'main' into env-file-fix 2024-12-18 21:57:02 +05:30
Anirban Kar
b892d708ec removed logs and openAI fix 2024-12-18 21:55:17 +05:30
Anirban Kar
d37c3736d5 removed logs 2024-12-18 21:34:18 +05:30
Anirban Kar
6975083fb9 stopped apikeys set to envfile being exposed to UI 2024-12-18 21:31:50 +05:30
Anirban Kar
620d13ad8a updated title header 2024-12-18 21:29:54 +05:30
Anirban Kar
b25b8b98f9 updated styling wordings and animations icons 2024-12-18 21:09:36 +05:30
github-actions[bot]
90c9c9c760 chore: update commit hash to 6458211bed 2024-12-18 15:12:36 +00:00
Cole Medin
6458211bed Merge pull request #822 from stackblitz-labs/documentation-enhancements
chore: a few documentation enhancements for main README and FAQs
2024-12-18 09:12:24 -06:00
Anirban Kar
3d8abee511 Merge branch 'main' into terminal-error-detection 2024-12-18 20:19:59 +05:30
Anirban Kar
26a3bcf9b6 Merge branch 'env-file-fix-old' into env-file-fix 2024-12-18 20:06:29 +05:30
Anirban Kar
283eb22ae5 added indicator on settings menu 2024-12-18 20:04:43 +05:30
Dustin Loring
7458b22780 fixed API Key import 2024-12-18 09:06:58 -05:00
Cole Medin
b3b4d74824 chore: a few documentation enhancements for main README and FAQs 2024-12-18 07:01:58 -06:00
github-actions[bot]
a1e902fe79 chore: update commit hash to a9309161e9 2024-12-18 12:31:51 +00:00
Cole Medin
a9309161e9 Merge pull request #817 from dustinwloring1988/docs/more-beginner-friendly
docs: simplified setup
2024-12-18 06:31:33 -06:00
Dustin Loring
278bd242b1 docs: simplified setup
Removed the section about environment variables. In docker removed the production build. Both of these can still be found in the docs.
2024-12-18 06:35:33 -05:00
Anirban Kar
e74d6cafb5 Merge branch 'main' into env-file-fix 2024-12-18 16:41:49 +05:30
Anirban Kar
62ebfe51a6 fix: .env file baseUrl Issue 2024-12-18 16:34:18 +05:30
Dustin Loring
ba4e78809c feat: improved providers list style
made the list 2 columns wide and separate out the experimental providers
2024-12-17 17:40:16 -05:00
github-actions[bot]
6003c165ef chore: update commit hash to e064803955 2024-12-17 22:12:17 +00:00
Dustin Loring
e064803955 fix: chat title character restriction
added: characters to valid list for chat title
2024-12-17 17:12:01 -05:00
Dustin Loring
1a0ede6774 Update DataTab.tsx 2024-12-17 16:57:16 -05:00
Dustin Loring
a9b15e56c9 feat: Data Tab
Removed Chat History Tab
Added Data Tab
Data tab can export and delete chat history, import API keys, import and export settings
2024-12-17 16:44:56 -05:00
Anirban Kar
fd193ee7d7 Merge branch 'main' into terminal-error-detection 2024-12-18 02:36:38 +05:30
github-actions[bot]
fce8999f27 chore: release version 0.0.3 2024-12-17 21:00:04 +00:00
Anirban Kar
eb6d435356 Merge pull request #784 from dustinwloring1988/fix/prompt-enhance #release
fix: prompt enhance patch
2024-12-18 02:29:45 +05:30
Anirban Kar
d51b0dcadf Merge branch 'main' into fix/prompt-enhance 2024-12-18 02:28:46 +05:30
Anirban Kar
18d04ca065 simplified the fix 2024-12-18 02:20:14 +05:30
GK
8d0f0da04a add: xAI grok-2-1212 model 2024-12-17 17:31:10 +00:00
Anirban Kar
d327cfea29 feat: added terminal error capturing and automated fix prompt 2024-12-17 21:19:43 +05:30
Dustin Loring
0e7937b835 Update README.md 2024-12-17 10:27:04 -05:00
github-actions[bot]
a2330084eb chore: update commit hash to 282beb96e2 2024-12-17 15:25:41 +00:00
Dustin Loring
282beb96e2 docs: miniflare error knowledge
added miniflare and wrangler error on Windows FAQ to the docs
2024-12-17 10:25:30 -05:00
Dustin Loring
206a6d7816 add/toc-for-readme
added a TOC for the README file, renamed some headings to better suite the TOC
2024-12-17 10:19:40 -05:00
Dustin Loring
defe73367e add: miniflare and wrangler error
added information to FAQ in docs
2024-12-17 07:56:25 -05:00
Anirban Kar
42bde1cae4 Merge branch 'main' into terminal-error-detection 2024-12-17 16:52:51 +05:30
Anirban Kar
e9e7857675 removed logs 2024-12-17 15:01:00 +05:30
Anirban Kar
69c0bf5873 fix: added wait till terminal prompt for bolt shell execution 2024-12-17 14:57:16 +05:30
Dustin Loring
2d57bd2746 add: charactors to the vaild list for chat titles
added common punctuation to the charactersValid
2024-12-16 18:55:38 -05:00
Dustin Loring
05146c18d6 fix: Prompt Enhance
Prompt Enhance option stopped, this fixes it
2024-12-16 18:40:04 -05:00
github-actions[bot]
0ee3736297 chore: update commit hash to 1e72d52278 2024-12-16 22:04:55 +00:00
Anirban Kar
1e72d52278 Merge pull request #781 from thecodacus/semantic-pull-pr
chore: Reintroducing semantic pull pr validation
2024-12-17 03:34:42 +05:30
Anirban Kar
35f5aaaa76 chore: adding back semantic pull pr check for better changelog system 2024-12-17 03:32:08 +05:30
Anirban Kar
d238c9353c Merge remote-tracking branch 'upstream/main' 2024-12-17 03:30:54 +05:30
github-actions[bot]
7e44cb8ff7 chore: release version 0.0.2 2024-12-16 21:50:26 +00:00
Anirban Kar
89eac1ba8b Merge pull request #776 from thecodacus/bugfix-for-stable #release
release: Bugfix for stable
2024-12-17 03:20:08 +05:30
Anirban Kar
5567d6deac Merge branch 'main' into bugfix-for-stable 2024-12-17 02:44:16 +05:30
Anirban Kar
f511a273de Merge remote-tracking branch 'upstream/main' 2024-12-17 02:43:00 +05:30
github-actions[bot]
e61459eb9e chore: update commit hash to c257129a61 2024-12-16 21:11:16 +00:00
Anirban Kar
c257129a61 Merge pull request #757 from dustinwloring1988/feat/enhanced-github-connection
feat: Improved GitHub connection
2024-12-17 02:41:04 +05:30
Anirban Kar
016488998d Merge branch 'main' into bugfix-for-stable 2024-12-17 01:03:18 +05:30
Anirban Kar
e4866eb75e Merge remote-tracking branch 'upstream/main' 2024-12-17 00:56:39 +05:30
github-actions[bot]
0b47365846 chore: update commit hash to 25b80ab267 2024-12-16 19:15:32 +00:00
Anirban Kar
25b80ab267 Merge pull request #774 from D-Byte/copyMyFix
ui: Fixed theming of Copy Code button
2024-12-17 00:45:15 +05:30
Anirban Kar
ad19d3f8f4 Merge branch 'main' into copyMyFix 2024-12-17 00:44:42 +05:30
github-actions[bot]
7a0223d21a chore: update commit hash to 0a4ef117ae 2024-12-16 18:46:41 +00:00
Anirban Kar
0a4ef117ae Merge pull request #597 from thecodacus/add-loading-on-git-import-from-url
feat:Added backdrop and loading screen in Git clone from Url
2024-12-17 00:16:29 +05:30
Anirban Kar
bf7e500452 Merge branch 'main' into add-loading-on-git-import-from-url 2024-12-17 00:15:18 +05:30
Anirban Kar
bf76a0b2e7 added UI fix for loading screen 2024-12-17 00:14:42 +05:30
Anirban Kar
7e650af569 Merge branch 'main' into add-loading-on-git-import-from-url 2024-12-17 00:10:45 +05:30
github-actions[bot]
0a2e0f2f3a chore: update commit hash to 43e1f436f5 2024-12-16 18:38:04 +00:00
Anirban Kar
43e1f436f5 Merge pull request #669 from thecodacus/prompt-url-params
feat(url-prompt) added prompt url params
2024-12-17 00:07:53 +05:30
Anirban Kar
208830151e Merge branch 'main' into prompt-url-params 2024-12-17 00:06:22 +05:30
Anirban Kar
8110c69eda Merge branch 'minor-bugfix' into bugfix-for-stable 2024-12-16 23:57:05 +05:30
Anirban Kar
356715ccd7 minor bugfix 2024-12-16 23:55:51 +05:30
Anirban Kar
25e6bb3e84 Merge remote-tracking branch 'upstream/main' 2024-12-16 22:56:19 +05:30
Arne Durr
329152f56d Merge branch 'main' into copyMyFix 2024-12-16 18:25:08 +01:00
Arne Durr
5f144e6994 Fixed theming of Copy Code button 2024-12-16 18:21:30 +01:00
github-actions[bot]
92476dd2d7 chore: update commit hash to 49b02dd885 2024-12-16 16:55:53 +00:00
Anirban Kar
49b02dd885 Merge pull request #773 from thecodacus/workflowfix
chore: Workflow fix
2024-12-16 22:25:44 +05:30
Anirban Kar
e601da9612 updated workflow for commit and stable release 2024-12-16 22:04:33 +05:30
Anirban Kar
47a1def877 Merge remote-tracking branch 'upstream/main' 2024-12-16 22:00:28 +05:30
Anirban Kar
99cbde505d Merge branch 'main' into terminal-error-detection 2024-12-16 21:59:36 +05:30
github-actions[bot]
00d871bace chore: update commit hash to de2cb43d17 2024-12-16 16:18:25 +00:00
Anirban Kar
de2cb43d17 Merge pull request #744 from thecodacus/system-prompt-variations
feat(experimental): Add Configurable System Prompts Feature
2024-12-16 21:48:12 +05:30
Anirban Kar
d473b2b713 Merge branch 'main' into system-prompt-variations-local 2024-12-16 21:44:47 +05:30
Anirban Kar
7158ad6237 Merge remote-tracking branch 'upstream/main' 2024-12-16 21:43:19 +05:30
github-actions[bot]
412f290e81 chore: update commit hash to eb1d5417e7 2024-12-16 16:12:13 +00:00
Anirban Kar
eb1d5417e7 Merge pull request #772 from thecodacus/commit-workflow-fix
chore: Commit workflow fix
2024-12-16 21:42:00 +05:30
Anirban Kar
647d2dc0cb commit workflow fix 2024-12-16 21:40:57 +05:30
Anirban Kar
f15dbd2a4e Merge remote-tracking branch 'upstream/main' 2024-12-16 21:37:24 +05:30
github-actions[bot]
9f6ce6ab70 chore: update commit hash to 6987ceae9e 2024-12-16 16:06:45 +00:00
Anirban Kar
6987ceae9e Merge pull request #433 from DiegoSouzaPW/feature/SlotCloneError
Check the render method of SlotClone. #432
2024-12-16 21:36:27 +05:30
github-actions[bot]
15ce03598f chore: update commit hash to 8aee6ebf47 2024-12-16 16:02:04 +00:00
Anirban Kar
8aee6ebf47 Merge pull request #771 from thecodacus/app-fail-safari-fix
fix: Application  fails to load on Safari
2024-12-16 21:31:52 +05:30
Anirban Kar
8deed62546 Merge branch 'main' into app-fail-safari-fix 2024-12-16 21:31:36 +05:30
github-actions[bot]
278322d544 chore: update commit hash to 995fb81ac7 2024-12-16 15:59:54 +00:00
Anirban Kar
995fb81ac7 Merge pull request #760 from Stijnus/main
fix: UI bug debug tab : System Information
2024-12-16 21:29:41 +05:30
Anirban Kar
951b11005f added missing icons for safari 2024-12-16 21:28:38 +05:30
github-actions[bot]
c2766cb5fc chore: update commit hash to f752bf7da5 2024-12-16 15:33:38 +00:00
Anirban Kar
f752bf7da5 Merge branch 'main' into main 2024-12-16 21:03:24 +05:30
Anirban Kar
bb94180209 Merge remote-tracking branch 'origin/main' into system-prompt-variations-local 2024-12-16 20:52:01 +05:30
Anirban Kar
2553814416 Merge remote-tracking branch 'upstream/main' 2024-12-16 20:41:50 +05:30
github-actions[bot]
976676399e chore: update commit hash to 78505ed2f3 2024-12-16 15:10:11 +00:00
Anirban Kar
78505ed2f3 Merge pull request #769 from thecodacus/token-usage
feat: Show token usage on LLM call assistant message
2024-12-16 20:39:57 +05:30
Anirban Kar
a15544749a Merge branch 'main' into token-usage 2024-12-16 19:56:20 +05:30
github-actions[bot]
dd24ccc298 chore: update commit hash to 77073a5e7f 2024-12-16 14:23:52 +00:00
Anirban Kar
77073a5e7f Merge pull request #755 from thecodacus/fix-variable-name
fix: Added auto detect branch name and version tag for Debug Tab
2024-12-16 19:53:39 +05:30
Anirban Kar
c3c9e43935 Merge branch 'main' into fix-variable-name 2024-12-16 19:53:01 +05:30
Anirban Kar
3b8d251a55 updated implementation 2024-12-16 19:47:18 +05:30
eduardruzga
070e911be1 Lint fix 2024-12-16 11:09:35 +02:00
eduardruzga
1b76d3c28f merge 2024-12-16 11:07:22 +02:00
eduardruzga
225b553876 Another attempt to add toek usage info 2024-12-16 11:01:41 +02:00
github-actions[bot]
66cb2af6df chore: update commit hash to 960f532f82 2024-12-16 08:01:34 +00:00
github-actions[bot]
960f532f82 chore: update commit hash to 6ba93974a0 2024-12-15 22:52:33 +00:00
Dustin Loring
6ba93974a0 add: default-provider-image
added and set a default provider icon
2024-12-15 17:52:23 -05:00
Dustin Loring
d0d0fcd88f add: default provider icon
Added and set a default provider icon
2024-12-15 17:38:39 -05:00
github-actions[bot]
039e616bf5 chore: update commit hash to d3727459aa 2024-12-15 22:15:59 +00:00
github-actions[bot]
9e1c44a8c9 chore: update commit hash to 810cc81a16 2024-12-15 22:13:52 +00:00
Dustin Loring
810cc81a16 doc: fix clickable links docs
Fix clickable links docs
2024-12-15 17:13:40 -05:00
Dustin Loring
a69cda5123 Update CONTRIBUTING.md 2024-12-15 16:52:11 -05:00
Dustin Loring
66a445d548 doc: Make links clickable in docs
Made links clickable in docs
2024-12-15 16:50:03 -05:00
github-actions[bot]
a6fa133321 chore: update commit hash to 0157fddc76 2024-12-15 21:43:20 +00:00
Dustin Loring
0157fddc76 doc: new section heading
new section heading added in index
2024-12-15 16:43:10 -05:00
Dustin Loring
2119a92031 doc: new section heading
small update
2024-12-15 16:41:25 -05:00
github-actions[bot]
f34c173aaa chore: update commit hash to d9b2801434 2024-12-15 21:37:17 +00:00
Dustin Loring
d9b2801434 doc: mkdoc-docs-styled
mkdoc consistent style
2024-12-15 16:37:07 -05:00
Dustin Loring
21bfcfcec4 quick fix 2024-12-15 16:34:08 -05:00
Dustin Loring
90847e7cb6 Update ConnectionsTab.tsx
checks to make sure the entered username and token is correct before accepting it. Let you disconnect also.
2024-12-15 16:30:10 -05:00
Anirban Kar
19a3a03d45 Merge branch 'main' into system-prompt-variations-local 2024-12-16 02:39:55 +05:30
Dustin Loring
a053bfc96f doc: mkdoc consistent style
used a consistent style throughout the mkdoc's when separating sections
2024-12-15 16:04:32 -05:00
github-actions[bot]
02621e3545 chore: update commit hash to d22b32ae63 2024-12-15 20:50:39 +00:00
Dustin Loring
d22b32ae63 doc: mkdoc-update-names
doc: update mkdocs.yml Bolt to bolt
2024-12-15 15:50:28 -05:00
github-actions[bot]
a340611310 chore: update commit hash to b5867835f5 2024-12-15 20:43:21 +00:00
Anirban Kar
b5867835f5 Merge pull request #751 from dustinwloring1988/fix/v3_lazyRouteDiscovery-warn
fix: update vite.config.ts
2024-12-16 02:13:11 +05:30
github-actions[bot]
e9376db705 chore: update commit hash to d75899d737 2024-12-15 20:42:22 +00:00
Anirban Kar
d75899d737 Merge pull request #753 from dustinwloring1988/fix/lm-studio-fetch-warning
fix: warn Constants Failed
2024-12-16 02:12:13 +05:30
Anirban Kar
bc6b84851f fix 2024-12-16 02:08:58 +05:30
github-actions[bot]
1c3582c440 chore: update commit hash to 1e7c3a4ff8 2024-12-15 20:34:30 +00:00
Dustin Loring
1e7c3a4ff8 add: favicon-ico
added a favicon.ico
2024-12-15 15:34:21 -05:00
Dustin Loring
15f624e0ee add: a fav.ico
Added a fav.ico
2024-12-15 15:31:07 -05:00
Stijnus
d3727459aa Update DebugTab.tsx
Fix debug information
2024-12-15 21:27:07 +01:00
Dustin Loring
2819911b96 Update constants.ts
fixes the 'WARN Constants Failed to get LMStudio models:  fetch failed' error as the user most likely just has it active in provider
2024-12-15 15:25:31 -05:00
Anirban Kar
885e104f27 added auto detect branch name and version tag 2024-12-16 01:54:24 +05:30
Dustin Loring
fb8191ebb0 Update vite.config.ts
added v3_lazyRouteDiscovery to the fvite.config.ts without any side effects.
this removes the warning in terminal
2024-12-15 15:20:22 -05:00
Dustin Loring
316c210e86 Update mkdocs.yml
changed Bolt to bolt
2024-12-15 15:17:05 -05:00
github-actions[bot]
c4f94aa517 chore: update commit hash to 4016f54933 2024-12-15 19:14:42 +00:00
Dustin Loring
4016f54933 ui-ux: debug-tab
debug tab check for update is now branch specific.
fixed bug with getting URLs for experimental models
2024-12-15 14:14:31 -05:00
github-actions[bot]
4caae9cec3 chore: update commit hash to e223e9b6af 2024-12-15 19:12:29 +00:00
Dustin Loring
e223e9b6af doc: update-Bolt-to-bolt
branding update Bolt to bolt in the docs
2024-12-15 14:12:19 -05:00
Dustin Loring
b5c8d43d9e quick fix 2024-12-15 14:06:37 -05:00
Dustin Loring
aab917eb7e Update CONTRIBUTING.md 2024-12-15 13:50:48 -05:00
Dustin Loring
30728ae5bd Update FAQ.md 2024-12-15 13:50:34 -05:00
Dustin Loring
51347edd28 quick fix 2024-12-15 13:08:16 -05:00
Dustin Loring
c5c3eee267 Update useSettings.tsx
if it has not been set by the user yet set it correctly for them
2024-12-15 13:04:50 -05:00
Dustin Loring
69b1dc4c9a updated to use settings for branch selection 2024-12-15 12:56:25 -05:00
Dustin Loring
fe24f3c011 doc: branding update
Changed Bolt to bolt and moved the section above the TOC to under it
2024-12-15 12:33:53 -05:00
Dustin Loring
348f396d32 Update commit.yaml 2024-12-15 12:10:44 -05:00
Dustin Loring
253e37f901 Update commit.yaml
now runs on all branches for auto update to work correctly
2024-12-15 12:06:42 -05:00
Anirban Kar
1f513accc9 Merge branch 'main' into system-prompt-variations 2024-12-15 22:21:46 +05:30
Anirban Kar
31706183b4 updated the examples and added strict rules 2024-12-15 22:15:17 +05:30
Dustin Loring
4d9ecbe201 Merge branch 'main' into ui-ux/debug-tab 2024-12-15 11:07:41 -05:00
Dustin Loring
b160d23b48 update by branch 2024-12-15 11:06:33 -05:00
Dustin Loring
a698fba1c7 feat: start update by branch
Here is a start to the update by branch
2024-12-15 11:00:23 -05:00
Anirban Kar
9f5c01f5dd Merge branch 'main' into system-prompt-variations 2024-12-15 21:01:52 +05:30
github-actions[bot]
ed6433e8cd chore: update commit hash to 87a90718d3 2024-12-15 15:27:46 +00:00
Dustin Loring
87a90718d3 doc: README-formatting
README formatting changed and to & to fit on one line
2024-12-15 10:27:36 -05:00
github-actions[bot]
825137a447 chore: update commit hash to 9cd9ee9088 2024-12-15 15:25:48 +00:00
Dustin Loring
9cd9ee9088 add: perplexity-provider-icon
added a Perplexity provider icon
2024-12-15 10:25:37 -05:00
Dustin Loring
2bb9f609dc add: Perplexity Provider Icon
added the provider icon for Perplexity
2024-12-15 10:19:31 -05:00
Anirban Kar
6467995ac3 updated readme 2024-12-15 20:40:46 +05:30
Anirban Kar
2b8236f988 updated readme 2024-12-15 20:28:15 +05:30
Dustin Loring
c54e6e588e Update README.md
changed 'and' to '&' so that it would fit on one line
2024-12-15 09:04:44 -05:00
github-actions[bot]
c7cdbdfc3d chore: update commit hash to 23346f6271 2024-12-15 13:48:21 +00:00
Dustin Loring
23346f6271 ui: fix-perplexity-icon
Added fallback icon for provider, fixes perplexity icon not showing
2024-12-15 08:48:12 -05:00
Dustin Loring
558d4b2e10 ui: fallback icon for provider
Added a fallback icon for providers
2024-12-15 08:44:57 -05:00
github-actions[bot]
fc13754788 chore: update commit hash to b3f7a5c378 2024-12-15 13:22:09 +00:00
Dustin Loring
b3f7a5c378 Merge pull request #726 from dustinwloring1988/ui-ux/features-tab
ui-ux: Features Tab Changes
2024-12-15 08:21:58 -05:00
github-actions[bot]
61ac8f9808 chore: update commit hash to d936c012bd 2024-12-15 13:09:26 +00:00
Dustin Loring
d936c012bd ui-ux: prompt-enhanced-toast
ui-ux: prompt enhanced toast notification
2024-12-15 08:09:16 -05:00
github-actions[bot]
4541a3e9dd chore: update commit hash to 7c3a3bbde6 2024-12-15 13:08:52 +00:00
Dustin Loring
7c3a3bbde6 ui-ux: Setting-Menu
ui-ux: Setting Modal Changes
2024-12-15 08:08:41 -05:00
github-actions[bot]
ecbf2f3bcd chore: update commit hash to a87cfd7950 2024-12-15 12:21:08 +00:00
Cole Medin
a87cfd7950 Merge pull request #728 from dustinwloring1988/branding/Change-Bolt-to-bolt
doc: README, FAQ, CONTRIBUTING branding updates
2024-12-15 06:20:59 -06:00
Anirban Kar
70f88f981a feat: Experimental Prompt Library Added 2024-12-15 16:47:16 +05:30
github-actions[bot]
4ea38e8766 chore: update commit hash to 25fe15232f 2024-12-15 09:52:57 +00:00
Anirban Kar
25fe15232f Merge pull request #602 from mark-when/contextMenu2
Feat: Basic file tree context menu
2024-12-15 15:22:46 +05:30
github-actions[bot]
b8e457eeb7 chore: update commit hash to b06f6e3a3e 2024-12-15 09:45:21 +00:00
Anirban Kar
b06f6e3a3e Merge pull request #715 from meetpateltech/perplexity-models
feat: added perplexity model
2024-12-15 15:15:10 +05:30
Anirban Kar
86f37fcaca Merge branch 'main' into perplexity-models 2024-12-15 15:15:01 +05:30
Dustin Loring
2cb8c825d0 ui-ux: prompt enhanced toast notification
changed prompt enhanced to give a toast notification instead of changing the ui.
2024-12-14 22:25:28 -05:00
Dustin Loring
aa3559149f Update DebugTab.tsx 2024-12-14 20:35:41 -05:00
Dustin Loring
e0d0c4b697 Branding updates
changed Bolt.diy to bolt.diy
reworded the bottom of the README
2024-12-14 20:26:56 -05:00
Dustin Loring
a976a25094 Update DebugTab.tsx
fixed the Local LLM Status not showing BaseURL's
2024-12-14 20:11:20 -05:00
Dustin Loring
bb03c30ddd Update DebugTab.tsx
Fixed Check for Update not getting the correct commit
2024-12-14 20:09:25 -05:00
Dustin Loring
5893629306 ui-ux: combined optional features
on features tab combined (debug info and event logs) into 'Debug Features'
2024-12-14 19:43:43 -05:00
Dustin Loring
d4aa189cee ui-ux: Renamed feature
Enhancement - on feature tab Change 'Enable Local Models' to 'Experimental Providers'
2024-12-14 19:40:37 -05:00
Dustin Loring
1e73e8863a ui-ux: Setting Modal Changes
Enhancement - move the connection tab below chat history in left side of settings
Enhancement - on chat tab Delete all chats, should prompt to make sure you want to
Enhancement - Debug tab change copy debug info from a popup to a toast notification
2024-12-14 19:30:36 -05:00
eduardruzga
2e05270bab Merge 2024-12-14 19:48:37 +02:00
github-actions[bot]
9efc709782 chore: update commit hash to ece0213500 2024-12-14 16:07:12 +00:00
Dustin Loring
ece0213500 add: Groq Llama 3.2 90B Vision Preview
Add 90b llama-3.2 model for better performance
2024-12-14 11:06:59 -05:00
github-actions[bot]
3aab6c7b68 chore: update commit hash to 43370f515d 2024-12-14 15:47:40 +00:00
Ed McConnell
43370f515d Merge pull request #722 from emcconnell/update-readme
Update readme
2024-12-14 10:47:30 -05:00
Ed McConnell
9408ae4dd9 Merge branch 'main' into update-readme 2024-12-14 10:45:41 -05:00
Ed McConnell
483189ab46 update readme 2024-12-14 10:42:28 -05:00
Ed McConnell
5cb693c415 update readme 2024-12-14 10:42:05 -05:00
github-actions[bot]
09881a478c chore: update commit hash to 4f10fb1294 2024-12-14 15:12:27 +00:00
Ed McConnell
4f10fb1294 Merge pull request #582 from emcconnell/feat/image-select
Add Screenshot Capture and Management Features to Chat and Workbench Components
2024-12-14 10:12:17 -05:00
Ed McConnell
9b98670ccb Merge branch 'main' into feat/image-select 2024-12-14 10:10:52 -05:00
github-actions[bot]
54c7e3d8f9 chore: update commit hash to eb53146937 2024-12-14 14:59:48 +00:00
Dustin Loring
eb53146937 add: groq-llama3.3-70b
add: Groq Llama 3.3 70B
removed Groq Llama 3.1 70B (deprecated)
2024-12-14 09:59:38 -05:00
Ed McConnell
4db916928c merge main 2024-12-14 09:56:51 -05:00
Ed McConnell
7a31db904d Merge branch 'main' into feat/image-select 2024-12-14 09:56:29 -05:00
github-actions[bot]
f87522f106 chore: update commit hash to f27f7bba51 2024-12-14 14:52:49 +00:00
github-actions[bot]
f27f7bba51 chore: update commit hash to 4f02887565 2024-12-14 08:46:42 +00:00
Anirban Kar
4f02887565 Merge pull request #679 from Dlouxgit/main
fix: handle conflicts between input method engine and enter key in chatbox
2024-12-14 14:16:31 +05:30
Anirban Kar
3db4004642 Update BaseChat.tsx 2024-12-14 14:15:27 +05:30
github-actions[bot]
79ce87ee5d chore: update commit hash to a71cfba660 2024-12-14 08:29:16 +00:00
github-actions[bot]
a71cfba660 chore: update commit hash to 4af18c069f 2024-12-14 07:27:29 +00:00
Anirban Kar
4af18c069f Merge pull request #655 from thecodacus/streaming-fixed
fix: Add Code Streaming Sampling for Performance Optimization
2024-12-14 12:57:18 +05:30
Anirban Kar
02d0be5feb Merge branch 'main' into streaming-fixed 2024-12-14 12:56:36 +05:30
github-actions[bot]
81d2c01442 chore: update commit hash to 6a5ed21c0f 2024-12-14 07:25:13 +00:00
Anirban Kar
6a5ed21c0f Merge pull request #670 from thecodacus/private-github-repo
added support for private github repo through github connections
2024-12-14 12:55:02 +05:30
Meet Patel
8bcd82c9d4 feat: added perplexity model 2024-12-14 11:59:10 +05:30
Ed McConnell
6ffcdd8b3c merge main into image 2024-12-13 21:22:12 -05:00
Ed McConnell
a936c5a990 Merge branch 'main' into feat/image-select-merge 2024-12-13 21:21:10 -05:00
github-actions[bot]
bbda3a1db4 chore: update commit hash to 9666b2ab67 2024-12-14 02:09:03 +00:00
Ed McConnell
4cfabd94ee merged main 2024-12-13 20:49:33 -05:00
kris1803
2064c83177 Fixed console error for SettingsWIndow & Removed ts-nocheck where not needed 2024-12-14 00:39:27 +01:00
github-actions[bot]
9666b2ab67 chore: update commit hash to 55094392cf 2024-12-13 20:58:40 +00:00
Anirban Kar
55094392cf Merge pull request #713 from thecodacus/context-optimization-fix
fix: removed context optimization temporarily, to be moved to optional
2024-12-14 02:28:22 +05:30
Anirban Kar
456c89429a fix: removed context optimization temporarily, to be moved to optional from menu 2024-12-14 02:25:36 +05:30
github-actions[bot]
77425d61d9 chore: update commit hash to 8c4397a19f 2024-12-13 20:38:54 +00:00
Anirban Kar
8c4397a19f Merge pull request #578 from thecodacus/context-optimization
feat(context optimization): Optimize LLM Context Management and File Handling
2024-12-14 02:08:43 +05:30
Dustin Loring
32409047ff Update constants.ts
Removed Llama3.1 70B and replaced it with Llama3.3-70B
2024-12-13 14:48:02 -05:00
github-actions[bot]
301675e30c chore: update commit hash to 1e04ab38b0 2024-12-13 19:26:12 +00:00
github-actions[bot]
1e04ab38b0 chore: update commit hash to d1fa70fc97 2024-12-13 18:58:51 +00:00
Dustin Loring
d1fa70fc97 fix: start new chat icon
Fix/start new chat icon
2024-12-13 13:58:41 -05:00
Anirban Kar
fe3889be81 Merge pull request #708 from SujalXplores/fix/ui-enhancements
Fix/UI enhancements
2024-12-14 00:27:22 +05:30
Anirban Kar
461cf27fc7 Merge branch 'main' into fix/ui-enhancements 2024-12-14 00:27:10 +05:30
Dustin Loring
4980a9a33c Merge branch 'main' into fix/start-new-chat-icon 2024-12-13 13:57:02 -05:00
github-actions[bot]
c4a94d6595 chore: update commit hash to 1d64a15ed0 2024-12-13 18:55:33 +00:00
Dustin Loring
1d64a15ed0 fix: lm studio fix
LM Studio was unable to receive messages sending message.
2024-12-13 13:53:43 -05:00
github-actions[bot]
b6df84b56a chore: update commit hash to 0c899e430a 2024-12-13 18:52:29 +00:00
Dustin Loring
0c899e430a fix: commit-file-ignore
No more seeing the commit file change if they are running actions
2024-12-13 13:52:17 -05:00
Dustin Loring
da07c667af Update commit.json 2024-12-13 13:42:59 -05:00
Dustin Loring
bc44e6fa3a Update .gitignore
Added with app/commit.json
2024-12-13 13:42:07 -05:00
SujalXplores
69ec309f81 feat: add unit configuration to uno.config.ts 2024-12-14 00:00:23 +05:30
SujalXplores
ddb920df7c refactor: simplify GitCloneButton component by removing unused tooltip and streamlining button structure 2024-12-13 22:49:14 +05:30
SujalXplores
56944de633 refactor: remove unused React import in ImportButtons component 2024-12-13 22:48:34 +05:30
SujalXplores
ff2726fd2f fix: adjust intro section margin and textarea outline style in BaseChat component 2024-12-13 22:47:57 +05:30
github-actions[bot]
1764145ba4 chore: update commit hash to 5f34051510 2024-12-13 16:19:58 +00:00
Dustin Loring
ba1b5543db fix: LM Studio sending messgae
LM Studio was not able to send a message now it is.
2024-12-13 11:03:55 -05:00
github-actions[bot]
4321007e4f chore: update commit hash to 5f34051510 2024-12-13 16:00:51 +00:00
github-actions[bot]
5f34051510 chore: update commit hash to 5773b1e271 2024-12-13 15:23:11 +00:00
github-actions[bot]
85b0322fd6 chore: update commit hash to d479daa578 2024-12-13 15:23:03 +00:00
Anirban Kar
5773b1e271 Merge pull request #676 from Stijnus/main
Added some small UI enhancements to the Settings and Sidebar
2024-12-13 20:53:00 +05:30
Anirban Kar
d479daa578 Merge branch 'main' into main 2024-12-13 20:52:51 +05:30
github-actions[bot]
78cd04a541 chore: update commit hash to eeafc12522 2024-12-13 15:19:54 +00:00
Dustin Loring
eeafc12522 doc: update README.md
Updated setup section
Updated the Features sections
Changed a few more Bolt.new to Bolt.diy
2024-12-13 10:19:43 -05:00
github-actions[bot]
a568421cef chore: update commit hash to dd296ab00d 2024-12-13 15:19:26 +00:00
Anirban Kar
dd296ab00d Merge remote-tracking branch 'github-desktop-stijnus/main' into pr/676 2024-12-13 20:49:07 +05:30
Anirban Kar
77b47c1ce6 some clean up and added a all log option 2024-12-13 20:48:33 +05:30
Dustin Loring
ec4b43d7a3 Update README.md 2024-12-13 10:16:41 -05:00
github-actions[bot]
bbf36b23f4 chore: update commit hash to d13da30bda 2024-12-13 15:02:35 +00:00
Anirban Kar
d13da30bda ui styles fixed 2024-12-13 20:31:37 +05:30
github-actions[bot]
4329e77664 chore: update commit hash to 8f15c81f37 2024-12-13 14:34:35 +00:00
Anirban Kar
8f15c81f37 Merge pull request #684 from thecodacus/fix-auto-select-model
fix: auto select model on provider disabled
2024-12-13 20:04:22 +05:30
github-actions[bot]
4ba5d37fcd chore: update commit hash to e5ecb0b7d5 2024-12-13 10:49:32 +00:00
Stijnus
e5ecb0b7d5 Update commit.json 2024-12-13 11:49:09 +01:00
Stijnus
a6d6fef7d6 Merge branch 'main' of https://github.com/Stijnus/bolt.new-any-llm 2024-12-13 11:39:25 +01:00
Stijnus
f8e090b9d4 Update commit.json 2024-12-13 11:39:03 +01:00
github-actions[bot]
a9f8c2bb6a chore: update commit hash to 7bafd2a5d6 2024-12-13 10:37:13 +00:00
Stijnus
7bafd2a5d6 Merge branch 'main' of https://github.com/stackblitz-labs/bolt.diy 2024-12-13 11:36:45 +01:00
Stijnus
c0c1275226 minor bug fixes 2024-12-13 11:33:29 +01:00
Stijnus
b1a3e3993e debug fixes 2024-12-13 09:22:21 +01:00
Stijnus
b16aab1f16 Update debug tab to check against fork 2024-12-13 09:17:35 +01:00
Anirban Kar
a404a35d0e auto select model on provider disabled 2024-12-13 12:01:50 +05:30
Stijnus
49e6c8034d Merge branch 'stackblitz-labs:main' into main 2024-12-13 06:58:09 +01:00
Dlouxgit
b0ca49d65e fix: handle conflicts between input method engine and enter key 2024-12-13 13:28:27 +08:00
Stijnus
87057f8137 Event logs bug fix
minor improvements download logs, auto scroll, clear logs
2024-12-13 01:40:58 +01:00
Stijnus
e39f16e436 Settings UI enhancement
Date & Time Display
Added a real-time clock component in the sidebar

Event Logs System
Implemented an EventLogsTab component for system monitoring
Provides a structured way to:
Track user interactions
Monitor system events
Display activity history
2024-12-13 01:11:35 +01:00
Stijnus
e716ca55f0 Add Logo icons LLM's
Added the Next.js Image component import for optimized image loading
Modified the provider item layout to include an icon next to the provider name
Used template literals to dynamically load the correct icon based on the provider name
Added proper sizing (24x24) for consistent icon display
Added dark:invert class to ensure icons are visible in dark mode (assuming they're dark by default)
2024-12-12 23:46:41 +01:00
Anirban Kar
3bc8c5f856 added support for private github repo through github connections 2024-12-13 01:23:56 +05:30
Anirban Kar
e3bdd6944b added prompt url params 2024-12-13 00:58:02 +05:30
Anirban Kar
97b886abf0 fix: added more controlled rate for code streaming 2024-12-12 03:13:52 +05:30
Anirban Kar
da37d9456f Merge branch 'main' into context-optimization 2024-12-12 02:44:36 +05:30
Anirban Kar
3c7b125828 Merge branch 'main' into context-optimization 2024-12-12 02:38:00 +05:30
Dustin Loring
74b6d27283 Update README.md 2024-12-11 15:51:39 -05:00
Dustin Loring
9b48f2471e Update README.md 2024-12-11 15:51:04 -05:00
Dustin Loring
9a8dcce906 Update README.md 2024-12-11 14:56:41 -05:00
Dustin Loring
b1e54a493f Update README.md 2024-12-11 12:08:37 -05:00
Anirban Kar
dfbbea110e removed console logs 2024-12-10 14:27:12 +05:30
eduardruzga
fcb61ba499 Refactor to use newver v4 version of Vercel AI package 2024-12-09 17:26:33 +02:00
Rob Koch
6eb2d84dff pnpm lock file 2024-12-08 16:31:53 -08:00
Rob Koch
13a15e9a3d copyPath and copyRelativePath for files and folders 2024-12-08 15:22:46 -08:00
Rob Koch
eb36ec6170 basic context menu for folders 2024-12-08 14:49:02 -08:00
Anirban Kar
b304749b21 added backdrop and loading screen 2024-12-08 22:53:20 +05:30
Anirban Kar
ea5c6244a6 feat(context optimization):improved context management and redused chat overhead 2024-12-07 15:58:13 +05:30
Ed McConnell
0e86bf7709 More selection tool changes 2024-12-06 22:27:15 -05:00
Ibrahim H.
a2da05e9cb Add 90b llama-3.2 model for better performance
Add support for `llama-3.2-90b-vision-preview` model from Groq.
2024-12-06 17:08:19 +01:00
Ed McConnell
7fdab0ad6a Second commit for screen cap feature 2024-12-05 17:31:47 -05:00
Ed McConnell
8b7e18e627 Initial commit for screen cap feature 2024-12-05 17:30:45 -05:00
Diego Souza
44bda1500a Check the render method of SlotClone. #432 2024-11-26 17:39:13 -03:00
146 changed files with 7669 additions and 3470 deletions

View File

@@ -32,7 +32,8 @@ OPEN_ROUTER_API_KEY=
GOOGLE_GENERATIVE_AI_API_KEY=
# You only need this environment variable set if you want to use oLLAMA models
# EXAMPLE http://localhost:11434
# DONT USE http://localhost:11434 due to IPV6 issues
# USE EXAMPLE http://127.0.0.1:11434
OLLAMA_API_BASE_URL=
# You only need this environment variable set if you want to use OpenAI Like models
@@ -50,6 +51,12 @@ OPENAI_LIKE_API_KEY=
# Get your Together API Key
TOGETHER_API_KEY=
# You only need this environment variable set if you want to use Hyperbolic models
#Get your Hyperbolics API Key at https://app.hyperbolic.xyz/settings
#baseURL="https://api.hyperbolic.xyz/v1/chat/completions"
HYPERBOLIC_API_KEY=
HYPERBOLIC_API_BASE_URL=
# Get your Mistral API Key by following these instructions -
# https://console.mistral.ai/api-keys/
# You only need this environment variable set if you want to use Mistral models
@@ -62,7 +69,8 @@ COHERE_API_KEY=
# Get LMStudio Base URL from LM Studio Developer Console
# Make sure to enable CORS
# Example: http://localhost:1234
# DONT USE http://localhost:1234 due to IPV6 issues
# Example: http://127.0.0.1:1234
LMSTUDIO_API_BASE_URL=
# Get your xAI API key
@@ -70,6 +78,11 @@ LMSTUDIO_API_BASE_URL=
# You only need this environment variable set if you want to use xAI models
XAI_API_KEY=
# Get your Perplexity API Key here -
# https://www.perplexity.ai/settings/api
# You only need this environment variable set if you want to use Perplexity models
PERPLEXITY_API_KEY=
# Include this environment variable if you want more logging for debugging locally
VITE_LOG_LEVEL=debug

261
.github/scripts/generate-changelog.sh vendored Executable file
View File

@@ -0,0 +1,261 @@
#!/usr/bin/env bash
# Ensure we're running in bash
if [ -z "$BASH_VERSION" ]; then
echo "This script requires bash. Please run with: bash $0" >&2
exit 1
fi
# Ensure we're using bash 4.0 or later for associative arrays
if ((BASH_VERSINFO[0] < 4)); then
echo "This script requires bash version 4 or later" >&2
echo "Current bash version: $BASH_VERSION" >&2
exit 1
fi
# Set default values for required environment variables if not in GitHub Actions
if [ -z "$GITHUB_ACTIONS" ]; then
: "${GITHUB_SERVER_URL:=https://github.com}"
: "${GITHUB_REPOSITORY:=stackblitz-labs/bolt.diy}"
: "${GITHUB_OUTPUT:=/tmp/github_output}"
touch "$GITHUB_OUTPUT"
# Running locally
echo "Running locally - checking for upstream remote..."
MAIN_REMOTE="origin"
if git remote -v | grep -q "upstream"; then
MAIN_REMOTE="upstream"
fi
MAIN_BRANCH="main" # or "master" depending on your repository
# Ensure we have latest tags
git fetch ${MAIN_REMOTE} --tags
# Use the remote reference for git log
GITLOG_REF="${MAIN_REMOTE}/${MAIN_BRANCH}"
else
# Running in GitHub Actions
GITLOG_REF="HEAD"
fi
# Get the latest tag
LATEST_TAG=$(git describe --tags --abbrev=0 2>/dev/null || echo "")
# Start changelog file
echo "# 🚀 Release v${NEW_VERSION}" > changelog.md
echo "" >> changelog.md
echo "## What's Changed 🌟" >> changelog.md
echo "" >> changelog.md
if [ -z "$LATEST_TAG" ]; then
echo "### 🎉 First Release" >> changelog.md
echo "" >> changelog.md
echo "Exciting times! This marks our first release. Thanks to everyone who contributed! 🙌" >> changelog.md
echo "" >> changelog.md
COMPARE_BASE="$(git rev-list --max-parents=0 HEAD)"
else
echo "### 🔄 Changes since $LATEST_TAG" >> changelog.md
echo "" >> changelog.md
COMPARE_BASE="$LATEST_TAG"
fi
# Function to extract conventional commit type and associated emoji
get_commit_type() {
local msg="$1"
if [[ $msg =~ ^feat(\(.+\))?:|^feature(\(.+\))?: ]]; then echo "✨ Features"
elif [[ $msg =~ ^fix(\(.+\))?: ]]; then echo "🐛 Bug Fixes"
elif [[ $msg =~ ^docs(\(.+\))?: ]]; then echo "📚 Documentation"
elif [[ $msg =~ ^style(\(.+\))?: ]]; then echo "💎 Styles"
elif [[ $msg =~ ^refactor(\(.+\))?: ]]; then echo "♻️ Code Refactoring"
elif [[ $msg =~ ^perf(\(.+\))?: ]]; then echo "⚡ Performance Improvements"
elif [[ $msg =~ ^test(\(.+\))?: ]]; then echo "🧪 Tests"
elif [[ $msg =~ ^build(\(.+\))?: ]]; then echo "🛠️ Build System"
elif [[ $msg =~ ^ci(\(.+\))?: ]]; then echo "⚙️ CI"
elif [[ $msg =~ ^chore(\(.+\))?: ]]; then echo "" # Skip chore commits
else echo "🔍 Other Changes" # Default category with emoji
fi
}
# Initialize associative arrays
declare -A CATEGORIES
declare -A COMMITS_BY_CATEGORY
declare -A ALL_AUTHORS
declare -A NEW_CONTRIBUTORS
# Get all historical authors before the compare base
while IFS= read -r author; do
ALL_AUTHORS["$author"]=1
done < <(git log "${COMPARE_BASE}" --pretty=format:"%ae" | sort -u)
# Process all commits since last tag
while IFS= read -r commit_line; do
if [[ ! $commit_line =~ ^[a-f0-9]+\| ]]; then
echo "WARNING: Skipping invalid commit line format: $commit_line" >&2
continue
fi
HASH=$(echo "$commit_line" | cut -d'|' -f1)
COMMIT_MSG=$(echo "$commit_line" | cut -d'|' -f2)
BODY=$(echo "$commit_line" | cut -d'|' -f3)
# Skip if hash doesn't match the expected format
if [[ ! $HASH =~ ^[a-f0-9]{40}$ ]]; then
continue
fi
HASH=$(echo "$commit_line" | cut -d'|' -f1)
COMMIT_MSG=$(echo "$commit_line" | cut -d'|' -f2)
BODY=$(echo "$commit_line" | cut -d'|' -f3)
# Validate hash format
if [[ ! $HASH =~ ^[a-f0-9]{40}$ ]]; then
echo "WARNING: Invalid commit hash format: $HASH" >&2
continue
fi
# Check if it's a merge commit
if [[ $COMMIT_MSG =~ Merge\ pull\ request\ #([0-9]+) ]]; then
# echo "Processing as merge commit" >&2
PR_NUM="${BASH_REMATCH[1]}"
# Extract the PR title from the merge commit body
PR_TITLE=$(echo "$BODY" | grep -v "^Merge pull request" | head -n 1)
# Only process if it follows conventional commit format
CATEGORY=$(get_commit_type "$PR_TITLE")
if [ -n "$CATEGORY" ]; then # Only process if it's a conventional commit
# Get PR author's GitHub username
GITHUB_USERNAME=$(gh pr view "$PR_NUM" --json author --jq '.author.login')
if [ -n "$GITHUB_USERNAME" ]; then
# Check if this is a first-time contributor
AUTHOR_EMAIL=$(git show -s --format='%ae' "$HASH")
if [ -z "${ALL_AUTHORS[$AUTHOR_EMAIL]}" ]; then
NEW_CONTRIBUTORS["$GITHUB_USERNAME"]=1
ALL_AUTHORS["$AUTHOR_EMAIL"]=1
fi
CATEGORIES["$CATEGORY"]=1
COMMITS_BY_CATEGORY["$CATEGORY"]+="* ${PR_TITLE#*: } ([#$PR_NUM](${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY}/pull/$PR_NUM)) by [@$GITHUB_USERNAME](https://github.com/$GITHUB_USERNAME)"$'\n'
else
COMMITS_BY_CATEGORY["$CATEGORY"]+="* ${PR_TITLE#*: } ([#$PR_NUM](${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY}/pull/$PR_NUM))"$'\n'
fi
fi
# Check if it's a squash merge by looking for (#NUMBER) pattern
elif [[ $COMMIT_MSG =~ \(#([0-9]+)\) ]]; then
# echo "Processing as squash commit" >&2
PR_NUM="${BASH_REMATCH[1]}"
# Only process if it follows conventional commit format
CATEGORY=$(get_commit_type "$COMMIT_MSG")
if [ -n "$CATEGORY" ]; then # Only process if it's a conventional commit
# Get PR author's GitHub username
GITHUB_USERNAME=$(gh pr view "$PR_NUM" --json author --jq '.author.login')
if [ -n "$GITHUB_USERNAME" ]; then
# Check if this is a first-time contributor
AUTHOR_EMAIL=$(git show -s --format='%ae' "$HASH")
if [ -z "${ALL_AUTHORS[$AUTHOR_EMAIL]}" ]; then
NEW_CONTRIBUTORS["$GITHUB_USERNAME"]=1
ALL_AUTHORS["$AUTHOR_EMAIL"]=1
fi
CATEGORIES["$CATEGORY"]=1
COMMIT_TITLE=${COMMIT_MSG%% (#*} # Remove the PR number suffix
COMMIT_TITLE=${COMMIT_TITLE#*: } # Remove the type prefix
COMMITS_BY_CATEGORY["$CATEGORY"]+="* $COMMIT_TITLE ([#$PR_NUM](${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY}/pull/$PR_NUM)) by [@$GITHUB_USERNAME](https://github.com/$GITHUB_USERNAME)"$'\n'
else
COMMIT_TITLE=${COMMIT_MSG%% (#*} # Remove the PR number suffix
COMMIT_TITLE=${COMMIT_TITLE#*: } # Remove the type prefix
COMMITS_BY_CATEGORY["$CATEGORY"]+="* $COMMIT_TITLE ([#$PR_NUM](${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY}/pull/$PR_NUM))"$'\n'
fi
fi
else
# echo "Processing as regular commit" >&2
# Process conventional commits without PR numbers
CATEGORY=$(get_commit_type "$COMMIT_MSG")
if [ -n "$CATEGORY" ]; then # Only process if it's a conventional commit
# Get commit author info
AUTHOR_EMAIL=$(git show -s --format='%ae' "$HASH")
# Try to get GitHub username using gh api
if [ -n "$GITHUB_ACTIONS" ] || command -v gh >/dev/null 2>&1; then
GITHUB_USERNAME=$(gh api "/repos/${GITHUB_REPOSITORY}/commits/${HASH}" --jq '.author.login' 2>/dev/null)
fi
if [ -n "$GITHUB_USERNAME" ]; then
# If we got GitHub username, use it
if [ -z "${ALL_AUTHORS[$AUTHOR_EMAIL]}" ]; then
NEW_CONTRIBUTORS["$GITHUB_USERNAME"]=1
ALL_AUTHORS["$AUTHOR_EMAIL"]=1
fi
CATEGORIES["$CATEGORY"]=1
COMMIT_TITLE=${COMMIT_MSG#*: } # Remove the type prefix
COMMITS_BY_CATEGORY["$CATEGORY"]+="* $COMMIT_TITLE (${HASH:0:7}) by [@$GITHUB_USERNAME](https://github.com/$GITHUB_USERNAME)"$'\n'
else
# Fallback to git author name if no GitHub username found
AUTHOR_NAME=$(git show -s --format='%an' "$HASH")
if [ -z "${ALL_AUTHORS[$AUTHOR_EMAIL]}" ]; then
NEW_CONTRIBUTORS["$AUTHOR_NAME"]=1
ALL_AUTHORS["$AUTHOR_EMAIL"]=1
fi
CATEGORIES["$CATEGORY"]=1
COMMIT_TITLE=${COMMIT_MSG#*: } # Remove the type prefix
COMMITS_BY_CATEGORY["$CATEGORY"]+="* $COMMIT_TITLE (${HASH:0:7}) by $AUTHOR_NAME"$'\n'
fi
fi
fi
done < <(git log "${COMPARE_BASE}..${GITLOG_REF}" --pretty=format:"%H|%s|%b" --reverse --first-parent)
# Write categorized commits to changelog with their emojis
for category in "✨ Features" "🐛 Bug Fixes" "📚 Documentation" "💎 Styles" "♻️ Code Refactoring" "⚡ Performance Improvements" "🧪 Tests" "🛠️ Build System" "⚙️ CI" "🔍 Other Changes"; do
if [ -n "${COMMITS_BY_CATEGORY[$category]}" ]; then
echo "### $category" >> changelog.md
echo "" >> changelog.md
echo "${COMMITS_BY_CATEGORY[$category]}" >> changelog.md
echo "" >> changelog.md
fi
done
# Add first-time contributors section if there are any
if [ ${#NEW_CONTRIBUTORS[@]} -gt 0 ]; then
echo "## ✨ First-time Contributors" >> changelog.md
echo "" >> changelog.md
echo "A huge thank you to our amazing new contributors! Your first contribution marks the start of an exciting journey! 🌟" >> changelog.md
echo "" >> changelog.md
# Use readarray to sort the keys
readarray -t sorted_contributors < <(printf '%s\n' "${!NEW_CONTRIBUTORS[@]}" | sort)
for github_username in "${sorted_contributors[@]}"; do
echo "* 🌟 [@$github_username](https://github.com/$github_username)" >> changelog.md
done
echo "" >> changelog.md
fi
# Add compare link if not first release
if [ -n "$LATEST_TAG" ]; then
echo "## 📈 Stats" >> changelog.md
echo "" >> changelog.md
echo "**Full Changelog**: [\`$LATEST_TAG..v${NEW_VERSION}\`](${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY}/compare/$LATEST_TAG...v${NEW_VERSION})" >> changelog.md
fi
# Output the changelog content
CHANGELOG_CONTENT=$(cat changelog.md)
{
echo "content<<EOF"
echo "$CHANGELOG_CONTENT"
echo "EOF"
} >> "$GITHUB_OUTPUT"
# Also print to stdout for local testing
echo "Generated changelog:"
echo "==================="
cat changelog.md
echo "==================="

View File

@@ -1,33 +0,0 @@
name: Update Commit Hash File
on:
push:
branches:
- main
permissions:
contents: write
jobs:
update-commit:
if: contains(github.event.head_commit.message, '#release') != true
runs-on: ubuntu-latest
steps:
- name: Checkout the code
uses: actions/checkout@v3
- name: Get the latest commit hash
run: echo "COMMIT_HASH=$(git rev-parse HEAD)" >> $GITHUB_ENV
- name: Update commit file
run: |
echo "{ \"commit\": \"$COMMIT_HASH\" }" > app/commit.json
- name: Commit and push the update
run: |
git config --global user.name "github-actions[bot]"
git config --global user.email "github-actions[bot]@users.noreply.github.com"
git add app/commit.json
git commit -m "chore: update commit hash to $COMMIT_HASH"
git push

View File

@@ -4,6 +4,8 @@ on:
push:
branches:
- main
paths:
- 'docs/**' # This will only trigger the workflow when files in docs directory change
permissions:
contents: write
jobs:

32
.github/workflows/semantic-pr.yaml vendored Normal file
View File

@@ -0,0 +1,32 @@
name: Semantic Pull Request
on:
pull_request_target:
types: [opened, reopened, edited, synchronize]
permissions:
pull-requests: read
jobs:
main:
name: Validate PR Title
runs-on: ubuntu-latest
steps:
# https://github.com/amannn/action-semantic-pull-request/releases/tag/v5.5.3
- uses: amannn/action-semantic-pull-request@0723387faaf9b38adef4775cd42cfd5155ed6017
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
subjectPattern: ^(?![A-Z]).+$
subjectPatternError: |
The subject "{subject}" found in the pull request title "{title}"
didn't match the configured pattern. Please ensure that the subject
doesn't start with an uppercase character.
types: |
fix
feat
chore
build
ci
perf
docs
refactor
revert
test

View File

@@ -9,30 +9,7 @@ permissions:
contents: write
jobs:
update-commit:
if: contains(github.event.head_commit.message, '#release')
runs-on: ubuntu-latest
steps:
- name: Checkout the code
uses: actions/checkout@v3
- name: Get the latest commit hash
run: echo "COMMIT_HASH=$(git rev-parse HEAD)" >> $GITHUB_ENV
- name: Update commit file
run: |
echo "{ \"commit\": \"$COMMIT_HASH\" }" > app/commit.json
- name: Commit and push the update
run: |
git config --global user.name "github-actions[bot]"
git config --global user.email "github-actions[bot]@users.noreply.github.com"
git add app/commit.json
git commit -m "chore: update commit hash to $COMMIT_HASH"
git push
prepare-release:
needs: update-commit
if: contains(github.event.head_commit.message, '#release')
runs-on: ubuntu-latest
@@ -103,83 +80,20 @@ jobs:
NEW_VERSION=${{ steps.bump_version.outputs.new_version }}
pnpm version $NEW_VERSION --no-git-tag-version --allow-same-version
- name: Prepare changelog script
run: chmod +x .github/scripts/generate-changelog.sh
- name: Generate Changelog
id: changelog
env:
NEW_VERSION: ${{ steps.bump_version.outputs.new_version }}
run: .github/scripts/generate-changelog.sh
- name: Get the latest commit hash and version tag
run: |
# Get the latest tag
LATEST_TAG=$(git describe --tags --abbrev=0 2>/dev/null || echo "")
# Start changelog file
echo "# Release v${{ steps.bump_version.outputs.new_version }}" > changelog.md
echo "" >> changelog.md
if [ -z "$LATEST_TAG" ]; then
echo "### 🎉 First Release" >> changelog.md
echo "" >> changelog.md
COMPARE_BASE="$(git rev-list --max-parents=0 HEAD)"
else
echo "### 🔄 Changes since $LATEST_TAG" >> changelog.md
echo "" >> changelog.md
COMPARE_BASE="$LATEST_TAG"
fi
# Function to extract conventional commit type
get_commit_type() {
if [[ $1 =~ ^feat:|^feature: ]]; then echo "✨ Features";
elif [[ $1 =~ ^fix: ]]; then echo "🐛 Bug Fixes";
elif [[ $1 =~ ^docs: ]]; then echo "📚 Documentation";
elif [[ $1 =~ ^style: ]]; then echo "💎 Styles";
elif [[ $1 =~ ^refactor: ]]; then echo "♻️ Code Refactoring";
elif [[ $1 =~ ^perf: ]]; then echo "⚡️ Performance Improvements";
elif [[ $1 =~ ^test: ]]; then echo "✅ Tests";
elif [[ $1 =~ ^build: ]]; then echo "🛠️ Build System";
elif [[ $1 =~ ^ci: ]]; then echo "⚙️ CI";
elif [[ $1 =~ ^chore: ]]; then echo "🔧 Chores";
else echo "🔍 Other Changes";
fi
}
# Generate categorized changelog
declare -A CATEGORIES
declare -A COMMITS_BY_CATEGORY
# Get commits since last tag or all commits if no tag exists
while IFS= read -r commit_line; do
HASH=$(echo "$commit_line" | cut -d'|' -f1)
MSG=$(echo "$commit_line" | cut -d'|' -f2)
PR_NUM=$(echo "$commit_line" | cut -d'|' -f3)
CATEGORY=$(get_commit_type "$MSG")
CATEGORIES["$CATEGORY"]=1
# Format commit message with PR link if available
if [ -n "$PR_NUM" ]; then
COMMITS_BY_CATEGORY["$CATEGORY"]+="- ${MSG#*: } ([#$PR_NUM](${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY}/pull/$PR_NUM))"$'\n'
else
COMMITS_BY_CATEGORY["$CATEGORY"]+="- ${MSG#*: }"$'\n'
fi
done < <(git log "${COMPARE_BASE}..HEAD" --pretty=format:"%H|%s|%(trailers:key=PR-Number,valueonly)" --reverse)
# Write categorized commits to changelog
for category in "✨ Features" "🐛 Bug Fixes" "📚 Documentation" "💎 Styles" "♻️ Code Refactoring" "⚡️ Performance Improvements" "✅ Tests" "🛠️ Build System" "⚙️ CI" "🔧 Chores" "🔍 Other Changes"; do
if [ -n "${COMMITS_BY_CATEGORY[$category]}" ]; then
echo "#### $category" >> changelog.md
echo "" >> changelog.md
echo "${COMMITS_BY_CATEGORY[$category]}" >> changelog.md
echo "" >> changelog.md
fi
done
# Add compare link if not first release
if [ -n "$LATEST_TAG" ]; then
echo "**Full Changelog**: [\`$LATEST_TAG..v${{ steps.bump_version.outputs.new_version }}\`](${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY}/compare/$LATEST_TAG...v${{ steps.bump_version.outputs.new_version }})" >> changelog.md
fi
# Save changelog content for the release
CHANGELOG_CONTENT=$(cat changelog.md)
echo "content<<EOF" >> $GITHUB_OUTPUT
echo "$CHANGELOG_CONTENT" >> $GITHUB_OUTPUT
echo "EOF" >> $GITHUB_OUTPUT
echo "COMMIT_HASH=$(git rev-parse HEAD)" >> $GITHUB_ENV
echo "NEW_VERSION=${{ steps.bump_version.outputs.new_version }}" >> $GITHUB_ENV
- name: Commit and Tag Release
run: |

3
.gitignore vendored
View File

@@ -37,3 +37,6 @@ modelfiles
# docs ignore
site
# commit file ignore
app/commit.json

View File

@@ -2,25 +2,31 @@
echo "🔍 Running pre-commit hook to check the code looks good... 🔍"
# Load NVM if available (useful for managing Node.js versions)
export NVM_DIR="$HOME/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh" # Load nvm if you're using i
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"
# Ensure `pnpm` is available
echo "Checking if pnpm is available..."
if ! command -v pnpm >/dev/null 2>&1; then
echo "❌ pnpm not found! Please ensure pnpm is installed and available in PATH."
exit 1
fi
# Run typecheck
echo "Running typecheck..."
which pnpm
if ! pnpm typecheck; then
echo "❌ Type checking failed! Please review TypeScript types."
echo "Once you're done, don't forget to add your changes to the commit! 🚀"
echo "Typecheck exit code: $?"
exit 1
fi
# Run lint
echo "Running lint..."
if ! pnpm lint; then
echo "❌ Linting failed! 'pnpm lint:fix' will help you fix the easy ones."
echo "❌ Linting failed! Run 'pnpm lint:fix' to fix the easy issues."
echo "Once you're done, don't forget to add your beautification to the commit! 🤩"
echo "lint exit code: $?"
exit 1
fi
echo "👍 All good! Committing changes..."
echo "👍 All checks passed! Committing changes..."

View File

@@ -1,217 +1,219 @@
# Contributing to oTToDev
# Contribution Guidelines
First off, thank you for considering contributing to Bolt.diy! This fork aims to expand the capabilities of the original project by integrating multiple LLM providers and enhancing functionality. Every contribution helps make Bolt.diy a better tool for developers worldwide.
Welcome! This guide provides all the details you need to contribute effectively to the project. Thank you for helping us make **bolt.diy** a better tool for developers worldwide. 💡
---
## 📋 Table of Contents
- [Code of Conduct](#code-of-conduct)
- [How Can I Contribute?](#how-can-i-contribute)
- [Pull Request Guidelines](#pull-request-guidelines)
- [Coding Standards](#coding-standards)
- [Development Setup](#development-setup)
- [Deploymnt with Docker](#docker-deployment-documentation)
- [Project Structure](#project-structure)
## Code of Conduct
1. [Code of Conduct](#code-of-conduct)
2. [How Can I Contribute?](#how-can-i-contribute)
3. [Pull Request Guidelines](#pull-request-guidelines)
4. [Coding Standards](#coding-standards)
5. [Development Setup](#development-setup)
6. [Testing](#testing)
7. [Deployment](#deployment)
8. [Docker Deployment](#docker-deployment)
9. [VS Code Dev Containers Integration](#vs-code-dev-containers-integration)
This project and everyone participating in it is governed by our Code of Conduct. By participating, you are expected to uphold this code. Please report unacceptable behavior to the project maintainers.
---
## How Can I Contribute?
## 🛡️ Code of Conduct
### 🐞 Reporting Bugs and Feature Requests
- Check the issue tracker to avoid duplicates
- Use the issue templates when available
- Include as much relevant information as possible
- For bugs, add steps to reproduce the issue
This project is governed by our **Code of Conduct**. By participating, you agree to uphold this code. Report unacceptable behavior to the project maintainers.
### 🔧 Code Contributions
1. Fork the repository
2. Create a new branch for your feature/fix
3. Write your code
4. Submit a pull request
---
### ✨ Becoming a Core Contributor
We're looking for dedicated contributors to help maintain and grow this project. If you're interested in becoming a core contributor, please fill out our [Contributor Application Form](https://forms.gle/TBSteXSDCtBDwr5m7).
## 🛠️ How Can I Contribute?
## Pull Request Guidelines
### 1⃣ Reporting Bugs or Feature Requests
- Check the [issue tracker](#) to avoid duplicates.
- Use issue templates (if available).
- Provide detailed, relevant information and steps to reproduce bugs.
### 📝 PR Checklist
- [ ] Branch from the main branch
- [ ] Update documentation if needed
- [ ] Manually verify all new functionality works as expected
- [ ] Keep PRs focused and atomic
### 2⃣ Code Contributions
1. Fork the repository.
2. Create a feature or fix branch.
3. Write and test your code.
4. Submit a pull request (PR).
### 👀 Review Process
1. Manually test the changes
2. At least one maintainer review required
3. Address all review comments
4. Maintain clean commit history
### 3⃣ Join as a Core Contributor
Interested in maintaining and growing the project? Fill out our [Contributor Application Form](https://forms.gle/TBSteXSDCtBDwr5m7).
## Coding Standards
---
### 💻 General Guidelines
- Follow existing code style
- Comment complex logic
- Keep functions focused and small
- Use meaningful variable names
- Lint your code. This repo contains a pre-commit-hook that will verify your code is linted properly,
so set up your IDE to do that for you!
## ✅ Pull Request Guidelines
## Development Setup
### PR Checklist
- Branch from the **main** branch.
- Update documentation, if needed.
- Test all functionality manually.
- Focus on one feature/bug per PR.
### 🔄 Initial Setup
1. Clone the repository:
### Review Process
1. Manual testing by reviewers.
2. At least one maintainer review required.
3. Address review comments.
4. Maintain a clean commit history.
---
## 📏 Coding Standards
### General Guidelines
- Follow existing code style.
- Comment complex logic.
- Keep functions small and focused.
- Use meaningful variable names.
---
## 🖥️ Development Setup
### 1⃣ Initial Setup
- Clone the repository:
```bash
git clone https://github.com/coleam00/bolt.new-any-llm.git
git clone https://github.com/stackblitz-labs/bolt.diy.git
```
2. Install dependencies:
- Install dependencies:
```bash
pnpm install
```
3. Set up environment variables:
- Rename `.env.example` to `.env.local`
- Add your LLM API keys (only set the ones you plan to use):
- Set up environment variables:
1. Rename `.env.example` to `.env.local`.
2. Add your API keys:
```bash
GROQ_API_KEY=XXX
HuggingFace_API_KEY=XXX
OPENAI_API_KEY=XXX
ANTHROPIC_API_KEY=XXX
...
```
- Optionally set debug level:
```bash
VITE_LOG_LEVEL=debug
```
3. Optionally set:
- Debug level: `VITE_LOG_LEVEL=debug`
- Context size: `DEFAULT_NUM_CTX=32768`
- Optionally set context size:
```bash
DEFAULT_NUM_CTX=32768
```
**Note**: Never commit your `.env.local` file to version control. Its already in `.gitignore`.
Some Example Context Values for the qwen2.5-coder:32b models are.
* DEFAULT_NUM_CTX=32768 - Consumes 36GB of VRAM
* DEFAULT_NUM_CTX=24576 - Consumes 32GB of VRAM
* DEFAULT_NUM_CTX=12288 - Consumes 26GB of VRAM
* DEFAULT_NUM_CTX=6144 - Consumes 24GB of VRAM
**Important**: Never commit your `.env.local` file to version control. It's already included in .gitignore.
### 🚀 Running the Development Server
### 2⃣ Run Development Server
```bash
pnpm run dev
```
**Tip**: Use **Google Chrome Canary** for local testing.
**Note**: You will need Google Chrome Canary to run this locally if you use Chrome! It's an easy install and a good browser for web development anyway.
---
## Testing
## 🧪 Testing
Run the test suite with:
```bash
pnpm test
```
## Deployment
---
To deploy the application to Cloudflare Pages:
## 🚀 Deployment
### Deploy to Cloudflare Pages
```bash
pnpm run deploy
```
Ensure you have required permissions and that Wrangler is configured.
Make sure you have the necessary permissions and Wrangler is correctly configured for your Cloudflare account.
---
# Docker Deployment Documentation
## 🐳 Docker Deployment
This guide outlines various methods for building and deploying the application using Docker.
This section outlines the methods for deploying the application using Docker. The processes for **Development** and **Production** are provided separately for clarity.
## Build Methods
---
### 1. Using Helper Scripts
### 🧑‍💻 Development Environment
NPM scripts are provided for convenient building:
#### Build Options
**Option 1: Helper Scripts**
```bash
# Development build
npm run dockerbuild
```
**Option 2: Direct Docker Build Command**
```bash
docker build . --target bolt-ai-development
```
**Option 3: Docker Compose Profile**
```bash
docker-compose --profile development up
```
#### Running the Development Container
```bash
docker run -p 5173:5173 --env-file .env.local bolt-ai:development
```
---
### 🏭 Production Environment
#### Build Options
**Option 1: Helper Scripts**
```bash
# Production build
npm run dockerbuild:prod
```
### 2. Direct Docker Build Commands
You can use Docker's target feature to specify the build environment:
**Option 2: Direct Docker Build Command**
```bash
# Development build
docker build . --target bolt-ai-development
# Production build
docker build . --target bolt-ai-production
```
### 3. Docker Compose with Profiles
Use Docker Compose profiles to manage different environments:
**Option 3: Docker Compose Profile**
```bash
# Development environment
docker-compose --profile development up
# Production environment
docker-compose --profile production up
```
## Running the Application
After building using any of the methods above, run the container with:
#### Running the Production Container
```bash
# Development
docker run -p 5173:5173 --env-file .env.local bolt-ai:development
# Production
docker run -p 5173:5173 --env-file .env.local bolt-ai:production
```
## Deployment with Coolify
---
[Coolify](https://github.com/coollabsio/coolify) provides a straightforward deployment process:
### Coolify Deployment
1. Import your Git repository as a new project
2. Select your target environment (development/production)
3. Choose "Docker Compose" as the Build Pack
4. Configure deployment domains
5. Set the custom start command:
For an easy deployment process, use [Coolify](https://github.com/coollabsio/coolify):
1. Import your Git repository into Coolify.
2. Choose **Docker Compose** as the build pack.
3. Configure environment variables (e.g., API keys).
4. Set the start command:
```bash
docker compose --profile production up
```
6. Configure environment variables
- Add necessary AI API keys
- Adjust other environment variables as needed
7. Deploy the application
## VS Code Integration
---
The `docker-compose.yaml` configuration is compatible with VS Code dev containers:
## 🛠️ VS Code Dev Containers Integration
1. Open the command palette in VS Code
2. Select the dev container configuration
3. Choose the "development" profile from the context menu
The `docker-compose.yaml` configuration is compatible with **VS Code Dev Containers**, making it easy to set up a development environment directly in Visual Studio Code.
## Environment Files
### Steps to Use Dev Containers
Ensure you have the appropriate `.env.local` file configured before running the containers. This file should contain:
- API keys
- Environment-specific configurations
- Other required environment variables
1. Open the command palette in VS Code (`Ctrl+Shift+P` or `Cmd+Shift+P` on macOS).
2. Select **Dev Containers: Reopen in Container**.
3. Choose the **development** profile when prompted.
4. VS Code will rebuild the container and open it with the pre-configured environment.
## Notes
---
- Port 5173 is exposed and mapped for both development and production environments
- Environment variables are loaded from `.env.local`
- Different profiles (development/production) can be used for different deployment scenarios
- The configuration supports both local development and production deployment
## 🔑 Environment Variables
Ensure `.env.local` is configured correctly with:
- API keys.
- Context-specific configurations.
Example for the `DEFAULT_NUM_CTX` variable:
```bash
DEFAULT_NUM_CTX=24576 # Uses 32GB VRAM
```

95
FAQ.md
View File

@@ -1,54 +1,91 @@
[![Bolt.new: AI-Powered Full-Stack Web Development in the Browser](./public/social_preview_index.jpg)](https://bolt.new)
# Frequently Asked Questions (FAQ)
# Bolt.new Fork by Cole Medin - Bolt.diy
<details>
<summary><strong>What are the best models for bolt.diy?</strong></summary>
## FAQ
For the best experience with bolt.diy, we recommend using the following models:
### How do I get the best results with Bolt.diy?
- **Claude 3.5 Sonnet (old)**: Best overall coder, providing excellent results across all use cases
- **Gemini 2.0 Flash**: Exceptional speed while maintaining good performance
- **GPT-4o**: Strong alternative to Claude 3.5 Sonnet with comparable capabilities
- **DeepSeekCoder V2 236b**: Best open source model (available through OpenRouter, DeepSeek API, or self-hosted)
- **Qwen 2.5 Coder 32b**: Best model for self-hosting with reasonable hardware requirements
- **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.
**Note**: Models with less than 7b parameters typically lack the capability to properly interact with bolt!
</details>
- **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.
<details>
<summary><strong>How do I get the best results with bolt.diy?</strong></summary>
- **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.diy understand the foundation of your project and ensure everything is wired up right before building out more advanced functionality.
- **Be specific about your stack**:
Mention the frameworks or libraries you want to use (e.g., Astro, Tailwind, ShadCN) in your initial prompt. This ensures that bolt.diy scaffolds the project according to your preferences.
- **Batch simple instructions**: Save time by combining simple instructions into one message. For example, you can ask Bolt.diy 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.
- **Use the enhance prompt icon**:
Before sending your prompt, click the *enhance* icon to let the AI refine your prompt. You can edit the suggested improvements before submitting.
### Do you plan on merging Bolt.diy back into the official Bolt.new repo?
- **Scaffold the basics first, then add features**:
Ensure the foundational structure of your application is in place before introducing advanced functionality. This helps bolt.diy establish a solid base to build on.
More news coming on this coming early next month - stay tuned!
- **Batch simple instructions**:
Combine simple tasks into a single prompt to save time and reduce API credit consumption. For example:
*"Change the color scheme, add mobile responsiveness, and restart the dev server."*
</details>
### Why are there so many open issues/pull requests?
<details>
<summary><strong>How do I contribute to bolt.diy?</strong></summary>
Bolt.diy 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
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.
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
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!
Check out our [Contribution Guide](CONTRIBUTING.md) for more details on how to get involved!
</details>
### How do local LLMs fair compared to larger models like Claude 3.5 Sonnet for Bolt.diy/Bolt.new?
<details>
<summary><strong>What are the future plans for bolt.diy?</strong></summary>
As much as the gap is quickly closing between open source and massive close source models, youre 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!
Visit our [Roadmap](https://roadmap.sh/r/ottodev-roadmap-2ovzo) for the latest updates.
New features and improvements are on the way!
</details>
### I'm getting the error: "There was an error processing this request"
<details>
<summary><strong>Why are there so many open issues/pull requests?</strong></summary>
If you see this error within Bolt.diy, 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.
bolt.diy began as a small showcase project on @ColeMedin's YouTube channel to explore editing open-source projects with local LLMs. However, it quickly grew into a massive community effort!
### I'm getting the error: "x-api-key header missing"
We're forming a team of maintainers to manage demand and streamline issue resolution. The maintainers are rockstars, and we're also exploring partnerships to help the project thrive.
</details>
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 Bolt.diy with Docker or pnpm, whichever you didnt run first. We are still on the hunt for why this happens once and a while!
<details>
<summary><strong>How do local LLMs compare to larger models like Claude 3.5 Sonnet for bolt.diy?</strong></summary>
### I'm getting a blank preview when Bolt.diy runs my app!
While local LLMs are improving rapidly, larger models like GPT-4o, Claude 3.5 Sonnet, and DeepSeek Coder V2 236b still offer the best results for complex applications. Our ongoing focus is to improve prompts, agents, and the platform to better support smaller local LLMs.
</details>
We promise you that we are constantly testing new PRs coming into Bolt.diy and the preview is core functionality, so the application is not broken! When you get a blank preview or dont 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.
<details>
<summary><strong>Common Errors and Troubleshooting</strong></summary>
### How to add a LLM:
### **"There was an error processing this request"**
This generic error message means something went wrong. Check both:
- The terminal (if you started the app with Docker or `pnpm`).
- The developer console in your browser (press `F12` or right-click > *Inspect*, then go to the *Console* tab).
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.
### **"x-api-key header missing"**
This error is sometimes resolved by restarting the Docker container.
If that doesn't work, try switching from Docker to `pnpm` or vice versa. We're actively investigating this issue.
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!
### **Blank preview when running the app**
A blank preview often occurs due to hallucinated bad code or incorrect commands.
To troubleshoot:
- Check the developer console for errors.
- Remember, previews are core functionality, so the app isn't broken! We're working on making these errors more transparent.
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!
### **"Everything works, but the results are bad"**
Local LLMs like Qwen-2.5-Coder are powerful for small applications but still experimental for larger projects. For better results, consider using larger models like GPT-4o, Claude 3.5 Sonnet, or DeepSeek Coder V2 236b.
### Everything works but the results are bad
### **"Received structured exception #0xc0000005: access violation"**
If you are getting this, you are probably on Windows. The fix is generally to update the [Visual C++ Redistributable](https://learn.microsoft.com/en-us/cpp/windows/latest-supported-vc-redist?view=msvc-170)
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!
### **"Miniflare or Wrangler errors in Windows"**
You will need to make sure you have the latest version of Visual Studio C++ installed (14.40.33816), more information here https://github.com/stackblitz-labs/bolt.diy/issues/19.
</details>
---
Got more questions? Feel free to reach out or open an issue in our GitHub repo!

390
README.md
View File

@@ -1,26 +1,39 @@
[![Bolt.new: AI-Powered Full-Stack Web Development in the Browser](./public/social_preview_index.jpg)](https://bolt.new)
# bolt.diy (Previously oTToDev)
[![bolt.diy: AI-Powered Full-Stack Web Development in the Browser](./public/social_preview_index.jpg)](https://bolt.diy)
# Bolt.diy (Previously oTToDev)
Welcome to bolt.diy, the official open source version of Bolt.new (previously known as oTToDev and bolt.new ANY LLM), which 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.
Welcome to Bolt.diy, the official open source version of Bolt.new (previously known as oTToDev and Bolt.new ANY LLM), which 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.
Check the [bolt.diy Docs](https://stackblitz-labs.github.io/bolt.diy/) for more information.
Check the [Bolt.diy Docs](https://stackblitz-labs.github.io/bolt.diy/) for more information. This documentation is still being updated after the transfer.
We have also launched an experimental agent called the "bolt.diy Expert" that can answer common questions about bolt.diy. Find it here on the [oTTomator Live Agent Studio](https://studio.ottomator.ai/).
Bolt.diy was originally started by [Cole Medin](https://www.youtube.com/@ColeMedin) but has quickly grown into a massive community effort to build the BEST open source AI coding assistant!
bolt.diy was originally started by [Cole Medin](https://www.youtube.com/@ColeMedin) but has quickly grown into a massive community effort to build the BEST open source AI coding assistant!
## Join the community for Bolt.diy!
## Table of Contents
https://thinktank.ottomator.ai
- [Join the Community](#join-the-community)
- [Requested Additions](#requested-additions)
- [Features](#features)
- [Setup](#setup)
- [Run the Application](#run-the-application)
- [Available Scripts](#available-scripts)
- [Contributing](#contributing)
- [Roadmap](#roadmap)
- [FAQ](#faq)
## Join the community
[Join the bolt.diy community here, in the thinktank on ottomator.ai!](https://thinktank.ottomator.ai)
## Requested Additions - Feel Free to Contribute!
## Requested Additions
- ✅ OpenRouter Integration (@coleam00)
- ✅ Gemini Integration (@jonathands)
- ✅ Autogenerate Ollama models from what is downloaded (@yunatamos)
- ✅ Filter models by provider (@jasonm23)
- ✅ Download project as ZIP (@fabwaseem)
- ✅ Improvements to the main Bolt.new prompt in `app\lib\.server\llm\prompts.ts` (@kofi-bhr)
- ✅ Improvements to the main bolt.new prompt in `app\lib\.server\llm\prompts.ts` (@kofi-bhr)
- ✅ DeepSeek API Integration (@zenith110)
- ✅ Mistral API Integration (@ArulGandhi)
- ✅ "Open AI Like" API Integration (@ZerxZ)
@@ -43,8 +56,15 @@ https://thinktank.ottomator.ai
- ✅ Mobile friendly (@qwikode)
- ✅ Better prompt enhancing (@SujalXplores)
- ✅ Attach images to prompts (@atrokhym)
-Detect package.json and commands to auto install and run preview for folder and git import (@wonderwhy-er)
- **HIGH PRIORITY** - Prevent Bolt from rewriting files as often (file locking and diffs)
-Added Git Clone button (@thecodacus)
- ✅ Git Import from url (@thecodacus)
- ✅ PromptLibrary to have different variations of prompts for different use cases (@thecodacus)
- ✅ Detect package.json and commands to auto install & run preview for folder and git import (@wonderwhy-er)
- ✅ Selection tool to target changes visually (@emcconnell)
- ✅ Detect terminal Errors and ask bolt to fix it (@thecodacus)
- ✅ Detect preview Errors and ask bolt to fix it (@wonderwhy-er)
- ✅ Add Starter Template Options (@thecodacus)
-**HIGH PRIORITY** - Prevent bolt from rewriting files as often (file locking and diffs)
-**HIGH PRIORITY** - Better prompting for smaller LLMs (code window sometimes doesn't start)
-**HIGH PRIORITY** - Run agents in the backend as opposed to a single model call
- ⬜ Deploy directly to Vercel/Netlify/other similar platforms
@@ -53,190 +73,254 @@ https://thinktank.ottomator.ai
- ⬜ Upload documents for knowledge - UI design templates, a code base to reference coding style, etc.
- ⬜ Voice prompting
- ⬜ Azure Open AI API Integration
- Perplexity Integration
- Perplexity Integration (@meetpateltech)
- ⬜ Vertex AI Integration
## Bolt.new: AI-Powered Full-Stack Web Development in the Browser
## Features
Bolt.new (and by extension Bolt.diy) 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)
## What Makes Bolt.new Different
Claude, v0, etc are incredible- but you can't install packages, run backends, or edit code. Thats where Bolt.new stands out:
- **Full-Stack in the Browser**: Bolt.new integrates cutting-edge AI models with an in-browser development environment powered by **StackBlitzs WebContainers**. This allows you to:
- Install and run npm tools and libraries (like Vite, Next.js, and more)
- Run Node.js servers
- Interact with third-party APIs
- Deploy to production from chat
- Share your work via a URL
- **AI with Environment Control**: Unlike traditional dev environments where the AI can only assist in code generation, Bolt.new gives AI models **complete control** over the entire environment including the filesystem, node server, package manager, terminal, and browser console. This empowers AI agents to handle the whole app lifecycle—from creation to deployment.
Whether youre an experienced developer, a PM, or a designer, Bolt.new allows you to easily build production-grade full-stack applications.
For developers interested in building their own AI-powered development tools with WebContainers, check out the open-source Bolt codebase in this repo!
- **AI-powered full-stack web development** directly in your browser.
- **Support for multiple LLMs** with an extensible architecture to integrate additional models.
- **Attach images to prompts** for better contextual understanding.
- **Integrated terminal** to view output of LLM-run commands.
- **Revert code to earlier versions** for easier debugging and quicker changes.
- **Download projects as ZIP** for easy portability.
- **Integration-ready Docker support** for a hassle-free setup.
## Setup
Many of you are new users to installing software from Github. If you have any installation troubles reach out and submit an "issue" using the links above, or feel free to enhance this documentation by forking, editing the instructions, and doing a pull request.
If you're new to installing software from GitHub, don't worry! If you encounter any issues, feel free to submit an "issue" using the provided links or improve this documentation by forking the repository, editing the instructions, and submitting a pull request. The following instruction will help you get the stable branch up and running on your local machine in no time.
1. Install Git from https://git-scm.com/downloads
Let's get you up and running with the stable version of Bolt.DIY!
2. Install Node.js from https://nodejs.org/en/download/
## Quick Download
Pay attention to the installer notes after completion.
[![Download Latest Release](https://img.shields.io/github/v/release/stackblitz-labs/bolt.diy?label=Download%20Bolt&sort=semver)](https://github.com/stackblitz-labs/bolt.diy/releases/latest) ← Click here to go the the latest release version!
On all operating systems, the path to Node.js should automatically be added to your system path. But you can check your path if you want to be sure. On Windows, you can search for "edit the system environment variables" in your system, select "Environment Variables..." once you are in the system properties, and then check for a path to Node in your "Path" system variable. On a Mac or Linux machine, it will tell you to check if /usr/local/bin is in your $PATH. To determine if usr/local/bin is included in $PATH open your Terminal and run:
- Next **click source.zip**
```
echo $PATH .
```
If you see usr/local/bin in the output then you're good to go.
3. Clone the repository (if you haven't already) by opening a Terminal window (or CMD with admin permissions) and then typing in this:
```
git clone https://github.com/stackblitz-labs/bolt.diy.git
```
## Prerequisites
3. Rename .env.example to .env.local and add your LLM API keys. You will find this file on a Mac at "[your name]/bold.new-any-llm/.env.example". For Windows and Linux the path will be similar.
Before you begin, you'll need to install two important pieces of software:
![image](https://github.com/user-attachments/assets/7e6a532c-2268-401f-8310-e8d20c731328)
### Install Node.js
If you can't see the file indicated above, its likely you can't view hidden files. On Mac, open a Terminal window and enter this command below. On Windows, you will see the hidden files option in File Explorer Settings. A quick Google search will help you if you are stuck here.
```
defaults write com.apple.finder AppleShowAllFiles YES
```
**NOTE**: you only have to set the ones you want to use and Ollama doesn't need an API key because it runs locally on your computer:
Get your GROQ API Key here: https://console.groq.com/keys
Get your Open AI API Key by following these instructions: https://help.openai.com/en/articles/4936850-where-do-i-find-my-openai-api-key
Get your Anthropic API Key in your account settings: https://console.anthropic.com/settings/keys
```
GROQ_API_KEY=XXX
OPENAI_API_KEY=XXX
ANTHROPIC_API_KEY=XXX
```
Optionally, you can set the debug level:
```
VITE_LOG_LEVEL=debug
```
And if using Ollama set the DEFAULT_NUM_CTX, the example below uses 8K context and ollama running on localhost port 11434:
```
OLLAMA_API_BASE_URL=http://localhost:11434
DEFAULT_NUM_CTX=8192
```
**Important**: Never commit your `.env.local` file to version control. It's already included in .gitignore.
## Run with Docker
Prerequisites:
Git and Node.js as mentioned above, as well as Docker: https://www.docker.com/
### 1a. Using Helper Scripts
NPM scripts are provided for convenient building:
Node.js is required to run the application.
1. Visit the [Node.js Download Page](https://nodejs.org/en/download/)
2. Download the "LTS" (Long Term Support) version for your operating system
3. Run the installer, accepting the default settings
4. Verify Node.js is properly installed:
- **For Windows Users**:
1. Press `Windows + R`
2. Type "sysdm.cpl" and press Enter
3. Go to "Advanced" tab → "Environment Variables"
4. Check if `Node.js` appears in the "Path" variable
- **For Mac/Linux Users**:
1. Open Terminal
2. Type this command:
```bash
# Development build
npm run dockerbuild
# Production build
npm run dockerbuild:prod
echo $PATH
```
3. Look for `/usr/local/bin` in the output
### 1b. Direct Docker Build Commands (alternative to using NPM scripts)
## Running the Application
You can use Docker's target feature to specify the build environment instead of using NPM scripts if you wish:
You have two options for running Bolt.DIY: directly on your machine or using Docker.
### Option 1: Direct Installation (Recommended for Beginners)
1. **Install Package Manager (pnpm)**:
```bash
# Development build
docker build . --target bolt-ai-development
# Production build
docker build . --target bolt-ai-production
npm install -g pnpm
```
### 2. Docker Compose with Profiles to Run the Container
Use Docker Compose profiles to manage different environments:
2. **Install Project Dependencies**:
```bash
# Development environment
docker-compose --profile development up
# Production environment
docker-compose --profile production up
```
When you run the Docker Compose command with the development profile, any changes you
make on your machine to the code will automatically be reflected in the site running
on the container (i.e. hot reloading still applies!).
## Run Without Docker
1. Install dependencies using Terminal (or CMD in Windows with admin permissions):
```
pnpm install
```
If you get an error saying "command not found: pnpm" or similar, then that means pnpm isn't installed. You can install it via this:
```
sudo npm install -g pnpm
```
2. Start the application with the command:
3. **Start the Application**:
```bash
pnpm run dev
```
**Important Note**: If you're using Google Chrome, you'll need Chrome Canary for local development. [Download it here](https://www.google.com/chrome/canary/)
### Option 2: Using Docker
This option requires some familiarity with Docker but provides a more isolated environment.
#### Additional Prerequisite
- Install Docker: [Download Docker](https://www.docker.com/)
#### Steps:
1. **Build the Docker Image**:
```bash
# Using npm script:
npm run dockerbuild
# OR using direct Docker command:
docker build . --target bolt-ai-development
```
2. **Run the Container**:
```bash
docker-compose --profile development up
```
## Configuring API Keys and Providers
### Adding Your API Keys
Setting up your API keys in Bolt.DIY is straightforward:
1. Open the home page (main interface)
2. Select your desired provider from the dropdown menu
3. Click the pencil (edit) icon
4. Enter your API key in the secure input field
![API Key Configuration Interface](./docs/images/api-key-ui-section.png)
### Configuring Custom Base URLs
For providers that support custom base URLs (such as Ollama or LM Studio), follow these steps:
1. Click the settings icon in the sidebar to open the settings menu
![Settings Button Location](./docs/images/bolt-settings-button.png)
2. Navigate to the "Providers" tab
3. Search for your provider using the search bar
4. Enter your custom base URL in the designated field
![Provider Base URL Configuration](./docs/images/provider-base-url.png)
> **Note**: Custom base URLs are particularly useful when running local instances of AI models or using custom API endpoints.
### Supported Providers
- Ollama
- LM Studio
- OpenAILike
## Setup Using Git (For Developers only)
This method is recommended for developers who want to:
- Contribute to the project
- Stay updated with the latest changes
- Switch between different versions
- Create custom modifications
#### Prerequisites
1. Install Git: [Download Git](https://git-scm.com/downloads)
#### Initial Setup
1. **Clone the Repository**:
```bash
# Using HTTPS
git clone https://github.com/stackblitz-labs/bolt.diy.git
```
2. **Navigate to Project Directory**:
```bash
cd bolt.diy
```
3. **Switch to the Main Branch**:
```bash
git checkout main
```
4. **Install Dependencies**:
```bash
pnpm install
```
5. **Start the Development Server**:
```bash
pnpm run dev
```
#### Staying Updated
To get the latest changes from the repository:
1. **Save Your Local Changes** (if any):
```bash
git stash
```
2. **Pull Latest Updates**:
```bash
git pull origin main
```
3. **Update Dependencies**:
```bash
pnpm install
```
4. **Restore Your Local Changes** (if any):
```bash
git stash pop
```
#### Troubleshooting Git Setup
If you encounter issues:
1. **Clean Installation**:
```bash
# Remove node modules and lock files
rm -rf node_modules pnpm-lock.yaml
# Clear pnpm cache
pnpm store prune
# Reinstall dependencies
pnpm install
```
2. **Reset Local Changes**:
```bash
# Discard all local changes
git reset --hard origin/main
```
Remember to always commit your local changes or stash them before pulling updates to avoid conflicts.
---
## Available Scripts
- `pnpm run dev`: Starts the development server.
- `pnpm run build`: Builds the project.
- `pnpm run start`: Runs the built application locally using Wrangler Pages. This script uses `bindings.sh` to set up necessary bindings so you don't have to duplicate environment variables.
- `pnpm run preview`: Builds the project and then starts it locally, useful for testing the production build. Note, HTTP streaming currently doesn't work as expected with `wrangler pages dev`.
- `pnpm test`: Runs the test suite using Vitest.
- `pnpm run typecheck`: Runs TypeScript type checking.
- `pnpm run typegen`: Generates TypeScript types using Wrangler.
- `pnpm run deploy`: Builds the project and deploys it to Cloudflare Pages.
- `pnpm run lint:fix`: Runs the linter and automatically fixes issues according to your ESLint configuration.
- **`pnpm run dev`**: Starts the development server.
- **`pnpm run build`**: Builds the project.
- **`pnpm run start`**: Runs the built application locally using Wrangler Pages.
- **`pnpm run preview`**: Builds and runs the production build locally.
- **`pnpm test`**: Runs the test suite using Vitest.
- **`pnpm run typecheck`**: Runs TypeScript type checking.
- **`pnpm run typegen`**: Generates TypeScript types using Wrangler.
- **`pnpm run deploy`**: Deploys the project to Cloudflare Pages.
- **`pnpm run lint:fix`**: Automatically fixes linting issues.
## Development
---
To start the development server:
## Contributing
```bash
pnpm run dev
```
We welcome contributions! Check out our [Contributing Guide](CONTRIBUTING.md) to get started.
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.
---
## How do I contribute to Bolt.diy?
## Roadmap
[Please check out our dedicated page for contributing to Bolt.diy here!](CONTRIBUTING.md)
Explore upcoming features and priorities on our [Roadmap](https://roadmap.sh/r/ottodev-roadmap-2ovzo).
## What are the future plans for Bolt.diy?
[Check out our Roadmap here!](https://roadmap.sh/r/ottodev-roadmap-2ovzo)
Lot more updates to this roadmap coming soon!
---
## FAQ
[Please check out our dedicated page for FAQ's related to Bolt.diy here!](FAQ.md)
For answers to common questions, issues, and to see a list of recommended models, visit our [FAQ Page](FAQ.md).

View File

@@ -1 +0,0 @@
{ "commit": "27fcd03db6e7d42d36ffb409e263857f4b05e063" }

View File

@@ -1,6 +1,7 @@
import React, { useState } from 'react';
import { IconButton } from '~/components/ui/IconButton';
import type { ProviderInfo } from '~/types/model';
import Cookies from 'js-cookie';
interface APIKeyManagerProps {
provider: ProviderInfo;
@@ -10,6 +11,23 @@ interface APIKeyManagerProps {
labelForGetApiKey?: string;
}
const apiKeyMemoizeCache: { [k: string]: Record<string, string> } = {};
export function getApiKeysFromCookies() {
const storedApiKeys = Cookies.get('apiKeys');
let parsedKeys = {};
if (storedApiKeys) {
parsedKeys = apiKeyMemoizeCache[storedApiKeys];
if (!parsedKeys) {
parsedKeys = apiKeyMemoizeCache[storedApiKeys] = JSON.parse(storedApiKeys);
}
}
return parsedKeys;
}
// eslint-disable-next-line @typescript-eslint/naming-convention
export const APIKeyManager: React.FC<APIKeyManagerProps> = ({ provider, apiKey, setApiKey }) => {
const [isEditing, setIsEditing] = useState(false);

View File

@@ -1,13 +1,30 @@
import { memo } from 'react';
import { Markdown } from './Markdown';
import type { JSONValue } from 'ai';
interface AssistantMessageProps {
content: string;
annotations?: JSONValue[];
}
export const AssistantMessage = memo(({ content }: AssistantMessageProps) => {
export const AssistantMessage = memo(({ content, annotations }: AssistantMessageProps) => {
const filteredAnnotations = (annotations?.filter(
(annotation: JSONValue) => annotation && typeof annotation === 'object' && Object.keys(annotation).includes('type'),
) || []) as { type: string; value: any }[];
const usage: {
completionTokens: number;
promptTokens: number;
totalTokens: number;
} = filteredAnnotations.find((annotation) => annotation.type === 'usage')?.value;
return (
<div className="overflow-hidden w-full">
{usage && (
<div className="text-sm text-bolt-elements-textSecondary mb-2">
Tokens: {usage.totalTokens} (prompt: {usage.promptTokens}, completion: {usage.completionTokens})
</div>
)}
<Markdown html>{content}</Markdown>
</div>
);

View File

@@ -3,7 +3,7 @@
* Preventing TS checks with files presented in the video for a better presentation.
*/
import type { Message } from 'ai';
import React, { type RefCallback, useEffect, useState } from 'react';
import React, { type RefCallback, useCallback, useEffect, useState } from 'react';
import { ClientOnly } from 'remix-utils/client-only';
import { Menu } from '~/components/sidebar/Menu.client';
import { IconButton } from '~/components/ui/IconButton';
@@ -12,7 +12,7 @@ import { classNames } from '~/utils/classNames';
import { MODEL_LIST, PROVIDER_LIST, initializeModelList } from '~/utils/constants';
import { Messages } from './Messages.client';
import { SendButton } from './SendButton.client';
import { APIKeyManager } from './APIKeyManager';
import { APIKeyManager, getApiKeysFromCookies } from './APIKeyManager';
import Cookies from 'js-cookie';
import * as Tooltip from '@radix-ui/react-tooltip';
@@ -26,6 +26,12 @@ import FilePreview from './FilePreview';
import { ModelSelector } from '~/components/chat/ModelSelector';
import { SpeechRecognitionButton } from '~/components/chat/SpeechRecognition';
import type { IProviderSetting, ProviderInfo } from '~/types/model';
import { ScreenshotStateManager } from './ScreenshotStateManager';
import { toast } from 'react-toastify';
import StarterTemplates from './StarterTemplates';
import type { ActionAlert } from '~/types/actions';
import ChatAlert from './ChatAlert';
import { LLMManager } from '~/lib/modules/llm/manager';
const TEXTAREA_MIN_HEIGHT = 76;
@@ -56,6 +62,8 @@ interface BaseChatProps {
setUploadedFiles?: (files: File[]) => void;
imageDataList?: string[];
setImageDataList?: (dataList: string[]) => void;
actionAlert?: ActionAlert;
clearAlert?: () => void;
}
export const BaseChat = React.forwardRef<HTMLDivElement, BaseChatProps>(
@@ -75,7 +83,8 @@ export const BaseChat = React.forwardRef<HTMLDivElement, BaseChatProps>(
input = '',
enhancingPrompt,
handleInputChange,
promptEnhanced,
// promptEnhanced,
enhancePrompt,
sendMessage,
handleStop,
@@ -86,53 +95,21 @@ export const BaseChat = React.forwardRef<HTMLDivElement, BaseChatProps>(
imageDataList = [],
setImageDataList,
messages,
actionAlert,
clearAlert,
},
ref,
) => {
const TEXTAREA_MAX_HEIGHT = chatStarted ? 400 : 200;
const [apiKeys, setApiKeys] = useState<Record<string, string>>(() => {
const savedKeys = Cookies.get('apiKeys');
if (savedKeys) {
try {
return JSON.parse(savedKeys);
} catch (error) {
console.error('Failed to parse API keys from cookies:', error);
return {};
}
}
return {};
});
const [apiKeys, setApiKeys] = useState<Record<string, string>>(getApiKeysFromCookies());
const [modelList, setModelList] = useState(MODEL_LIST);
const [isModelSettingsCollapsed, setIsModelSettingsCollapsed] = useState(false);
const [isListening, setIsListening] = useState(false);
const [recognition, setRecognition] = useState<SpeechRecognition | null>(null);
const [transcript, setTranscript] = useState('');
const [isModelLoading, setIsModelLoading] = useState<string | undefined>('all');
useEffect(() => {
console.log(transcript);
}, [transcript]);
useEffect(() => {
// Load API keys from cookies on component mount
try {
const storedApiKeys = Cookies.get('apiKeys');
if (storedApiKeys) {
const parsedKeys = JSON.parse(storedApiKeys);
if (typeof parsedKeys === 'object' && parsedKeys !== null) {
setApiKeys(parsedKeys);
}
}
} catch (error) {
console.error('Error loading API keys from cookies:', error);
// Clear invalid cookie data
Cookies.remove('apiKeys');
}
const getProviderSettings = useCallback(() => {
let providerSettings: Record<string, IProviderSetting> | undefined = undefined;
try {
@@ -152,10 +129,13 @@ export const BaseChat = React.forwardRef<HTMLDivElement, BaseChatProps>(
Cookies.remove('providers');
}
initializeModelList(providerSettings).then((modelList) => {
setModelList(modelList);
});
return providerSettings;
}, []);
useEffect(() => {
console.log(transcript);
}, [transcript]);
useEffect(() => {
if (typeof window !== 'undefined' && ('SpeechRecognition' in window || 'webkitSpeechRecognition' in window)) {
const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;
const recognition = new SpeechRecognition();
@@ -187,6 +167,65 @@ export const BaseChat = React.forwardRef<HTMLDivElement, BaseChatProps>(
}
}, []);
useEffect(() => {
if (typeof window !== 'undefined') {
const providerSettings = getProviderSettings();
let parsedApiKeys: Record<string, string> | undefined = {};
try {
parsedApiKeys = getApiKeysFromCookies();
setApiKeys(parsedApiKeys);
} catch (error) {
console.error('Error loading API keys from cookies:', error);
// Clear invalid cookie data
Cookies.remove('apiKeys');
}
setIsModelLoading('all');
initializeModelList({ apiKeys: parsedApiKeys, providerSettings })
.then((modelList) => {
// console.log('Model List: ', modelList);
setModelList(modelList);
})
.catch((error) => {
console.error('Error initializing model list:', error);
})
.finally(() => {
setIsModelLoading(undefined);
});
}
}, [providerList]);
const onApiKeysChange = async (providerName: string, apiKey: string) => {
const newApiKeys = { ...apiKeys, [providerName]: apiKey };
setApiKeys(newApiKeys);
Cookies.set('apiKeys', JSON.stringify(newApiKeys));
const provider = LLMManager.getInstance(import.meta.env || process.env || {}).getProvider(providerName);
if (provider && provider.getDynamicModels) {
setIsModelLoading(providerName);
try {
const providerSettings = getProviderSettings();
const staticModels = provider.staticModels;
const dynamicModels = await provider.getDynamicModels(
newApiKeys,
providerSettings,
import.meta.env || process.env || {},
);
setModelList((preModels) => {
const filteredOutPreModels = preModels.filter((x) => x.provider !== providerName);
return [...filteredOutPreModels, ...staticModels, ...dynamicModels];
});
} catch (error) {
console.error('Error loading dynamic models:', error);
}
setIsModelLoading(undefined);
}
};
const startListening = () => {
if (recognition) {
recognition.start();
@@ -283,7 +322,7 @@ export const BaseChat = React.forwardRef<HTMLDivElement, BaseChatProps>(
<div ref={scrollRef} className="flex flex-col lg:flex-row overflow-y-auto w-full h-full">
<div className={classNames(styles.Chat, 'flex flex-col flex-grow lg:min-w-[var(--chat-min-width)] h-full')}>
{!chatStarted && (
<div id="intro" className="mt-[26vh] max-w-chat mx-auto text-center px-4 lg:px-0">
<div id="intro" className="mt-[16vh] max-w-chat mx-auto text-center px-4 lg:px-0">
<h1 className="text-3xl lg:text-6xl font-bold text-bolt-elements-textPrimary mb-4 animate-fade-in">
Where ideas begin
</h1>
@@ -310,11 +349,31 @@ export const BaseChat = React.forwardRef<HTMLDivElement, BaseChatProps>(
}}
</ClientOnly>
<div
className={classNames(
'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',
{
className={classNames('flex flex-col gap-4 w-full max-w-chat mx-auto z-prompt mb-6', {
'sticky bottom-2': chatStarted,
},
})}
>
<div className="bg-bolt-elements-background-depth-2">
{actionAlert && (
<ChatAlert
alert={actionAlert}
clearAlert={() => clearAlert?.()}
postMessage={(message) => {
sendMessage?.({} as any, message);
clearAlert?.();
}}
/>
)}
</div>
<div
className={classNames(
'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',
/*
* {
* 'sticky bottom-2': chatStarted,
* },
*/
)}
>
<svg className={classNames(styles.PromptEffectContainer)}>
@@ -344,6 +403,8 @@ export const BaseChat = React.forwardRef<HTMLDivElement, BaseChatProps>(
<rect className={classNames(styles.PromptShine)} x="48" y="24" width="70" height="1"></rect>
</svg>
<div>
<ClientOnly>
{() => (
<div className={isModelSettingsCollapsed ? 'hidden' : ''}>
<ModelSelector
key={provider?.name + ':' + modelList.length}
@@ -352,21 +413,22 @@ export const BaseChat = React.forwardRef<HTMLDivElement, BaseChatProps>(
modelList={modelList}
provider={provider}
setProvider={setProvider}
providerList={providerList || PROVIDER_LIST}
providerList={providerList || (PROVIDER_LIST as ProviderInfo[])}
apiKeys={apiKeys}
modelLoading={isModelLoading}
/>
{(providerList || []).length > 0 && provider && (
<APIKeyManager
provider={provider}
apiKey={apiKeys[provider.name] || ''}
setApiKey={(key) => {
const newApiKeys = { ...apiKeys, [provider.name]: key };
setApiKeys(newApiKeys);
Cookies.set('apiKeys', JSON.stringify(newApiKeys));
onApiKeysChange(provider.name, key);
}}
/>
)}
</div>
)}
</ClientOnly>
</div>
<FilePreview
files={uploadedFiles}
@@ -376,6 +438,16 @@ export const BaseChat = React.forwardRef<HTMLDivElement, BaseChatProps>(
setImageDataList?.(imageDataList.filter((_, i) => i !== index));
}}
/>
<ClientOnly>
{() => (
<ScreenshotStateManager
setUploadedFiles={setUploadedFiles}
setImageDataList={setImageDataList}
uploadedFiles={uploadedFiles}
imageDataList={imageDataList}
/>
)}
</ClientOnly>
<div
className={classNames(
'relative shadow-xs border border-bolt-elements-borderColor backdrop-blur rounded-lg',
@@ -384,7 +456,7 @@ export const BaseChat = React.forwardRef<HTMLDivElement, BaseChatProps>(
<textarea
ref={textareaRef}
className={classNames(
'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',
'w-full pl-4 pt-4 pr-16 outline-none resize-none text-bolt-elements-textPrimary placeholder-bolt-elements-textTertiary bg-transparent text-sm',
'transition-all duration-200',
'hover:border-bolt-elements-focus',
)}
@@ -431,6 +503,11 @@ export const BaseChat = React.forwardRef<HTMLDivElement, BaseChatProps>(
return;
}
// ignore if using input method engine
if (event.nativeEvent.isComposing) {
return;
}
handleSendMessage?.(event);
}
}}
@@ -473,25 +550,16 @@ export const BaseChat = React.forwardRef<HTMLDivElement, BaseChatProps>(
<IconButton
title="Enhance prompt"
disabled={input.length === 0 || enhancingPrompt}
className={classNames(
'transition-all',
enhancingPrompt ? 'opacity-100' : '',
promptEnhanced ? 'text-bolt-elements-item-contentAccent' : '',
promptEnhanced ? 'pr-1.5' : '',
promptEnhanced ? 'enabled:hover:bg-bolt-elements-item-backgroundAccent' : '',
)}
onClick={() => enhancePrompt?.()}
className={classNames('transition-all', enhancingPrompt ? 'opacity-100' : '')}
onClick={() => {
enhancePrompt?.();
toast.success('Prompt enhanced!');
}}
>
{enhancingPrompt ? (
<>
<div className="i-svg-spinners:90-ring-with-bg text-bolt-elements-loader-progress text-xl animate-spin"></div>
<div className="ml-1.5">Enhancing prompt...</div>
</>
) : (
<>
<div className="i-bolt:stars text-xl"></div>
{promptEnhanced && <div className="ml-1.5">Prompt enhanced</div>}
</>
)}
</IconButton>
@@ -519,15 +587,17 @@ export const BaseChat = React.forwardRef<HTMLDivElement, BaseChatProps>(
</div>
{input.length > 3 ? (
<div className="text-xs text-bolt-elements-textTertiary">
Use <kbd className="kdb px-1.5 py-0.5 rounded bg-bolt-elements-background-depth-2">Shift</kbd> +{' '}
<kbd className="kdb px-1.5 py-0.5 rounded bg-bolt-elements-background-depth-2">Return</kbd> a
new line
Use <kbd className="kdb px-1.5 py-0.5 rounded bg-bolt-elements-background-depth-2">Shift</kbd>{' '}
+ <kbd className="kdb px-1.5 py-0.5 rounded bg-bolt-elements-background-depth-2">Return</kbd>{' '}
a new line
</div>
) : null}
</div>
</div>
</div>
</div>
</div>
<div className="flex flex-col justify-center gap-5">
{!chatStarted && (
<div className="flex justify-center gap-2">
{ImportButtons(importChat)}
@@ -543,6 +613,8 @@ export const BaseChat = React.forwardRef<HTMLDivElement, BaseChatProps>(
handleSendMessage?.(event, messageInput);
})}
{!chatStarted && <StarterTemplates />}
</div>
</div>
<ClientOnly>{() => <Workbench chatStarted={chatStarted} isStreaming={isStreaming} />}</ClientOnly>
</div>

View File

@@ -20,6 +20,9 @@ import Cookies from 'js-cookie';
import { debounce } from '~/utils/debounce';
import { useSettings } from '~/lib/hooks/useSettings';
import type { ProviderInfo } from '~/types/model';
import { useSearchParams } from '@remix-run/react';
import { createSampler } from '~/utils/sampler';
import { getTemplates, selectStarterTemplate } from '~/utils/selectStarterTemplate';
const toastAnimation = cssTransition({
enter: 'animated fadeInRight',
@@ -33,6 +36,9 @@ export function Chat() {
const { ready, initialMessages, storeMessageHistory, importChat, exportChat } = useChatHistory();
const title = useStore(description);
useEffect(() => {
workbenchStore.setReloadedMessages(initialMessages.map((m) => m.id));
}, [initialMessages]);
return (
<>
@@ -76,6 +82,24 @@ export function Chat() {
);
}
const processSampledMessages = createSampler(
(options: {
messages: Message[];
initialMessages: Message[];
isLoading: boolean;
parseMessages: (messages: Message[], isLoading: boolean) => void;
storeMessageHistory: (messages: Message[]) => Promise<void>;
}) => {
const { messages, initialMessages, isLoading, parseMessages, storeMessageHistory } = options;
parseMessages(messages, isLoading);
if (messages.length > initialMessages.length) {
storeMessageHistory(messages).catch((error) => toast.error(error.message));
}
},
50,
);
interface ChatProps {
initialMessages: Message[];
storeMessageHistory: (messages: Message[]) => Promise<void>;
@@ -92,7 +116,11 @@ export const ChatImpl = memo(
const [chatStarted, setChatStarted] = useState(initialMessages.length > 0);
const [uploadedFiles, setUploadedFiles] = useState<File[]>([]); // Move here
const [imageDataList, setImageDataList] = useState<string[]>([]); // Move here
const { activeProviders } = useSettings();
const [searchParams, setSearchParams] = useSearchParams();
const [fakeLoading, setFakeLoading] = useState(false);
const files = useStore(workbenchStore.files);
const actionAlert = useStore(workbenchStore.alert);
const { activeProviders, promptId, autoSelectTemplate, contextOptimizationEnabled } = useSettings();
const [model, setModel] = useState(() => {
const savedModel = Cookies.get('selectedModel');
@@ -100,7 +128,7 @@ export const ChatImpl = memo(
});
const [provider, setProvider] = useState(() => {
const savedProvider = Cookies.get('selectedProvider');
return PROVIDER_LIST.find((p) => p.name === savedProvider) || DEFAULT_PROVIDER;
return (PROVIDER_LIST.find((p) => p.name === savedProvider) || DEFAULT_PROVIDER) as ProviderInfo;
});
const { showChat } = useStore(chatStore);
@@ -109,23 +137,54 @@ export const ChatImpl = memo(
const [apiKeys, setApiKeys] = useState<Record<string, string>>({});
const { messages, isLoading, input, handleInputChange, setInput, stop, append } = useChat({
const { messages, isLoading, input, handleInputChange, setInput, stop, append, setMessages, reload } = useChat({
api: '/api/chat',
body: {
apiKeys,
files,
promptId,
contextOptimization: contextOptimizationEnabled,
},
sendExtraMessageFields: true,
onError: (error) => {
logger.error('Request failed\n\n', error);
toast.error(
'There was an error processing your request: ' + (error.message ? error.message : 'No details were returned'),
);
},
onFinish: () => {
onFinish: (message, response) => {
const usage = response.usage;
if (usage) {
console.log('Token usage:', usage);
// You can now use the usage data as needed
}
logger.debug('Finished streaming');
},
initialMessages,
initialInput: Cookies.get(PROMPT_COOKIE_KEY) || '',
});
useEffect(() => {
const prompt = searchParams.get('prompt');
// console.log(prompt, searchParams, model, provider);
if (prompt) {
setSearchParams({});
runAnimation();
append({
role: 'user',
content: [
{
type: 'text',
text: `[Model: ${model}]\n\n[Provider: ${provider.name}]\n\n${prompt}`,
},
] as any, // Type assertion to bypass compiler check
});
}
}, [model, provider, searchParams]);
const { enhancingPrompt, promptEnhanced, enhancePrompt, resetEnhancer } = usePromptEnhancer();
const { parsedMessages, parseMessages } = useMessageParser();
@@ -137,11 +196,13 @@ export const ChatImpl = memo(
}, []);
useEffect(() => {
parseMessages(messages, isLoading);
if (messages.length > initialMessages.length) {
storeMessageHistory(messages).catch((error) => toast.error(error.message));
}
processSampledMessages({
messages,
initialMessages,
isLoading,
parseMessages,
storeMessageHistory,
});
}, [messages, isLoading, parseMessages]);
const scrollTextArea = () => {
@@ -208,6 +269,110 @@ export const ChatImpl = memo(
runAnimation();
if (!chatStarted && messageInput && autoSelectTemplate) {
setFakeLoading(true);
setMessages([
{
id: `${new Date().getTime()}`,
role: 'user',
content: [
{
type: 'text',
text: `[Model: ${model}]\n\n[Provider: ${provider.name}]\n\n${_input}`,
},
...imageDataList.map((imageData) => ({
type: 'image',
image: imageData,
})),
] as any, // Type assertion to bypass compiler check
},
]);
// reload();
const { template, title } = await selectStarterTemplate({
message: messageInput,
model,
provider,
});
if (template !== 'blank') {
const temResp = await getTemplates(template, title);
if (temResp) {
const { assistantMessage, userMessage } = temResp;
setMessages([
{
id: `${new Date().getTime()}`,
role: 'user',
content: messageInput,
// annotations: ['hidden'],
},
{
id: `${new Date().getTime()}`,
role: 'assistant',
content: assistantMessage,
},
{
id: `${new Date().getTime()}`,
role: 'user',
content: `[Model: ${model}]\n\n[Provider: ${provider.name}]\n\n${userMessage}`,
annotations: ['hidden'],
},
]);
reload();
setFakeLoading(false);
return;
} else {
setMessages([
{
id: `${new Date().getTime()}`,
role: 'user',
content: [
{
type: 'text',
text: `[Model: ${model}]\n\n[Provider: ${provider.name}]\n\n${_input}`,
},
...imageDataList.map((imageData) => ({
type: 'image',
image: imageData,
})),
] as any, // Type assertion to bypass compiler check
},
]);
reload();
setFakeLoading(false);
return;
}
} else {
setMessages([
{
id: `${new Date().getTime()}`,
role: 'user',
content: [
{
type: 'text',
text: `[Model: ${model}]\n\n[Provider: ${provider.name}]\n\n${_input}`,
},
...imageDataList.map((imageData) => ({
type: 'image',
image: imageData,
})),
] as any, // Type assertion to bypass compiler check
},
]);
reload();
setFakeLoading(false);
return;
}
}
if (fileModifications !== undefined) {
/**
* If we have file modifications we append a new user message manually since we have to prefix
@@ -310,7 +475,7 @@ export const ChatImpl = memo(
input={input}
showChat={showChat}
chatStarted={chatStarted}
isStreaming={isLoading}
isStreaming={isLoading || fakeLoading}
enhancingPrompt={enhancingPrompt}
promptEnhanced={promptEnhanced}
sendMessage={sendMessage}
@@ -355,6 +520,8 @@ export const ChatImpl = memo(
setUploadedFiles={setUploadedFiles}
imageDataList={imageDataList}
setImageDataList={setImageDataList}
actionAlert={actionAlert}
clearAlert={() => workbenchStore.clearAlert()}
/>
);
},

View File

@@ -0,0 +1,108 @@
import { AnimatePresence, motion } from 'framer-motion';
import type { ActionAlert } from '~/types/actions';
import { classNames } from '~/utils/classNames';
interface Props {
alert: ActionAlert;
clearAlert: () => void;
postMessage: (message: string) => void;
}
export default function ChatAlert({ alert, clearAlert, postMessage }: Props) {
const { description, content, source } = alert;
const isPreview = source === 'preview';
const title = isPreview ? 'Preview Error' : 'Terminal Error';
const message = isPreview
? 'We encountered an error while running the preview. Would you like Bolt to analyze and help resolve this issue?'
: 'We encountered an error while running terminal commands. Would you like Bolt to analyze and help resolve this issue?';
return (
<AnimatePresence>
<motion.div
initial={{ opacity: 0, y: -20 }}
animate={{ opacity: 1, y: 0 }}
exit={{ opacity: 0, y: -20 }}
transition={{ duration: 0.3 }}
className={`rounded-lg border border-bolt-elements-borderColor bg-bolt-elements-background-depth-2 p-4`}
>
<div className="flex items-start">
{/* Icon */}
<motion.div
className="flex-shrink-0"
initial={{ scale: 0 }}
animate={{ scale: 1 }}
transition={{ delay: 0.2 }}
>
<div className={`i-ph:warning-duotone text-xl text-bolt-elements-button-danger-text`}></div>
</motion.div>
{/* Content */}
<div className="ml-3 flex-1">
<motion.h3
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
transition={{ delay: 0.1 }}
className={`text-sm font-medium text-bolt-elements-textPrimary`}
>
{title}
</motion.h3>
<motion.div
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
transition={{ delay: 0.2 }}
className={`mt-2 text-sm text-bolt-elements-textSecondary`}
>
<p>{message}</p>
{description && (
<div className="text-xs text-bolt-elements-textSecondary p-2 bg-bolt-elements-background-depth-3 rounded mt-4 mb-4">
Error: {description}
</div>
)}
</motion.div>
{/* Actions */}
<motion.div
className="mt-4"
initial={{ opacity: 0, y: 10 }}
animate={{ opacity: 1, y: 0 }}
transition={{ delay: 0.3 }}
>
<div className={classNames(' flex gap-2')}>
<button
onClick={() =>
postMessage(
`*Fix this ${isPreview ? 'preview' : 'terminal'} error* \n\`\`\`${isPreview ? 'js' : 'sh'}\n${content}\n\`\`\`\n`,
)
}
className={classNames(
`px-2 py-1.5 rounded-md text-sm font-medium`,
'bg-bolt-elements-button-primary-background',
'hover:bg-bolt-elements-button-primary-backgroundHover',
'focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-bolt-elements-button-danger-background',
'text-bolt-elements-button-primary-text',
'flex items-center gap-1.5',
)}
>
<div className="i-ph:chat-circle-duotone"></div>
Ask Bolt
</button>
<button
onClick={clearAlert}
className={classNames(
`px-2 py-1.5 rounded-md text-sm font-medium`,
'bg-bolt-elements-button-secondary-background',
'hover:bg-bolt-elements-button-secondary-backgroundHover',
'focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-bolt-elements-button-secondary-background',
'text-bolt-elements-button-secondary-text',
)}
>
Dismiss
</button>
</div>
</motion.div>
</div>
</div>
</motion.div>
</AnimatePresence>
);
}

View File

@@ -53,7 +53,7 @@ export const CodeBlock = memo(
<div
className={classNames(
styles.CopyButtonContainer,
'bg-white absolute top-[10px] right-[10px] rounded-md z-10 text-lg flex items-center justify-center opacity-0 group-hover:opacity-100',
'bg-transparant absolute top-[10px] right-[10px] rounded-md z-10 text-lg flex items-center justify-center opacity-0 group-hover:opacity-100',
{
'rounded-l-0 opacity-100': copied,
},
@@ -62,7 +62,7 @@ export const CodeBlock = memo(
{!disableCopy && (
<button
className={classNames(
'flex items-center bg-transparent p-[6px] justify-center before:bg-white before:rounded-l-md before:text-gray-500 before:border-r before:border-gray-300',
'flex items-center bg-accent-500 p-[6px] justify-center before:bg-white before:rounded-l-md before:text-gray-500 before:border-r before:border-gray-300 rounded-md transition-theme',
{
'before:opacity-0': !copied,
'before:opacity-100': copied,

View File

@@ -1,7 +1,6 @@
import ignore from 'ignore';
import { useGit } from '~/lib/hooks/useGit';
import type { Message } from 'ai';
import WithTooltip from '~/components/ui/Tooltip';
import { detectProjectCommands, createCommandsMessage } from '~/utils/projectCommands';
import { generateId } from '~/utils/fileUtils';
@@ -99,17 +98,13 @@ ${file.content}
};
return (
<WithTooltip tooltip="Clone A Git Repo">
<button
onClick={(e) => {
onClick(e);
}}
title="Clone A Git Repo"
onClick={onClick}
title="Clone a Git Repo"
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"
>
<span className="i-ph:git-branch" />
Clone A Git Repo
Clone a Git Repo
</button>
</WithTooltip>
);
}

View File

@@ -3,6 +3,7 @@ import type { Message } from 'ai';
import { toast } from 'react-toastify';
import { MAX_FILES, isBinaryFile, shouldIncludeFile } from '~/utils/fileUtils';
import { createChatFromFolder } from '~/utils/folderImport';
import { logStore } from '~/lib/stores/logs'; // Assuming logStore is imported from this location
interface ImportFolderButtonProps {
className?: string;
@@ -15,26 +16,40 @@ export const ImportFolderButton: React.FC<ImportFolderButtonProps> = ({ classNam
const handleFileChange = async (e: React.ChangeEvent<HTMLInputElement>) => {
const allFiles = Array.from(e.target.files || []);
if (allFiles.length > MAX_FILES) {
toast.error(
`This folder contains ${allFiles.length.toLocaleString()} files. This product is not yet optimized for very large projects. Please select a folder with fewer than ${MAX_FILES.toLocaleString()} files.`,
);
const filteredFiles = allFiles.filter((file) => {
const path = file.webkitRelativePath.split('/').slice(1).join('/');
const include = shouldIncludeFile(path);
return include;
});
if (filteredFiles.length === 0) {
const error = new Error('No valid files found');
logStore.logError('File import failed - no valid files', error, { folderName: 'Unknown Folder' });
toast.error('No files found in the selected folder');
return;
}
const folderName = allFiles[0]?.webkitRelativePath.split('/')[0] || 'Unknown Folder';
if (filteredFiles.length > MAX_FILES) {
const error = new Error(`Too many files: ${filteredFiles.length}`);
logStore.logError('File import failed - too many files', error, {
fileCount: filteredFiles.length,
maxFiles: MAX_FILES,
});
toast.error(
`This folder contains ${filteredFiles.length.toLocaleString()} files. This product is not yet optimized for very large projects. Please select a folder with fewer than ${MAX_FILES.toLocaleString()} files.`,
);
return;
}
const folderName = filteredFiles[0]?.webkitRelativePath.split('/')[0] || 'Unknown Folder';
setIsLoading(true);
const loadingToast = toast.loading(`Importing ${folderName}...`);
try {
const filteredFiles = allFiles.filter((file) => shouldIncludeFile(file.webkitRelativePath));
if (filteredFiles.length === 0) {
toast.error('No files found in the selected folder');
return;
}
const fileChecks = await Promise.all(
filteredFiles.map(async (file) => ({
file,
@@ -48,11 +63,18 @@ export const ImportFolderButton: React.FC<ImportFolderButtonProps> = ({ classNam
.map((f) => f.file.webkitRelativePath.split('/').slice(1).join('/'));
if (textFiles.length === 0) {
const error = new Error('No text files found');
logStore.logError('File import failed - no text files', error, { folderName });
toast.error('No text files found in the selected folder');
return;
}
if (binaryFilePaths.length > 0) {
logStore.logWarning(`Skipping binary files during import`, {
folderName,
binaryCount: binaryFilePaths.length,
});
toast.info(`Skipping ${binaryFilePaths.length} binary files`);
}
@@ -62,8 +84,14 @@ export const ImportFolderButton: React.FC<ImportFolderButtonProps> = ({ classNam
await importChat(folderName, [...messages]);
}
logStore.logSystem('Folder imported successfully', {
folderName,
textFileCount: textFiles.length,
binaryFileCount: binaryFilePaths.length,
});
toast.success('Folder imported successfully');
} catch (error) {
logStore.logError('Failed to import folder', error, { folderName });
console.error('Failed to import folder:', error);
toast.error('Failed to import folder');
} finally {

View File

@@ -1,5 +1,5 @@
import type { Message } from 'ai';
import React from 'react';
import React, { Fragment } from 'react';
import { classNames } from '~/utils/classNames';
import { AssistantMessage } from './AssistantMessage';
import { UserMessage } from './UserMessage';
@@ -44,10 +44,15 @@ export const Messages = React.forwardRef<HTMLDivElement, MessagesProps>((props:
<div id={id} ref={ref} className={props.className}>
{messages.length > 0
? messages.map((message, index) => {
const { role, content, id: messageId } = message;
const { role, content, id: messageId, annotations } = message;
const isUserMessage = role === 'user';
const isFirst = index === 0;
const isLast = index === messages.length - 1;
const isHidden = annotations?.includes('hidden');
if (isHidden) {
return <Fragment key={index} />;
}
return (
<div
@@ -65,12 +70,16 @@ export const Messages = React.forwardRef<HTMLDivElement, MessagesProps>((props:
</div>
)}
<div className="grid grid-col-1 w-full">
{isUserMessage ? <UserMessage content={content} /> : <AssistantMessage content={content} />}
{isUserMessage ? (
<UserMessage content={content} />
) : (
<AssistantMessage content={content} annotations={message.annotations} />
)}
</div>
{!isUserMessage && (
<div className="flex gap-2 flex-col lg:flex-row">
<WithTooltip tooltip="Revert to this message">
{messageId && (
<WithTooltip tooltip="Revert to this message">
<button
onClick={() => handleRewind(messageId)}
key="i-ph:arrow-u-up-left"
@@ -79,8 +88,8 @@ export const Messages = React.forwardRef<HTMLDivElement, MessagesProps>((props:
'text-xl text-bolt-elements-textSecondary hover:text-bolt-elements-textPrimary transition-colors',
)}
/>
)}
</WithTooltip>
)}
<WithTooltip tooltip="Fork chat from this message">
<button

View File

@@ -1,7 +1,6 @@
import type { ProviderInfo } from '~/types/model';
import type { ModelInfo } from '~/utils/types';
import { useEffect, useState } from 'react';
import Cookies from 'js-cookie';
import { useEffect } from 'react';
import type { ModelInfo } from '~/lib/modules/llm/types';
interface ModelSelectorProps {
model?: string;
@@ -11,6 +10,7 @@ interface ModelSelectorProps {
modelList: ModelInfo[];
providerList: ProviderInfo[];
apiKeys: Record<string, string>;
modelLoading?: string;
}
export const ModelSelector = ({
@@ -20,39 +20,19 @@ export const ModelSelector = ({
setProvider,
modelList,
providerList,
modelLoading,
}: ModelSelectorProps) => {
// Load enabled providers from cookies
const [enabledProviders, setEnabledProviders] = useState(() => {
const savedProviders = Cookies.get('providers');
if (savedProviders) {
try {
const parsedProviders = JSON.parse(savedProviders);
return providerList.filter((p) => parsedProviders[p.name]);
} catch (error) {
console.error('Failed to parse providers from cookies:', error);
return providerList;
}
}
return providerList;
});
// Update enabled providers when cookies change
useEffect(() => {
// Function to update providers from cookies
const updateProvidersFromCookies = () => {
const savedProviders = Cookies.get('providers');
if (savedProviders) {
try {
const parsedProviders = JSON.parse(savedProviders);
const newEnabledProviders = providerList.filter((p) => parsedProviders[p.name]);
setEnabledProviders(newEnabledProviders);
// If current provider is disabled, switch to first enabled provider
if (provider && !parsedProviders[provider.name] && newEnabledProviders.length > 0) {
const firstEnabledProvider = newEnabledProviders[0];
if (providerList.length == 0) {
return;
}
if (provider && !providerList.map((p) => p.name).includes(provider.name)) {
const firstEnabledProvider = providerList[0];
setProvider?.(firstEnabledProvider);
// Also update the model to the first available one for the new provider
@@ -62,22 +42,9 @@ export const ModelSelector = ({
setModel?.(firstModel.name);
}
}
} catch (error) {
console.error('Failed to parse providers from cookies:', error);
}
}
};
// Initial update
updateProvidersFromCookies();
// Set up an interval to check for cookie changes
const interval = setInterval(updateProvidersFromCookies, 1000);
return () => clearInterval(interval);
}, [providerList, provider, setProvider, modelList, setModel]);
if (enabledProviders.length === 0) {
if (providerList.length === 0) {
return (
<div className="mb-2 p-4 rounded-lg border border-bolt-elements-borderColor bg-bolt-elements-prompt-background text-bolt-elements-textPrimary">
<p className="text-center">
@@ -93,7 +60,7 @@ export const ModelSelector = ({
<select
value={provider?.name ?? ''}
onChange={(e) => {
const newProvider = enabledProviders.find((p: ProviderInfo) => p.name === e.target.value);
const newProvider = providerList.find((p: ProviderInfo) => p.name === e.target.value);
if (newProvider && setProvider) {
setProvider(newProvider);
@@ -107,7 +74,7 @@ export const ModelSelector = ({
}}
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"
>
{enabledProviders.map((provider: ProviderInfo) => (
{providerList.map((provider: ProviderInfo) => (
<option key={provider.name} value={provider.name}>
{provider.name}
</option>
@@ -118,14 +85,21 @@ export const ModelSelector = ({
value={model}
onChange={(e) => setModel?.(e.target.value)}
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%]"
disabled={modelLoading === 'all' || modelLoading === provider?.name}
>
{[...modelList]
{modelLoading == 'all' || modelLoading == provider?.name ? (
<option key={0} value="">
Loading...
</option>
) : (
[...modelList]
.filter((e) => e.provider == provider?.name && e.name)
.map((modelOption, index) => (
<option key={index} value={modelOption.name}>
{modelOption.label}
</option>
))}
))
)}
</select>
</div>
);

View File

@@ -0,0 +1,33 @@
import { useEffect } from 'react';
interface ScreenshotStateManagerProps {
setUploadedFiles?: (files: File[]) => void;
setImageDataList?: (dataList: string[]) => void;
uploadedFiles: File[];
imageDataList: string[];
}
export const ScreenshotStateManager = ({
setUploadedFiles,
setImageDataList,
uploadedFiles,
imageDataList,
}: ScreenshotStateManagerProps) => {
useEffect(() => {
if (setUploadedFiles && setImageDataList) {
(window as any).__BOLT_SET_UPLOADED_FILES__ = setUploadedFiles;
(window as any).__BOLT_SET_IMAGE_DATA_LIST__ = setImageDataList;
(window as any).__BOLT_UPLOADED_FILES__ = uploadedFiles;
(window as any).__BOLT_IMAGE_DATA_LIST__ = imageDataList;
}
return () => {
delete (window as any).__BOLT_SET_UPLOADED_FILES__;
delete (window as any).__BOLT_SET_IMAGE_DATA_LIST__;
delete (window as any).__BOLT_UPLOADED_FILES__;
delete (window as any).__BOLT_IMAGE_DATA_LIST__;
};
}, [setUploadedFiles, setImageDataList, uploadedFiles, imageDataList]);
return null;
};

View File

@@ -0,0 +1,37 @@
import React from 'react';
import type { Template } from '~/types/template';
import { STARTER_TEMPLATES } from '~/utils/constants';
interface FrameworkLinkProps {
template: Template;
}
const FrameworkLink: React.FC<FrameworkLinkProps> = ({ template }) => (
<a
href={`/git?url=https://github.com/${template.githubRepo}.git`}
data-state="closed"
data-discover="true"
className="items-center justify-center "
>
<div
className={`inline-block ${template.icon} w-8 h-8 text-4xl transition-theme opacity-25 hover:opacity-75 transition-all`}
/>
</a>
);
const StarterTemplates: React.FC = () => {
return (
<div className="flex flex-col items-center gap-4">
<span className="text-sm text-gray-500">or start a blank app with your favorite stack</span>
<div className="flex justify-center">
<div className="flex w-70 flex-wrap items-center justify-center gap-4">
{STARTER_TEMPLATES.map((template) => (
<FrameworkLink key={template.name} template={template} />
))}
</div>
</div>
</div>
);
};
export default StarterTemplates;

View File

@@ -12,42 +12,36 @@ interface UserMessageProps {
export function UserMessage({ content }: UserMessageProps) {
if (Array.isArray(content)) {
const textItem = content.find((item) => item.type === 'text');
const textContent = sanitizeUserMessage(textItem?.text || '');
const textContent = stripMetadata(textItem?.text || '');
const images = content.filter((item) => item.type === 'image' && item.image);
return (
<div className="overflow-hidden pt-[4px]">
<div className="flex items-start gap-4">
<div className="flex-1">
<Markdown limitedMarkdown>{textContent}</Markdown>
</div>
{images.length > 0 && (
<div className="flex-shrink-0 w-[160px]">
<div className="flex flex-col gap-4">
{textContent && <Markdown html>{textContent}</Markdown>}
{images.map((item, index) => (
<div key={index} className="relative">
<img
key={index}
src={item.image}
alt={`Uploaded image ${index + 1}`}
className="w-full h-[160px] rounded-lg object-cover border border-bolt-elements-borderColor"
alt={`Image ${index + 1}`}
className="max-w-full h-auto rounded-lg"
style={{ maxHeight: '512px', objectFit: 'contain' }}
/>
</div>
))}
</div>
)}
</div>
</div>
);
}
const textContent = sanitizeUserMessage(content);
const textContent = stripMetadata(content);
return (
<div className="overflow-hidden pt-[4px]">
<Markdown limitedMarkdown>{textContent}</Markdown>
<Markdown html>{textContent}</Markdown>
</div>
);
}
function sanitizeUserMessage(content: string) {
function stripMetadata(content: string) {
return content.replace(MODEL_REGEX, '').replace(PROVIDER_REGEX, '');
}

View File

@@ -1,6 +1,5 @@
import type { Message } from 'ai';
import { toast } from 'react-toastify';
import React from 'react';
import { ImportFolderButton } from '~/components/chat/ImportFolderButton';
export function ImportButtons(importChat: ((description: string, messages: Message[]) => Promise<void>) | undefined) {

View File

@@ -8,6 +8,8 @@ import { Chat } from '~/components/chat/Chat.client';
import { useGit } from '~/lib/hooks/useGit';
import { useChatHistory } from '~/lib/persistence';
import { createCommandsMessage, detectProjectCommands } from '~/utils/projectCommands';
import { LoadingOverlay } from '~/components/ui/LoadingOverlay';
import { toast } from 'react-toastify';
const IGNORE_PATTERNS = [
'node_modules/**',
@@ -38,6 +40,7 @@ export function GitUrlImport() {
const { ready: historyReady, importChat } = useChatHistory();
const { ready: gitReady, gitClone } = useGit();
const [imported, setImported] = useState(false);
const [loading, setLoading] = useState(true);
const importRepo = async (repoUrl?: string) => {
if (!gitReady && !historyReady) {
@@ -109,9 +112,23 @@ ${file.content}
return;
}
importRepo(url);
importRepo(url).catch((error) => {
console.error('Error importing repo:', error);
toast.error('Failed to import repository');
setLoading(false);
window.location.href = '/';
});
setImported(true);
}, [searchParams, historyReady, gitReady, imported]);
return <ClientOnly fallback={<BaseChat />}>{() => <Chat />}</ClientOnly>;
return (
<ClientOnly fallback={<BaseChat />}>
{() => (
<>
<Chat />
{loading && <LoadingOverlay message="Please wait while we clone the repository..." />}
</>
)}
</ClientOnly>
);
}

View File

@@ -5,30 +5,30 @@ import { classNames } from '~/utils/classNames';
import { DialogTitle, dialogVariants, dialogBackdropVariants } from '~/components/ui/Dialog';
import { IconButton } from '~/components/ui/IconButton';
import styles from './Settings.module.scss';
import ChatHistoryTab from './chat-history/ChatHistoryTab';
import ProvidersTab from './providers/ProvidersTab';
import { useSettings } from '~/lib/hooks/useSettings';
import FeaturesTab from './features/FeaturesTab';
import DebugTab from './debug/DebugTab';
import EventLogsTab from './event-logs/EventLogsTab';
import ConnectionsTab from './connections/ConnectionsTab';
import DataTab from './data/DataTab';
interface SettingsProps {
open: boolean;
onClose: () => void;
}
type TabType = 'chat-history' | 'providers' | 'features' | 'debug' | 'connection';
type TabType = 'data' | 'providers' | 'features' | 'debug' | 'event-logs' | 'connection';
// Providers that support base URL configuration
export const SettingsWindow = ({ open, onClose }: SettingsProps) => {
const { debug } = useSettings();
const [activeTab, setActiveTab] = useState<TabType>('chat-history');
const { debug, eventLogs } = useSettings();
const [activeTab, setActiveTab] = useState<TabType>('data');
const tabs: { id: TabType; label: string; icon: string; component?: ReactElement }[] = [
{ id: 'chat-history', label: 'Chat History', icon: 'i-ph:book', component: <ChatHistoryTab /> },
{ id: 'data', label: 'Data', icon: 'i-ph:database', component: <DataTab /> },
{ id: 'providers', label: 'Providers', icon: 'i-ph:key', component: <ProvidersTab /> },
{ id: 'features', label: 'Features', icon: 'i-ph:star', component: <FeaturesTab /> },
{ id: 'connection', label: 'Connection', icon: 'i-ph:link', component: <ConnectionsTab /> },
{ id: 'features', label: 'Features', icon: 'i-ph:star', component: <FeaturesTab /> },
...(debug
? [
{
@@ -39,6 +39,16 @@ export const SettingsWindow = ({ open, onClose }: SettingsProps) => {
},
]
: []),
...(eventLogs
? [
{
id: 'event-logs' as TabType,
label: 'Event Logs',
icon: 'i-ph:list-bullets',
component: <EventLogsTab />,
},
]
: []),
];
return (
@@ -53,7 +63,7 @@ export const SettingsWindow = ({ open, onClose }: SettingsProps) => {
variants={dialogBackdropVariants}
/>
</RadixDialog.Overlay>
<RadixDialog.Content asChild>
<RadixDialog.Content aria-describedby={undefined} asChild>
<motion.div
className="fixed top-[50%] left-[50%] z-max h-[85vh] w-[90vw] max-w-[900px] translate-x-[-50%] translate-y-[-50%] border border-bolt-elements-borderColor rounded-lg shadow-lg focus:outline-none overflow-hidden"
initial="closed"

View File

@@ -1,105 +0,0 @@
import { useNavigate } from '@remix-run/react';
import React, { useState } from 'react';
import { toast } from 'react-toastify';
import { db, deleteById, getAll } from '~/lib/persistence';
import { classNames } from '~/utils/classNames';
import styles from '~/components/settings/Settings.module.scss';
export default function ChatHistoryTab() {
const navigate = useNavigate();
const [isDeleting, setIsDeleting] = useState(false);
const downloadAsJson = (data: any, filename: string) => {
const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' });
const url = URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = url;
link.download = filename;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
URL.revokeObjectURL(url);
};
const handleDeleteAllChats = async () => {
if (!db) {
toast.error('Database is not available');
return;
}
try {
setIsDeleting(true);
const allChats = await getAll(db);
// Delete all chats one by one
await Promise.all(allChats.map((chat) => deleteById(db!, chat.id)));
toast.success('All chats deleted successfully');
navigate('/', { replace: true });
} catch (error) {
toast.error('Failed to delete chats');
console.error(error);
} finally {
setIsDeleting(false);
}
};
const handleExportAllChats = async () => {
if (!db) {
toast.error('Database is not available');
return;
}
try {
const allChats = await getAll(db);
const exportData = {
chats: allChats,
exportDate: new Date().toISOString(),
};
downloadAsJson(exportData, `all-chats-${new Date().toISOString()}.json`);
toast.success('Chats exported successfully');
} catch (error) {
toast.error('Failed to export chats');
console.error(error);
}
};
return (
<>
<div className="p-4">
<h3 className="text-lg font-medium text-bolt-elements-textPrimary mb-4">Chat History</h3>
<button
onClick={handleExportAllChats}
className={classNames(
'bg-bolt-elements-button-primary-background',
'rounded-lg px-4 py-2 mb-4 transition-colors duration-200',
'hover:bg-bolt-elements-button-primary-backgroundHover',
'text-bolt-elements-button-primary-text',
)}
>
Export All Chats
</button>
<div
className={classNames('text-bolt-elements-textPrimary rounded-lg py-4 mb-4', styles['settings-danger-area'])}
>
<h4 className="font-semibold">Danger Area</h4>
<p className="mb-2">This action cannot be undone!</p>
<button
onClick={handleDeleteAllChats}
disabled={isDeleting}
className={classNames(
'bg-bolt-elements-button-danger-background',
'rounded-lg px-4 py-2 transition-colors duration-200',
isDeleting ? 'opacity-50 cursor-not-allowed' : 'hover:bg-bolt-elements-button-danger-backgroundHover',
'text-bolt-elements-button-danger-text',
)}
>
{isDeleting ? 'Deleting...' : 'Delete All Chats'}
</button>
</div>
</div>
</>
);
}

View File

@@ -1,15 +1,93 @@
import React, { useState } from 'react';
import React, { useState, useEffect } from 'react';
import { toast } from 'react-toastify';
import Cookies from 'js-cookie';
import { logStore } from '~/lib/stores/logs';
interface GitHubUserResponse {
login: string;
id: number;
[key: string]: any; // for other properties we don't explicitly need
}
export default function ConnectionsTab() {
const [githubUsername, setGithubUsername] = useState(Cookies.get('githubUsername') || '');
const [githubToken, setGithubToken] = useState(Cookies.get('githubToken') || '');
const [isConnected, setIsConnected] = useState(false);
const [isVerifying, setIsVerifying] = useState(false);
const handleSaveConnection = () => {
useEffect(() => {
// Check if credentials exist and verify them
if (githubUsername && githubToken) {
verifyGitHubCredentials();
}
}, []);
const verifyGitHubCredentials = async () => {
setIsVerifying(true);
try {
const response = await fetch('https://api.github.com/user', {
headers: {
Authorization: `Bearer ${githubToken}`,
},
});
if (response.ok) {
const data = (await response.json()) as GitHubUserResponse;
if (data.login === githubUsername) {
setIsConnected(true);
return true;
}
}
setIsConnected(false);
return false;
} catch (error) {
console.error('Error verifying GitHub credentials:', error);
setIsConnected(false);
return false;
} finally {
setIsVerifying(false);
}
};
const handleSaveConnection = async () => {
if (!githubUsername || !githubToken) {
toast.error('Please provide both GitHub username and token');
return;
}
setIsVerifying(true);
const isValid = await verifyGitHubCredentials();
if (isValid) {
Cookies.set('githubUsername', githubUsername);
Cookies.set('githubToken', githubToken);
toast.success('GitHub credentials saved successfully!');
logStore.logSystem('GitHub connection settings updated', {
username: githubUsername,
hasToken: !!githubToken,
});
toast.success('GitHub credentials verified and saved successfully!');
Cookies.set('git:github.com', JSON.stringify({ username: githubToken, password: 'x-oauth-basic' }));
setIsConnected(true);
} else {
toast.error('Invalid GitHub credentials. Please check your username and token.');
}
};
const handleDisconnect = () => {
Cookies.remove('githubUsername');
Cookies.remove('githubToken');
Cookies.remove('git:github.com');
setGithubUsername('');
setGithubToken('');
setIsConnected(false);
logStore.logSystem('GitHub connection removed');
toast.success('GitHub connection removed successfully!');
};
return (
@@ -22,7 +100,8 @@ export default function ConnectionsTab() {
type="text"
value={githubUsername}
onChange={(e) => setGithubUsername(e.target.value)}
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"
disabled={isVerifying}
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 disabled:opacity-50"
/>
</div>
<div className="flex-1">
@@ -31,17 +110,41 @@ export default function ConnectionsTab() {
type="password"
value={githubToken}
onChange={(e) => setGithubToken(e.target.value)}
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"
disabled={isVerifying}
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 disabled:opacity-50"
/>
</div>
</div>
<div className="flex mb-4">
<div className="flex mb-4 items-center">
{!isConnected ? (
<button
onClick={handleSaveConnection}
className="bg-bolt-elements-button-primary-background rounded-lg px-4 py-2 mr-2 transition-colors duration-200 hover:bg-bolt-elements-button-primary-backgroundHover text-bolt-elements-button-primary-text"
disabled={isVerifying || !githubUsername || !githubToken}
className="bg-bolt-elements-button-primary-background rounded-lg px-4 py-2 mr-2 transition-colors duration-200 hover:bg-bolt-elements-button-primary-backgroundHover text-bolt-elements-button-primary-text disabled:opacity-50 disabled:cursor-not-allowed flex items-center"
>
Save Connection
{isVerifying ? (
<>
<div className="i-ph:spinner animate-spin mr-2" />
Verifying...
</>
) : (
'Connect'
)}
</button>
) : (
<button
onClick={handleDisconnect}
className="bg-bolt-elements-button-danger-background rounded-lg px-4 py-2 mr-2 transition-colors duration-200 hover:bg-bolt-elements-button-danger-backgroundHover text-bolt-elements-button-danger-text"
>
Disconnect
</button>
)}
{isConnected && (
<span className="text-sm text-green-600 flex items-center">
<div className="i-ph:check-circle mr-1" />
Connected to GitHub
</span>
)}
</div>
</div>
);

View File

@@ -0,0 +1,305 @@
import React, { useState } from 'react';
import { useNavigate } from '@remix-run/react';
import Cookies from 'js-cookie';
import { toast } from 'react-toastify';
import { db, deleteById, getAll } from '~/lib/persistence';
import { logStore } from '~/lib/stores/logs';
import { classNames } from '~/utils/classNames';
// List of supported providers that can have API keys
const API_KEY_PROVIDERS = [
'Anthropic',
'OpenAI',
'Google',
'Groq',
'HuggingFace',
'OpenRouter',
'Deepseek',
'Mistral',
'OpenAILike',
'Together',
'xAI',
'Perplexity',
'Cohere',
'AzureOpenAI',
] as const;
interface ApiKeys {
[key: string]: string;
}
export default function DataTab() {
const navigate = useNavigate();
const [isDeleting, setIsDeleting] = useState(false);
const downloadAsJson = (data: any, filename: string) => {
const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' });
const url = URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = url;
link.download = filename;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
URL.revokeObjectURL(url);
};
const handleExportAllChats = async () => {
if (!db) {
const error = new Error('Database is not available');
logStore.logError('Failed to export chats - DB unavailable', error);
toast.error('Database is not available');
return;
}
try {
const allChats = await getAll(db);
const exportData = {
chats: allChats,
exportDate: new Date().toISOString(),
};
downloadAsJson(exportData, `all-chats-${new Date().toISOString()}.json`);
logStore.logSystem('Chats exported successfully', { count: allChats.length });
toast.success('Chats exported successfully');
} catch (error) {
logStore.logError('Failed to export chats', error);
toast.error('Failed to export chats');
console.error(error);
}
};
const handleDeleteAllChats = async () => {
const confirmDelete = window.confirm('Are you sure you want to delete all chats? This action cannot be undone.');
if (!confirmDelete) {
return;
}
if (!db) {
const error = new Error('Database is not available');
logStore.logError('Failed to delete chats - DB unavailable', error);
toast.error('Database is not available');
return;
}
try {
setIsDeleting(true);
const allChats = await getAll(db);
await Promise.all(allChats.map((chat) => deleteById(db!, chat.id)));
logStore.logSystem('All chats deleted successfully', { count: allChats.length });
toast.success('All chats deleted successfully');
navigate('/', { replace: true });
} catch (error) {
logStore.logError('Failed to delete chats', error);
toast.error('Failed to delete chats');
console.error(error);
} finally {
setIsDeleting(false);
}
};
const handleExportSettings = () => {
const settings = {
providers: Cookies.get('providers'),
isDebugEnabled: Cookies.get('isDebugEnabled'),
isEventLogsEnabled: Cookies.get('isEventLogsEnabled'),
isLocalModelsEnabled: Cookies.get('isLocalModelsEnabled'),
promptId: Cookies.get('promptId'),
isLatestBranch: Cookies.get('isLatestBranch'),
commitHash: Cookies.get('commitHash'),
eventLogs: Cookies.get('eventLogs'),
selectedModel: Cookies.get('selectedModel'),
selectedProvider: Cookies.get('selectedProvider'),
githubUsername: Cookies.get('githubUsername'),
githubToken: Cookies.get('githubToken'),
bolt_theme: localStorage.getItem('bolt_theme'),
};
downloadAsJson(settings, 'bolt-settings.json');
toast.success('Settings exported successfully');
};
const handleImportSettings = (event: React.ChangeEvent<HTMLInputElement>) => {
const file = event.target.files?.[0];
if (!file) {
return;
}
const reader = new FileReader();
reader.onload = (e) => {
try {
const settings = JSON.parse(e.target?.result as string);
Object.entries(settings).forEach(([key, value]) => {
if (key === 'bolt_theme') {
if (value) {
localStorage.setItem(key, value as string);
}
} else if (value) {
Cookies.set(key, value as string);
}
});
toast.success('Settings imported successfully. Please refresh the page for changes to take effect.');
} catch (error) {
toast.error('Failed to import settings. Make sure the file is a valid JSON file.');
console.error('Failed to import settings:', error);
}
};
reader.readAsText(file);
event.target.value = '';
};
const handleExportApiKeyTemplate = () => {
const template: ApiKeys = {};
API_KEY_PROVIDERS.forEach((provider) => {
template[`${provider}_API_KEY`] = '';
});
template.OPENAI_LIKE_API_BASE_URL = '';
template.LMSTUDIO_API_BASE_URL = '';
template.OLLAMA_API_BASE_URL = '';
template.TOGETHER_API_BASE_URL = '';
downloadAsJson(template, 'api-keys-template.json');
toast.success('API keys template exported successfully');
};
const handleImportApiKeys = (event: React.ChangeEvent<HTMLInputElement>) => {
const file = event.target.files?.[0];
if (!file) {
return;
}
const reader = new FileReader();
reader.onload = (e) => {
try {
const apiKeys = JSON.parse(e.target?.result as string);
let importedCount = 0;
const consolidatedKeys: Record<string, string> = {};
API_KEY_PROVIDERS.forEach((provider) => {
const keyName = `${provider}_API_KEY`;
if (apiKeys[keyName]) {
consolidatedKeys[provider] = apiKeys[keyName];
importedCount++;
}
});
if (importedCount > 0) {
// Store all API keys in a single cookie as JSON
Cookies.set('apiKeys', JSON.stringify(consolidatedKeys));
// Also set individual cookies for backward compatibility
Object.entries(consolidatedKeys).forEach(([provider, key]) => {
Cookies.set(`${provider}_API_KEY`, key);
});
toast.success(`Successfully imported ${importedCount} API keys/URLs. Refreshing page to apply changes...`);
// Reload the page after a short delay to allow the toast to be seen
setTimeout(() => {
window.location.reload();
}, 1500);
} else {
toast.warn('No valid API keys found in the file');
}
// Set base URLs if they exist
['OPENAI_LIKE_API_BASE_URL', 'LMSTUDIO_API_BASE_URL', 'OLLAMA_API_BASE_URL', 'TOGETHER_API_BASE_URL'].forEach(
(baseUrl) => {
if (apiKeys[baseUrl]) {
Cookies.set(baseUrl, apiKeys[baseUrl]);
}
},
);
} catch (error) {
toast.error('Failed to import API keys. Make sure the file is a valid JSON file.');
console.error('Failed to import API keys:', error);
}
};
reader.readAsText(file);
event.target.value = '';
};
return (
<div className="p-4 bg-bolt-elements-bg-depth-2 border border-bolt-elements-borderColor rounded-lg mb-4">
<div className="mb-6">
<h3 className="text-lg font-medium text-bolt-elements-textPrimary mb-4">Data Management</h3>
<div className="space-y-8">
<div className="flex flex-col gap-4">
<div>
<h4 className="text-bolt-elements-textPrimary mb-2">Chat History</h4>
<p className="text-sm text-bolt-elements-textSecondary mb-4">Export or delete all your chat history.</p>
<div className="flex gap-4">
<button
onClick={handleExportAllChats}
className="px-4 py-2 bg-bolt-elements-button-primary-background hover:bg-bolt-elements-button-primary-backgroundHover text-bolt-elements-textPrimary rounded-lg transition-colors"
>
Export All Chats
</button>
<button
onClick={handleDeleteAllChats}
disabled={isDeleting}
className={classNames(
'px-4 py-2 bg-bolt-elements-button-danger-background hover:bg-bolt-elements-button-danger-backgroundHover text-bolt-elements-button-danger-text rounded-lg transition-colors',
isDeleting ? 'opacity-50 cursor-not-allowed' : '',
)}
>
{isDeleting ? 'Deleting...' : 'Delete All Chats'}
</button>
</div>
</div>
<div>
<h4 className="text-bolt-elements-textPrimary mb-2">Settings Backup</h4>
<p className="text-sm text-bolt-elements-textSecondary mb-4">
Export your settings to a JSON file or import settings from a previously exported file.
</p>
<div className="flex gap-4">
<button
onClick={handleExportSettings}
className="px-4 py-2 bg-bolt-elements-button-primary-background hover:bg-bolt-elements-button-primary-backgroundHover text-bolt-elements-textPrimary rounded-lg transition-colors"
>
Export Settings
</button>
<label className="px-4 py-2 bg-bolt-elements-button-primary-background hover:bg-bolt-elements-button-primary-backgroundHover text-bolt-elements-textPrimary rounded-lg transition-colors cursor-pointer">
Import Settings
<input type="file" accept=".json" onChange={handleImportSettings} className="hidden" />
</label>
</div>
</div>
<div>
<h4 className="text-bolt-elements-textPrimary mb-2">API Keys Management</h4>
<p className="text-sm text-bolt-elements-textSecondary mb-4">
Import API keys from a JSON file or download a template to fill in your keys.
</p>
<div className="flex gap-4">
<button
onClick={handleExportApiKeyTemplate}
className="px-4 py-2 bg-bolt-elements-button-primary-background hover:bg-bolt-elements-button-primary-backgroundHover text-bolt-elements-textPrimary rounded-lg transition-colors"
>
Download Template
</button>
<label className="px-4 py-2 bg-bolt-elements-button-primary-background hover:bg-bolt-elements-button-primary-backgroundHover text-bolt-elements-textPrimary rounded-lg transition-colors cursor-pointer">
Import API Keys
<input type="file" accept=".json" onChange={handleImportApiKeys} className="hidden" />
</label>
</div>
</div>
</div>
</div>
</div>
</div>
);
}

View File

@@ -1,69 +1,639 @@
import React, { useCallback, useEffect, useState } from 'react';
import { useSettings } from '~/lib/hooks/useSettings';
import commit from '~/commit.json';
import { toast } from 'react-toastify';
import { providerBaseUrlEnvKeys } from '~/utils/constants';
const versionHash = commit.commit; // Get the version hash from commit.json
interface ProviderStatus {
name: string;
enabled: boolean;
isLocal: boolean;
isRunning: boolean | null;
error?: string;
lastChecked: Date;
responseTime?: number;
url: string | null;
}
interface SystemInfo {
os: string;
browser: string;
screen: string;
language: string;
timezone: string;
memory: string;
cores: number;
deviceType: string;
colorDepth: string;
pixelRatio: number;
online: boolean;
cookiesEnabled: boolean;
doNotTrack: boolean;
}
interface IProviderConfig {
name: string;
settings: {
enabled: boolean;
baseUrl?: string;
};
}
interface CommitData {
commit: string;
version?: string;
}
const connitJson: CommitData = {
commit: __COMMIT_HASH,
version: __APP_VERSION,
};
const LOCAL_PROVIDERS = ['Ollama', 'LMStudio', 'OpenAILike'];
const versionHash = connitJson.commit;
const versionTag = connitJson.version;
const GITHUB_URLS = {
original: 'https://api.github.com/repos/stackblitz-labs/bolt.diy/commits/main',
fork: 'https://api.github.com/repos/Stijnus/bolt.new-any-llm/commits/main',
commitJson: async (branch: string) => {
try {
const response = await fetch(`https://api.github.com/repos/stackblitz-labs/bolt.diy/commits/${branch}`);
const data: { sha: string } = await response.json();
const packageJsonResp = await fetch(
`https://raw.githubusercontent.com/stackblitz-labs/bolt.diy/${branch}/package.json`,
);
const packageJson: { version: string } = await packageJsonResp.json();
return {
commit: data.sha.slice(0, 7),
version: packageJson.version,
};
} catch (error) {
console.log('Failed to fetch local commit info:', error);
throw new Error('Failed to fetch local commit info');
}
},
};
function getSystemInfo(): SystemInfo {
const formatBytes = (bytes: number): string => {
if (bytes === 0) {
return '0 Bytes';
}
const k = 1024;
const sizes = ['Bytes', 'KB', 'MB', 'GB'];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
};
const getBrowserInfo = (): string => {
const ua = navigator.userAgent;
let browser = 'Unknown';
if (ua.includes('Firefox/')) {
browser = 'Firefox';
} else if (ua.includes('Chrome/')) {
if (ua.includes('Edg/')) {
browser = 'Edge';
} else if (ua.includes('OPR/')) {
browser = 'Opera';
} else {
browser = 'Chrome';
}
} else if (ua.includes('Safari/')) {
if (!ua.includes('Chrome')) {
browser = 'Safari';
}
}
// Extract version number
const match = ua.match(new RegExp(`${browser}\\/([\\d.]+)`));
const version = match ? ` ${match[1]}` : '';
return `${browser}${version}`;
};
const getOperatingSystem = (): string => {
const ua = navigator.userAgent;
const platform = navigator.platform;
if (ua.includes('Win')) {
return 'Windows';
}
if (ua.includes('Mac')) {
if (ua.includes('iPhone') || ua.includes('iPad')) {
return 'iOS';
}
return 'macOS';
}
if (ua.includes('Linux')) {
return 'Linux';
}
if (ua.includes('Android')) {
return 'Android';
}
return platform || 'Unknown';
};
const getDeviceType = (): string => {
const ua = navigator.userAgent;
if (ua.includes('Mobile')) {
return 'Mobile';
}
if (ua.includes('Tablet')) {
return 'Tablet';
}
return 'Desktop';
};
// Get more detailed memory info if available
const getMemoryInfo = (): string => {
if ('memory' in performance) {
const memory = (performance as any).memory;
return `${formatBytes(memory.jsHeapSizeLimit)} (Used: ${formatBytes(memory.usedJSHeapSize)})`;
}
return 'Not available';
};
return {
os: getOperatingSystem(),
browser: getBrowserInfo(),
screen: `${window.screen.width}x${window.screen.height}`,
language: navigator.language,
timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
memory: getMemoryInfo(),
cores: navigator.hardwareConcurrency || 0,
deviceType: getDeviceType(),
// Add new fields
colorDepth: `${window.screen.colorDepth}-bit`,
pixelRatio: window.devicePixelRatio,
online: navigator.onLine,
cookiesEnabled: navigator.cookieEnabled,
doNotTrack: navigator.doNotTrack === '1',
};
}
const checkProviderStatus = async (url: string | null, providerName: string): Promise<ProviderStatus> => {
if (!url) {
console.log(`[Debug] No URL provided for ${providerName}`);
return {
name: providerName,
enabled: false,
isLocal: true,
isRunning: false,
error: 'No URL configured',
lastChecked: new Date(),
url: null,
};
}
console.log(`[Debug] Checking status for ${providerName} at ${url}`);
const startTime = performance.now();
try {
if (providerName.toLowerCase() === 'ollama') {
// Special check for Ollama root endpoint
try {
console.log(`[Debug] Checking Ollama root endpoint: ${url}`);
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), 5000); // 5 second timeout
const response = await fetch(url, {
signal: controller.signal,
headers: {
Accept: 'text/plain,application/json',
},
});
clearTimeout(timeoutId);
const text = await response.text();
console.log(`[Debug] Ollama root response:`, text);
if (text.includes('Ollama is running')) {
console.log(`[Debug] Ollama running confirmed via root endpoint`);
return {
name: providerName,
enabled: false,
isLocal: true,
isRunning: true,
lastChecked: new Date(),
responseTime: performance.now() - startTime,
url,
};
}
} catch (error) {
console.log(`[Debug] Ollama root check failed:`, error);
const errorMessage = error instanceof Error ? error.message : 'Unknown error';
if (errorMessage.includes('aborted')) {
return {
name: providerName,
enabled: false,
isLocal: true,
isRunning: false,
error: 'Connection timeout',
lastChecked: new Date(),
responseTime: performance.now() - startTime,
url,
};
}
}
}
// Try different endpoints based on provider
const checkUrls = [`${url}/api/health`, url.endsWith('v1') ? `${url}/models` : `${url}/v1/models`];
console.log(`[Debug] Checking additional endpoints:`, checkUrls);
const results = await Promise.all(
checkUrls.map(async (checkUrl) => {
try {
console.log(`[Debug] Trying endpoint: ${checkUrl}`);
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), 5000);
const response = await fetch(checkUrl, {
signal: controller.signal,
headers: {
Accept: 'application/json',
},
});
clearTimeout(timeoutId);
const ok = response.ok;
console.log(`[Debug] Endpoint ${checkUrl} response:`, ok);
if (ok) {
try {
const data = await response.json();
console.log(`[Debug] Endpoint ${checkUrl} data:`, data);
} catch {
console.log(`[Debug] Could not parse JSON from ${checkUrl}`);
}
}
return ok;
} catch (error) {
console.log(`[Debug] Endpoint ${checkUrl} failed:`, error);
return false;
}
}),
);
const isRunning = results.some((result) => result);
console.log(`[Debug] Final status for ${providerName}:`, isRunning);
return {
name: providerName,
enabled: false,
isLocal: true,
isRunning,
lastChecked: new Date(),
responseTime: performance.now() - startTime,
url,
};
} catch (error) {
console.log(`[Debug] Provider check failed for ${providerName}:`, error);
return {
name: providerName,
enabled: false,
isLocal: true,
isRunning: false,
error: error instanceof Error ? error.message : 'Unknown error',
lastChecked: new Date(),
responseTime: performance.now() - startTime,
url,
};
}
};
export default function DebugTab() {
const { providers } = useSettings();
const [activeProviders, setActiveProviders] = useState<string[]>([]);
useEffect(() => {
setActiveProviders(
Object.entries(providers)
.filter(([_key, provider]) => provider.settings.enabled)
.map(([_key, provider]) => provider.name),
const { providers, isLatestBranch } = useSettings();
const [activeProviders, setActiveProviders] = useState<ProviderStatus[]>([]);
const [updateMessage, setUpdateMessage] = useState<string>('');
const [systemInfo] = useState<SystemInfo>(getSystemInfo());
const [isCheckingUpdate, setIsCheckingUpdate] = useState(false);
const updateProviderStatuses = async () => {
if (!providers) {
return;
}
try {
const entries = Object.entries(providers) as [string, IProviderConfig][];
const statuses = await Promise.all(
entries
.filter(([, provider]) => LOCAL_PROVIDERS.includes(provider.name))
.map(async ([, provider]) => {
const envVarName =
providerBaseUrlEnvKeys[provider.name].baseUrlKey || `REACT_APP_${provider.name.toUpperCase()}_URL`;
// Access environment variables through import.meta.env
let settingsUrl = provider.settings.baseUrl;
if (settingsUrl && settingsUrl.trim().length === 0) {
settingsUrl = undefined;
}
const url = settingsUrl || import.meta.env[envVarName] || null; // Ensure baseUrl is used
console.log(`[Debug] Using URL for ${provider.name}:`, url, `(from ${envVarName})`);
const status = await checkProviderStatus(url, provider.name);
return {
...status,
enabled: provider.settings.enabled ?? false,
};
}),
);
setActiveProviders(statuses);
} catch (error) {
console.error('[Debug] Failed to update provider statuses:', error);
}
};
useEffect(() => {
updateProviderStatuses();
const interval = setInterval(updateProviderStatuses, 30000);
return () => clearInterval(interval);
}, [providers]);
const handleCheckForUpdate = useCallback(async () => {
if (isCheckingUpdate) {
return;
}
try {
setIsCheckingUpdate(true);
setUpdateMessage('Checking for updates...');
const branchToCheck = isLatestBranch ? 'main' : 'stable';
console.log(`[Debug] Checking for updates against ${branchToCheck} branch`);
const latestCommitResp = await GITHUB_URLS.commitJson(branchToCheck);
const remoteCommitHash = latestCommitResp.commit;
const currentCommitHash = versionHash;
if (remoteCommitHash !== currentCommitHash) {
setUpdateMessage(
`Update available from ${branchToCheck} branch!\n` +
`Current: ${currentCommitHash.slice(0, 7)}\n` +
`Latest: ${remoteCommitHash.slice(0, 7)}`,
);
} else {
setUpdateMessage(`You are on the latest version from the ${branchToCheck} branch`);
}
} catch (error) {
setUpdateMessage('Failed to check for updates');
console.error('[Debug] Failed to check for updates:', error);
} finally {
setIsCheckingUpdate(false);
}
}, [isCheckingUpdate, isLatestBranch]);
const handleCopyToClipboard = useCallback(() => {
const debugInfo = {
OS: navigator.platform,
Browser: navigator.userAgent,
ActiveFeatures: activeProviders,
BaseURLs: {
Ollama: process.env.REACT_APP_OLLAMA_URL,
OpenAI: process.env.REACT_APP_OPENAI_URL,
LMStudio: process.env.REACT_APP_LM_STUDIO_URL,
System: systemInfo,
Providers: activeProviders.map((provider) => ({
name: provider.name,
enabled: provider.enabled,
isLocal: provider.isLocal,
running: provider.isRunning,
error: provider.error,
lastChecked: provider.lastChecked,
responseTime: provider.responseTime,
url: provider.url,
})),
Version: {
hash: versionHash.slice(0, 7),
branch: isLatestBranch ? 'main' : 'stable',
},
Version: versionHash,
Timestamp: new Date().toISOString(),
};
navigator.clipboard.writeText(JSON.stringify(debugInfo, null, 2)).then(() => {
alert('Debug information copied to clipboard!');
toast.success('Debug information copied to clipboard!');
});
}, [providers]);
}, [activeProviders, systemInfo, isLatestBranch]);
return (
<div className="p-4">
<h3 className="text-lg font-medium text-bolt-elements-textPrimary mb-4">Debug Tab</h3>
<div className="p-4 space-y-6">
<div className="flex items-center justify-between">
<h3 className="text-lg font-medium text-bolt-elements-textPrimary">Debug Information</h3>
<div className="flex gap-2">
<button
onClick={handleCopyToClipboard}
className="bg-blue-500 text-white rounded-lg px-4 py-2 hover:bg-blue-600 mb-4 transition-colors duration-200"
className="bg-bolt-elements-button-primary-background rounded-lg px-4 py-2 transition-colors duration-200 hover:bg-bolt-elements-button-primary-backgroundHover text-bolt-elements-button-primary-text"
>
Copy to Clipboard
Copy Debug Info
</button>
<button
onClick={handleCheckForUpdate}
disabled={isCheckingUpdate}
className={`bg-bolt-elements-button-primary-background rounded-lg px-4 py-2 transition-colors duration-200
${!isCheckingUpdate ? 'hover:bg-bolt-elements-button-primary-backgroundHover' : 'opacity-75 cursor-not-allowed'}
text-bolt-elements-button-primary-text`}
>
{isCheckingUpdate ? 'Checking...' : 'Check for Updates'}
</button>
</div>
</div>
<h4 className="text-md font-medium text-bolt-elements-textPrimary">System Information</h4>
<p className="text-bolt-elements-textSecondary">OS: {navigator.platform}</p>
<p className="text-bolt-elements-textSecondary">Browser: {navigator.userAgent}</p>
<h4 className="text-md font-medium text-bolt-elements-textPrimary mt-4">Active Features</h4>
<ul>
{activeProviders.map((name) => (
<li key={name} className="text-bolt-elements-textSecondary">
{name}
{updateMessage && (
<div
className={`bg-bolt-elements-surface rounded-lg p-3 ${
updateMessage.includes('Update available') ? 'border-l-4 border-yellow-400' : ''
}`}
>
<p className="text-bolt-elements-textSecondary whitespace-pre-line">{updateMessage}</p>
{updateMessage.includes('Update available') && (
<div className="mt-3 text-sm">
<p className="font-medium text-bolt-elements-textPrimary">To update:</p>
<ol className="list-decimal ml-4 mt-1 text-bolt-elements-textSecondary">
<li>
Pull the latest changes:{' '}
<code className="bg-bolt-elements-surface-hover px-1 rounded">git pull upstream main</code>
</li>
<li>
Install any new dependencies:{' '}
<code className="bg-bolt-elements-surface-hover px-1 rounded">pnpm install</code>
</li>
<li>Restart the application</li>
</ol>
</div>
)}
</div>
)}
<section className="space-y-4">
<div>
<h4 className="text-md font-medium text-bolt-elements-textPrimary mb-2">System Information</h4>
<div className="bg-bolt-elements-surface rounded-lg p-4">
<div className="grid grid-cols-2 md:grid-cols-3 gap-4">
<div>
<p className="text-xs text-bolt-elements-textSecondary">Operating System</p>
<p className="text-sm font-medium text-bolt-elements-textPrimary">{systemInfo.os}</p>
</div>
<div>
<p className="text-xs text-bolt-elements-textSecondary">Device Type</p>
<p className="text-sm font-medium text-bolt-elements-textPrimary">{systemInfo.deviceType}</p>
</div>
<div>
<p className="text-xs text-bolt-elements-textSecondary">Browser</p>
<p className="text-sm font-medium text-bolt-elements-textPrimary">{systemInfo.browser}</p>
</div>
<div>
<p className="text-xs text-bolt-elements-textSecondary">Display</p>
<p className="text-sm font-medium text-bolt-elements-textPrimary">
{systemInfo.screen} ({systemInfo.colorDepth}) @{systemInfo.pixelRatio}x
</p>
</div>
<div>
<p className="text-xs text-bolt-elements-textSecondary">Connection</p>
<p className="text-sm font-medium flex items-center gap-2">
<span
className={`inline-block w-2 h-2 rounded-full ${systemInfo.online ? 'bg-green-500' : 'bg-red-500'}`}
/>
<span className={`${systemInfo.online ? 'text-green-600' : 'text-red-600'}`}>
{systemInfo.online ? 'Online' : 'Offline'}
</span>
</p>
</div>
<div>
<p className="text-xs text-bolt-elements-textSecondary">Screen Resolution</p>
<p className="text-sm font-medium text-bolt-elements-textPrimary">{systemInfo.screen}</p>
</div>
<div>
<p className="text-xs text-bolt-elements-textSecondary">Language</p>
<p className="text-sm font-medium text-bolt-elements-textPrimary">{systemInfo.language}</p>
</div>
<div>
<p className="text-xs text-bolt-elements-textSecondary">Timezone</p>
<p className="text-sm font-medium text-bolt-elements-textPrimary">{systemInfo.timezone}</p>
</div>
<div>
<p className="text-xs text-bolt-elements-textSecondary">CPU Cores</p>
<p className="text-sm font-medium text-bolt-elements-textPrimary">{systemInfo.cores}</p>
</div>
</div>
<div className="mt-3 pt-3 border-t border-bolt-elements-surface-hover">
<p className="text-xs text-bolt-elements-textSecondary">Version</p>
<p className="text-sm font-medium text-bolt-elements-textPrimary font-mono">
{connitJson.commit.slice(0, 7)}
<span className="ml-2 text-xs text-bolt-elements-textSecondary">
(v{versionTag || '0.0.1'}) - {isLatestBranch ? 'nightly' : 'stable'}
</span>
</p>
</div>
</div>
</div>
<div>
<h4 className="text-md font-medium text-bolt-elements-textPrimary mb-2">Local LLM Status</h4>
<div className="bg-bolt-elements-surface rounded-lg">
<div className="grid grid-cols-1 divide-y">
{activeProviders.map((provider) => (
<div key={provider.name} className="p-3 flex flex-col space-y-2">
<div className="flex items-center justify-between">
<div className="flex items-center gap-3">
<div className="flex-shrink-0">
<div
className={`w-2 h-2 rounded-full ${
!provider.enabled ? 'bg-gray-300' : provider.isRunning ? 'bg-green-400' : 'bg-red-400'
}`}
/>
</div>
<div>
<p className="text-sm font-medium text-bolt-elements-textPrimary">{provider.name}</p>
{provider.url && (
<p className="text-xs text-bolt-elements-textSecondary truncate max-w-[300px]">
{provider.url}
</p>
)}
</div>
</div>
<div className="flex items-center gap-2">
<span
className={`px-2 py-0.5 text-xs rounded-full ${
provider.enabled ? 'bg-green-100 text-green-800' : 'bg-gray-100 text-gray-800'
}`}
>
{provider.enabled ? 'Enabled' : 'Disabled'}
</span>
{provider.enabled && (
<span
className={`px-2 py-0.5 text-xs rounded-full ${
provider.isRunning ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'
}`}
>
{provider.isRunning ? 'Running' : 'Not Running'}
</span>
)}
</div>
</div>
<div className="pl-5 flex flex-col space-y-1 text-xs">
{/* Status Details */}
<div className="flex flex-wrap gap-2">
<span className="text-bolt-elements-textSecondary">
Last checked: {new Date(provider.lastChecked).toLocaleTimeString()}
</span>
{provider.responseTime && (
<span className="text-bolt-elements-textSecondary">
Response time: {Math.round(provider.responseTime)}ms
</span>
)}
</div>
{/* Error Message */}
{provider.error && (
<div className="mt-1 text-red-600 bg-red-50 rounded-md p-2">
<span className="font-medium">Error:</span> {provider.error}
</div>
)}
{/* Connection Info */}
{provider.url && (
<div className="text-bolt-elements-textSecondary">
<span className="font-medium">Endpoints checked:</span>
<ul className="list-disc list-inside pl-2 mt-1">
<li>{provider.url} (root)</li>
<li>{provider.url}/api/health</li>
<li>{provider.url}/v1/models</li>
</ul>
</div>
)}
</div>
</div>
))}
</ul>
<h4 className="text-md font-medium text-bolt-elements-textPrimary mt-4">Base URLs</h4>
<ul>
<li className="text-bolt-elements-textSecondary">Ollama: {process.env.REACT_APP_OLLAMA_URL}</li>
<li className="text-bolt-elements-textSecondary">OpenAI: {process.env.REACT_APP_OPENAI_URL}</li>
<li className="text-bolt-elements-textSecondary">LM Studio: {process.env.REACT_APP_LM_STUDIO_URL}</li>
</ul>
<h4 className="text-md font-medium text-bolt-elements-textPrimary mt-4">Version Information</h4>
<p className="text-bolt-elements-textSecondary">Version Hash: {versionHash}</p>
{activeProviders.length === 0 && (
<div className="p-4 text-center text-bolt-elements-textSecondary">No local LLMs configured</div>
)}
</div>
</div>
</div>
</section>
</div>
);
}

View File

@@ -0,0 +1,219 @@
import React, { useCallback, useEffect, useState, useMemo } from 'react';
import { useSettings } from '~/lib/hooks/useSettings';
import { toast } from 'react-toastify';
import { Switch } from '~/components/ui/Switch';
import { logStore, type LogEntry } from '~/lib/stores/logs';
import { useStore } from '@nanostores/react';
import { classNames } from '~/utils/classNames';
export default function EventLogsTab() {
const {} = useSettings();
const showLogs = useStore(logStore.showLogs);
const [logLevel, setLogLevel] = useState<LogEntry['level'] | 'all'>('info');
const [autoScroll, setAutoScroll] = useState(true);
const [searchQuery, setSearchQuery] = useState('');
const [, forceUpdate] = useState({});
const filteredLogs = useMemo(() => {
const logs = logStore.getLogs();
return logs.filter((log) => {
const matchesLevel = !logLevel || log.level === logLevel || logLevel === 'all';
const matchesSearch =
!searchQuery ||
log.message?.toLowerCase().includes(searchQuery.toLowerCase()) ||
JSON.stringify(log.details)?.toLowerCase()?.includes(searchQuery?.toLowerCase());
return matchesLevel && matchesSearch;
});
}, [logLevel, searchQuery]);
// Effect to initialize showLogs
useEffect(() => {
logStore.showLogs.set(true);
}, []);
useEffect(() => {
// System info logs
logStore.logSystem('Application initialized', {
version: process.env.NEXT_PUBLIC_APP_VERSION,
environment: process.env.NODE_ENV,
});
// Debug logs for system state
logStore.logDebug('System configuration loaded', {
runtime: 'Next.js',
features: ['AI Chat', 'Event Logging'],
});
// Warning logs for potential issues
logStore.logWarning('Resource usage threshold approaching', {
memoryUsage: '75%',
cpuLoad: '60%',
});
// Error logs with detailed context
logStore.logError('API connection failed', new Error('Connection timeout'), {
endpoint: '/api/chat',
retryCount: 3,
lastAttempt: new Date().toISOString(),
});
}, []);
useEffect(() => {
const container = document.querySelector('.logs-container');
if (container && autoScroll) {
container.scrollTop = container.scrollHeight;
}
}, [filteredLogs, autoScroll]);
const handleClearLogs = useCallback(() => {
if (confirm('Are you sure you want to clear all logs?')) {
logStore.clearLogs();
toast.success('Logs cleared successfully');
forceUpdate({}); // Force a re-render after clearing logs
}
}, []);
const handleExportLogs = useCallback(() => {
try {
const logText = logStore
.getLogs()
.map(
(log) =>
`[${log.level.toUpperCase()}] ${log.timestamp} - ${log.message}${
log.details ? '\nDetails: ' + JSON.stringify(log.details, null, 2) : ''
}`,
)
.join('\n\n');
const blob = new Blob([logText], { type: 'text/plain' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `event-logs-${new Date().toISOString()}.txt`;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
toast.success('Logs exported successfully');
} catch (error) {
toast.error('Failed to export logs');
console.error('Export error:', error);
}
}, []);
const getLevelColor = (level: LogEntry['level']) => {
switch (level) {
case 'info':
return 'text-blue-500';
case 'warning':
return 'text-yellow-500';
case 'error':
return 'text-red-500';
case 'debug':
return 'text-gray-500';
default:
return 'text-bolt-elements-textPrimary';
}
};
return (
<div className="p-4 h-full flex flex-col">
<div className="flex flex-col space-y-4 mb-4">
{/* Title and Toggles Row */}
<div className="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4">
<h3 className="text-lg font-medium text-bolt-elements-textPrimary">Event Logs</h3>
<div className="flex flex-wrap items-center gap-4">
<div className="flex items-center space-x-2">
<span className="text-sm text-bolt-elements-textSecondary whitespace-nowrap">Show Actions</span>
<Switch checked={showLogs} onCheckedChange={(checked) => logStore.showLogs.set(checked)} />
</div>
<div className="flex items-center space-x-2">
<span className="text-sm text-bolt-elements-textSecondary whitespace-nowrap">Auto-scroll</span>
<Switch checked={autoScroll} onCheckedChange={setAutoScroll} />
</div>
</div>
</div>
{/* Controls Row */}
<div className="flex flex-wrap items-center gap-2">
<select
value={logLevel}
onChange={(e) => setLogLevel(e.target.value as LogEntry['level'])}
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-[20%] text-sm min-w-[100px]"
>
<option value="all">All</option>
<option value="info">Info</option>
<option value="warning">Warning</option>
<option value="error">Error</option>
<option value="debug">Debug</option>
</select>
<div className="flex-1 min-w-[200px]">
<input
type="text"
placeholder="Search logs..."
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
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"
/>
</div>
{showLogs && (
<div className="flex items-center gap-2 flex-nowrap">
<button
onClick={handleExportLogs}
className={classNames(
'bg-bolt-elements-button-primary-background',
'rounded-lg px-4 py-2 transition-colors duration-200',
'hover:bg-bolt-elements-button-primary-backgroundHover',
'text-bolt-elements-button-primary-text',
)}
>
Export Logs
</button>
<button
onClick={handleClearLogs}
className={classNames(
'bg-bolt-elements-button-danger-background',
'rounded-lg px-4 py-2 transition-colors duration-200',
'hover:bg-bolt-elements-button-danger-backgroundHover',
'text-bolt-elements-button-danger-text',
)}
>
Clear Logs
</button>
</div>
)}
</div>
</div>
<div className="bg-bolt-elements-bg-depth-1 rounded-lg p-4 h-[calc(100vh - 250px)] min-h-[400px] overflow-y-auto logs-container overflow-y-auto">
{filteredLogs.length === 0 ? (
<div className="text-center text-bolt-elements-textSecondary py-8">No logs found</div>
) : (
filteredLogs.map((log, index) => (
<div
key={index}
className="text-sm mb-3 font-mono border-b border-bolt-elements-borderColor pb-2 last:border-0"
>
<div className="flex items-start space-x-2 flex-wrap">
<span className={`font-bold ${getLevelColor(log.level)} whitespace-nowrap`}>
[{log.level.toUpperCase()}]
</span>
<span className="text-bolt-elements-textSecondary whitespace-nowrap">
{new Date(log.timestamp).toLocaleString()}
</span>
<span className="text-bolt-elements-textPrimary break-all">{log.message}</span>
</div>
{log.details && (
<pre className="mt-2 text-xs text-bolt-elements-textSecondary overflow-x-auto whitespace-pre-wrap break-all">
{JSON.stringify(log.details, null, 2)}
</pre>
)}
</div>
))
)}
</div>
</div>
);
}

View File

@@ -1,28 +1,106 @@
import React from 'react';
import { Switch } from '~/components/ui/Switch';
import { PromptLibrary } from '~/lib/common/prompt-library';
import { useSettings } from '~/lib/hooks/useSettings';
export default function FeaturesTab() {
const { debug, enableDebugMode, isLocalModel, enableLocalModels } = useSettings();
const {
debug,
enableDebugMode,
isLocalModel,
enableLocalModels,
enableEventLogs,
isLatestBranch,
enableLatestBranch,
promptId,
setPromptId,
autoSelectTemplate,
setAutoSelectTemplate,
enableContextOptimization,
contextOptimizationEnabled,
} = useSettings();
const handleToggle = (enabled: boolean) => {
enableDebugMode(enabled);
enableEventLogs(enabled);
};
return (
<div className="p-4 bg-bolt-elements-bg-depth-2 border border-bolt-elements-borderColor rounded-lg mb-4">
<div className="mb-6">
<h3 className="text-lg font-medium text-bolt-elements-textPrimary mb-4">Optional Features</h3>
<div className="flex items-center justify-between mb-2">
<span className="text-bolt-elements-textPrimary">Debug Info</span>
<Switch className="ml-auto" checked={debug} onCheckedChange={enableDebugMode} />
<div className="space-y-4">
<div className="flex items-center justify-between">
<span className="text-bolt-elements-textPrimary">Debug Features</span>
<Switch className="ml-auto" checked={debug} onCheckedChange={handleToggle} />
</div>
<div className="flex items-center justify-between">
<div>
<span className="text-bolt-elements-textPrimary">Use Main Branch</span>
<p className="text-xs text-bolt-elements-textTertiary">
Check for updates against the main branch instead of stable
</p>
</div>
<Switch className="ml-auto" checked={isLatestBranch} onCheckedChange={enableLatestBranch} />
</div>
<div className="flex items-center justify-between">
<div>
<span className="text-bolt-elements-textPrimary">Auto Select Code Template</span>
<p className="text-xs text-bolt-elements-textTertiary">
Let Bolt select the best starter template for your project.
</p>
</div>
<Switch className="ml-auto" checked={autoSelectTemplate} onCheckedChange={setAutoSelectTemplate} />
</div>
<div className="flex items-center justify-between">
<div>
<span className="text-bolt-elements-textPrimary">Use Context Optimization</span>
<p className="text-sm text-bolt-elements-textSecondary">
redact file contents form chat and puts the latest file contents on the system prompt
</p>
</div>
<Switch
className="ml-auto"
checked={contextOptimizationEnabled}
onCheckedChange={enableContextOptimization}
/>
</div>
</div>
</div>
<div className="mb-6 border-t border-bolt-elements-borderColor pt-4">
<h3 className="text-lg font-medium text-bolt-elements-textPrimary mb-4">Experimental Features</h3>
<p className="text-sm text-bolt-elements-textSecondary mb-4">
<p className="text-sm text-bolt-elements-textSecondary mb-10">
Disclaimer: Experimental features may be unstable and are subject to change.
</p>
<div className="flex flex-col">
<div className="flex items-center justify-between mb-2">
<span className="text-bolt-elements-textPrimary">Enable Local Models</span>
<span className="text-bolt-elements-textPrimary">Experimental Providers</span>
<Switch className="ml-auto" checked={isLocalModel} onCheckedChange={enableLocalModels} />
</div>
<p className="text-xs text-bolt-elements-textTertiary mb-4">
Enable experimental providers such as Ollama, LMStudio, and OpenAILike.
</p>
</div>
<div className="flex items-start justify-between pt-4 mb-2 gap-2">
<div className="flex-1 max-w-[200px]">
<span className="text-bolt-elements-textPrimary">Prompt Library</span>
<p className="text-xs text-bolt-elements-textTertiary mb-4">
Choose a prompt from the library to use as the system prompt.
</p>
</div>
<select
value={promptId}
onChange={(e) => setPromptId(e.target.value)}
className="flex-1 p-2 ml-auto 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 text-sm min-w-[100px]"
>
{PromptLibrary.getList().map((x) => (
<option key={x.id} value={x.id}>
{x.label}
</option>
))}
</select>
</div>
</div>
</div>
);

View File

@@ -3,6 +3,12 @@ import { Switch } from '~/components/ui/Switch';
import { useSettings } from '~/lib/hooks/useSettings';
import { LOCAL_PROVIDERS, URL_CONFIGURABLE_PROVIDERS } from '~/lib/stores/settings';
import type { IProviderConfig } from '~/types/model';
import { logStore } from '~/lib/stores/logs';
// Import a default fallback icon
import { providerBaseUrlEnvKeys } from '~/utils/constants';
const DefaultIcon = '/icons/Default.svg'; // Adjust the path as necessary
export default function ProvidersTab() {
const { providers, updateProviderSettings, isLocalModel } = useSettings();
@@ -29,9 +35,87 @@ export default function ProvidersTab() {
newFilteredProviders.sort((a, b) => a.name.localeCompare(b.name));
setFilteredProviders(newFilteredProviders);
// Split providers into regular and URL-configurable
const regular = newFilteredProviders.filter((p) => !URL_CONFIGURABLE_PROVIDERS.includes(p.name));
const urlConfigurable = newFilteredProviders.filter((p) => URL_CONFIGURABLE_PROVIDERS.includes(p.name));
setFilteredProviders([...regular, ...urlConfigurable]);
}, [providers, searchTerm, isLocalModel]);
const renderProviderCard = (provider: IProviderConfig) => {
const envBaseUrlKey = providerBaseUrlEnvKeys[provider.name].baseUrlKey;
const envBaseUrl = envBaseUrlKey ? import.meta.env[envBaseUrlKey] : undefined;
const isUrlConfigurable = URL_CONFIGURABLE_PROVIDERS.includes(provider.name);
return (
<div
key={provider.name}
className="flex flex-col provider-item hover:bg-bolt-elements-bg-depth-3 p-4 rounded-lg border border-bolt-elements-borderColor"
>
<div className="flex items-center justify-between mb-2">
<div className="flex items-center gap-2">
<img
src={`/icons/${provider.name}.svg`}
onError={(e) => {
e.currentTarget.src = DefaultIcon;
}}
alt={`${provider.name} icon`}
className="w-6 h-6 dark:invert"
/>
<span className="text-bolt-elements-textPrimary">{provider.name}</span>
</div>
<Switch
className="ml-auto"
checked={provider.settings.enabled}
onCheckedChange={(enabled) => {
updateProviderSettings(provider.name, { ...provider.settings, enabled });
if (enabled) {
logStore.logProvider(`Provider ${provider.name} enabled`, { provider: provider.name });
} else {
logStore.logProvider(`Provider ${provider.name} disabled`, { provider: provider.name });
}
}}
/>
</div>
{isUrlConfigurable && provider.settings.enabled && (
<div className="mt-2">
{envBaseUrl && (
<label className="block text-xs text-bolt-elements-textSecondary text-green-300 mb-2">
Set On (.env) : {envBaseUrl}
</label>
)}
<label className="block text-sm text-bolt-elements-textSecondary mb-2">
{envBaseUrl ? 'Override Base Url' : 'Base URL '}:{' '}
</label>
<input
type="text"
value={provider.settings.baseUrl || ''}
onChange={(e) => {
let newBaseUrl: string | undefined = e.target.value;
if (newBaseUrl && newBaseUrl.trim().length === 0) {
newBaseUrl = undefined;
}
updateProviderSettings(provider.name, { ...provider.settings, baseUrl: newBaseUrl });
logStore.logProvider(`Base URL updated for ${provider.name}`, {
provider: provider.name,
baseUrl: newBaseUrl,
});
}}
placeholder={`Enter ${provider.name} base URL`}
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"
/>
</div>
)}
</div>
);
};
const regularProviders = filteredProviders.filter((p) => !URL_CONFIGURABLE_PROVIDERS.includes(p.name));
const urlConfigurableProviders = filteredProviders.filter((p) => URL_CONFIGURABLE_PROVIDERS.includes(p.name));
return (
<div className="p-4">
<div className="flex mb-4">
@@ -43,36 +127,21 @@ export default function ProvidersTab() {
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"
/>
</div>
{filteredProviders.map((provider) => (
<div
key={provider.name}
className="flex flex-col mb-2 provider-item hover:bg-bolt-elements-bg-depth-3 p-4 rounded-lg border border-bolt-elements-borderColor "
>
<div className="flex items-center justify-between mb-2">
<span className="text-bolt-elements-textPrimary">{provider.name}</span>
<Switch
className="ml-auto"
checked={provider.settings.enabled}
onCheckedChange={(enabled) => updateProviderSettings(provider.name, { ...provider.settings, enabled })}
/>
</div>
{/* Base URL input for configurable providers */}
{URL_CONFIGURABLE_PROVIDERS.includes(provider.name) && provider.settings.enabled && (
<div className="mt-2">
<label className="block text-sm text-bolt-elements-textSecondary mb-1">Base URL:</label>
<input
type="text"
value={provider.settings.baseUrl || ''}
onChange={(e) =>
updateProviderSettings(provider.name, { ...provider.settings, baseUrl: e.target.value })
}
placeholder={`Enter ${provider.name} base URL`}
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"
/>
{/* Regular Providers Grid */}
<div className="grid grid-cols-2 gap-4 mb-8">{regularProviders.map(renderProviderCard)}</div>
{/* URL Configurable Providers Section */}
{urlConfigurableProviders.length > 0 && (
<div className="mt-8">
<h3 className="text-lg font-semibold mb-2 text-bolt-elements-textPrimary">Experimental Providers</h3>
<p className="text-sm text-bolt-elements-textSecondary mb-4">
These providers are experimental and allow you to run AI models locally or connect to your own
infrastructure. They require additional setup but offer more flexibility.
</p>
<div className="space-y-4">{urlConfigurableProviders.map(renderProviderCard)}</div>
</div>
)}
</div>
))}
</div>
);
}

View File

@@ -4,6 +4,7 @@ import * as Dialog from '@radix-ui/react-dialog';
import { type ChatHistoryItem } from '~/lib/persistence';
import WithTooltip from '~/components/ui/Tooltip';
import { useEditChatDescription } from '~/lib/hooks';
import { forwardRef, type ForwardedRef } from 'react';
interface HistoryItemProps {
item: ChatHistoryItem;
@@ -103,7 +104,9 @@ export function HistoryItem({ item, onDelete, onDuplicate, exportChat }: History
);
}
const ChatActionButton = ({
const ChatActionButton = forwardRef(
(
{
toolTipContent,
icon,
className,
@@ -114,14 +117,18 @@ const ChatActionButton = ({
className?: string;
onClick: (event: React.MouseEvent<HTMLButtonElement, MouseEvent>) => void;
btnTitle?: string;
}) => {
},
ref: ForwardedRef<HTMLButtonElement>,
) => {
return (
<WithTooltip tooltip={toolTipContent}>
<button
ref={ref}
type="button"
className={`scale-110 mr-2 hover:text-bolt-elements-item-contentAccent ${icon} ${className ? className : ''}`}
onClick={onClick}
/>
</WithTooltip>
);
};
},
);

View File

@@ -35,6 +35,25 @@ const menuVariants = {
type DialogContent = { type: 'delete'; item: ChatHistoryItem } | null;
function CurrentDateTime() {
const [dateTime, setDateTime] = useState(new Date());
useEffect(() => {
const timer = setInterval(() => {
setDateTime(new Date());
}, 60000); // Update every minute
return () => clearInterval(timer);
}, []);
return (
<div className="flex items-center gap-2 px-4 py-3 font-bold text-gray-700 dark:text-gray-300 border-b border-bolt-elements-borderColor">
<div className="h-4 w-4 i-ph:clock-thin" />
{dateTime.toLocaleDateString()} {dateTime.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}
</div>
);
}
export const Menu = () => {
const { duplicateCurrentChat, exportChat } = useChatHistory();
const menuRef = useRef<HTMLDivElement>(null);
@@ -126,18 +145,17 @@ export const Menu = () => {
variants={menuVariants}
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"
>
<div className="flex items-center h-[var(--header-height)]">{/* Placeholder */}</div>
<div className="h-[60px]" /> {/* Spacer for top margin */}
<CurrentDateTime />
<div className="flex-1 flex flex-col h-full w-full overflow-hidden">
<div className="p-4 select-none">
<a
href="/"
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"
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 mb-4"
>
<span className="inline-block i-bolt:chat scale-110" />
Start new chat
</a>
</div>
<div className="pl-4 pr-4 my-2">
<div className="relative w-full">
<input
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"

View File

@@ -1,4 +1,4 @@
import { memo } from 'react';
import { memo, forwardRef, type ForwardedRef } from 'react';
import { classNames } from '~/utils/classNames';
type IconSize = 'sm' | 'md' | 'lg' | 'xl' | 'xxl';
@@ -25,8 +25,11 @@ type IconButtonWithChildrenProps = {
type IconButtonProps = IconButtonWithoutChildrenProps | IconButtonWithChildrenProps;
// Componente IconButton com suporte a refs
export const IconButton = memo(
({
forwardRef(
(
{
icon,
size = 'xl',
className,
@@ -36,9 +39,12 @@ export const IconButton = memo(
title,
onClick,
children,
}: IconButtonProps) => {
}: IconButtonProps,
ref: ForwardedRef<HTMLButtonElement>,
) => {
return (
<button
ref={ref}
className={classNames(
'flex items-center text-bolt-elements-item-contentDefault bg-transparent enabled:hover:text-bolt-elements-item-contentActive rounded-md p-1 enabled:hover:bg-bolt-elements-item-backgroundActive disabled:cursor-not-allowed',
{
@@ -60,6 +66,7 @@ export const IconButton = memo(
</button>
);
},
),
);
function getIconSize(size: IconSize) {

View File

@@ -0,0 +1,14 @@
export const LoadingOverlay = ({ message = 'Loading...' }) => {
return (
<div className="fixed inset-0 flex items-center justify-center bg-black/80 z-50 backdrop-blur-sm">
{/* Loading content */}
<div className="relative flex flex-col items-center gap-4 p-8 rounded-lg bg-bolt-elements-background-depth-2 shadow-lg">
<div
className={'i-svg-spinners:90-ring-with-bg text-bolt-elements-loader-progress'}
style={{ fontSize: '2rem' }}
></div>
<p className="text-lg text-bolt-elements-textTertiary">{message}</p>
</div>
</div>
);
};

View File

@@ -1,8 +1,9 @@
import * as Tooltip from '@radix-ui/react-tooltip';
import { forwardRef, type ForwardedRef, type ReactElement } from 'react';
interface TooltipProps {
tooltip: React.ReactNode;
children: React.ReactNode;
children: ReactElement;
sideOffset?: number;
className?: string;
arrowClassName?: string;
@@ -12,7 +13,9 @@ interface TooltipProps {
delay?: number;
}
const WithTooltip = ({
const WithTooltip = forwardRef(
(
{
tooltip,
children,
sideOffset = 5,
@@ -22,7 +25,9 @@ const WithTooltip = ({
position = 'top',
maxWidth = 250,
delay = 0,
}: TooltipProps) => {
}: TooltipProps,
_ref: ForwardedRef<HTMLElement>,
) => {
return (
<Tooltip.Root delayDuration={delay}>
<Tooltip.Trigger asChild>{children}</Tooltip.Trigger>
@@ -68,6 +73,7 @@ const WithTooltip = ({
</Tooltip.Portal>
</Tooltip.Root>
);
};
},
);
export default WithTooltip;

View File

@@ -2,6 +2,7 @@ import { memo, useEffect, useMemo, useState, type ReactNode } from 'react';
import type { FileMap } from '~/lib/stores/files';
import { classNames } from '~/utils/classNames';
import { createScopedLogger, renderLogger } from '~/utils/logger';
import * as ContextMenu from '@radix-ui/react-context-menu';
const logger = createScopedLogger('FileTree');
@@ -110,6 +111,22 @@ export const FileTree = memo(
});
};
const onCopyPath = (fileOrFolder: FileNode | FolderNode) => {
try {
navigator.clipboard.writeText(fileOrFolder.fullPath);
} catch (error) {
logger.error(error);
}
};
const onCopyRelativePath = (fileOrFolder: FileNode | FolderNode) => {
try {
navigator.clipboard.writeText(fileOrFolder.fullPath.substring((rootFolder || '').length));
} catch (error) {
logger.error(error);
}
};
return (
<div className={classNames('text-sm', className, 'overflow-y-auto')}>
{filteredFileList.map((fileOrFolder) => {
@@ -121,6 +138,12 @@ export const FileTree = memo(
selected={selectedFile === fileOrFolder.fullPath}
file={fileOrFolder}
unsavedChanges={unsavedFiles?.has(fileOrFolder.fullPath)}
onCopyPath={() => {
onCopyPath(fileOrFolder);
}}
onCopyRelativePath={() => {
onCopyRelativePath(fileOrFolder);
}}
onClick={() => {
onFileSelect?.(fileOrFolder.fullPath);
}}
@@ -134,6 +157,12 @@ export const FileTree = memo(
folder={fileOrFolder}
selected={allowFolderSelection && selectedFile === fileOrFolder.fullPath}
collapsed={collapsedFolders.has(fileOrFolder.fullPath)}
onCopyPath={() => {
onCopyPath(fileOrFolder);
}}
onCopyRelativePath={() => {
onCopyRelativePath(fileOrFolder);
}}
onClick={() => {
toggleCollapseState(fileOrFolder.fullPath);
}}
@@ -156,26 +185,67 @@ interface FolderProps {
folder: FolderNode;
collapsed: boolean;
selected?: boolean;
onCopyPath: () => void;
onCopyRelativePath: () => void;
onClick: () => void;
}
function Folder({ folder: { depth, name }, collapsed, selected = false, onClick }: FolderProps) {
interface FolderContextMenuProps {
onCopyPath?: () => void;
onCopyRelativePath?: () => void;
children: ReactNode;
}
function ContextMenuItem({ onSelect, children }: { onSelect?: () => void; children: ReactNode }) {
return (
<ContextMenu.Item
onSelect={onSelect}
className="flex items-center gap-2 px-2 py-1.5 outline-0 text-sm text-bolt-elements-textPrimary cursor-pointer ws-nowrap text-bolt-elements-item-contentDefault hover:text-bolt-elements-item-contentActive hover:bg-bolt-elements-item-backgroundActive rounded-md"
>
<span className="size-4 shrink-0"></span>
<span>{children}</span>
</ContextMenu.Item>
);
}
function FileContextMenu({ onCopyPath, onCopyRelativePath, children }: FolderContextMenuProps) {
return (
<ContextMenu.Root>
<ContextMenu.Trigger>{children}</ContextMenu.Trigger>
<ContextMenu.Portal>
<ContextMenu.Content
style={{ zIndex: 998 }}
className="border border-bolt-elements-borderColor rounded-md z-context-menu bg-bolt-elements-background-depth-1 dark:bg-bolt-elements-background-depth-2 data-[state=open]:animate-in animate-duration-100 data-[state=open]:fade-in-0 data-[state=open]:zoom-in-98 w-56"
>
<ContextMenu.Group className="p-1 border-b-px border-solid border-bolt-elements-borderColor">
<ContextMenuItem onSelect={onCopyPath}>Copy path</ContextMenuItem>
<ContextMenuItem onSelect={onCopyRelativePath}>Copy relative path</ContextMenuItem>
</ContextMenu.Group>
</ContextMenu.Content>
</ContextMenu.Portal>
</ContextMenu.Root>
);
}
function Folder({ folder, collapsed, selected = false, onCopyPath, onCopyRelativePath, onClick }: FolderProps) {
return (
<FileContextMenu onCopyPath={onCopyPath} onCopyRelativePath={onCopyRelativePath}>
<NodeButton
className={classNames('group', {
'bg-transparent text-bolt-elements-item-contentDefault hover:text-bolt-elements-item-contentActive hover:bg-bolt-elements-item-backgroundActive':
!selected,
'bg-bolt-elements-item-backgroundAccent text-bolt-elements-item-contentAccent': selected,
})}
depth={depth}
depth={folder.depth}
iconClasses={classNames({
'i-ph:caret-right scale-98': collapsed,
'i-ph:caret-down scale-98': !collapsed,
})}
onClick={onClick}
>
{name}
{folder.name}
</NodeButton>
</FileContextMenu>
);
}
@@ -183,14 +253,25 @@ interface FileProps {
file: FileNode;
selected: boolean;
unsavedChanges?: boolean;
onCopyPath: () => void;
onCopyRelativePath: () => void;
onClick: () => void;
}
function File({ file: { depth, name }, onClick, selected, unsavedChanges = false }: FileProps) {
function File({
file: { depth, name },
onClick,
onCopyPath,
onCopyRelativePath,
selected,
unsavedChanges = false,
}: FileProps) {
return (
<FileContextMenu onCopyPath={onCopyPath} onCopyRelativePath={onCopyRelativePath}>
<NodeButton
className={classNames('group', {
'bg-transparent hover:bg-bolt-elements-item-backgroundActive text-bolt-elements-item-contentDefault': !selected,
'bg-transparent hover:bg-bolt-elements-item-backgroundActive text-bolt-elements-item-contentDefault':
!selected,
'bg-bolt-elements-item-backgroundAccent text-bolt-elements-item-contentAccent': selected,
})}
depth={depth}
@@ -208,6 +289,7 @@ function File({ file: { depth, name }, onClick, selected, unsavedChanges = false
{unsavedChanges && <span className="i-ph:circle-fill scale-68 shrink-0 text-orange-500" />}
</div>
</NodeButton>
</FileContextMenu>
);
}

View File

@@ -3,6 +3,7 @@ import { memo, useCallback, useEffect, useRef, useState } from 'react';
import { IconButton } from '~/components/ui/IconButton';
import { workbenchStore } from '~/lib/stores/workbench';
import { PortDropdown } from './PortDropdown';
import { ScreenshotSelector } from './ScreenshotSelector';
type ResizeSide = 'left' | 'right' | null;
@@ -20,6 +21,7 @@ export const Preview = memo(() => {
const [url, setUrl] = useState('');
const [iframeUrl, setIframeUrl] = useState<string | undefined>();
const [isSelectionMode, setIsSelectionMode] = useState(false);
// Toggle between responsive mode and device mode
const [isDeviceModeOn, setIsDeviceModeOn] = useState(false);
@@ -218,12 +220,17 @@ export const Preview = memo(() => {
)}
<div className="bg-bolt-elements-background-depth-2 p-2 flex items-center gap-1.5">
<IconButton icon="i-ph:arrow-clockwise" onClick={reloadPreview} />
<IconButton
icon="i-ph:selection"
onClick={() => setIsSelectionMode(!isSelectionMode)}
className={isSelectionMode ? 'bg-bolt-elements-background-depth-3' : ''}
/>
<div
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
focus-within-border-bolt-elements-borderColorActive focus-within:text-bolt-elements-preview-addressBar-textActive"
>
<input
title="URL"
ref={inputRef}
className="w-full bg-transparent outline-none"
type="text"
@@ -281,7 +288,20 @@ export const Preview = memo(() => {
}}
>
{activePreview ? (
<iframe ref={iframeRef} className="border-none w-full h-full bg-white" src={iframeUrl} allowFullScreen />
<>
<iframe
ref={iframeRef}
title="preview"
className="border-none w-full h-full bg-white"
src={iframeUrl}
allowFullScreen
/>
<ScreenshotSelector
isSelectionMode={isSelectionMode}
setIsSelectionMode={setIsSelectionMode}
containerRef={iframeRef}
/>
</>
) : (
<div className="flex w-full h-full justify-center items-center bg-white">No preview available</div>
)}

View File

@@ -0,0 +1,293 @@
import { memo, useCallback, useEffect, useRef, useState } from 'react';
import { toast } from 'react-toastify';
interface ScreenshotSelectorProps {
isSelectionMode: boolean;
setIsSelectionMode: (mode: boolean) => void;
containerRef: React.RefObject<HTMLElement>;
}
export const ScreenshotSelector = memo(
({ isSelectionMode, setIsSelectionMode, containerRef }: ScreenshotSelectorProps) => {
const [isCapturing, setIsCapturing] = useState(false);
const [selectionStart, setSelectionStart] = useState<{ x: number; y: number } | null>(null);
const [selectionEnd, setSelectionEnd] = useState<{ x: number; y: number } | null>(null);
const mediaStreamRef = useRef<MediaStream | null>(null);
const videoRef = useRef<HTMLVideoElement | null>(null);
useEffect(() => {
// Cleanup function to stop all tracks when component unmounts
return () => {
if (videoRef.current) {
videoRef.current.pause();
videoRef.current.srcObject = null;
videoRef.current.remove();
videoRef.current = null;
}
if (mediaStreamRef.current) {
mediaStreamRef.current.getTracks().forEach((track) => track.stop());
mediaStreamRef.current = null;
}
};
}, []);
const initializeStream = async () => {
if (!mediaStreamRef.current) {
try {
const stream = await navigator.mediaDevices.getDisplayMedia({
audio: false,
video: {
displaySurface: 'window',
preferCurrentTab: true,
surfaceSwitching: 'include',
systemAudio: 'exclude',
},
} as MediaStreamConstraints);
// Add handler for when sharing stops
stream.addEventListener('inactive', () => {
if (videoRef.current) {
videoRef.current.pause();
videoRef.current.srcObject = null;
videoRef.current.remove();
videoRef.current = null;
}
if (mediaStreamRef.current) {
mediaStreamRef.current.getTracks().forEach((track) => track.stop());
mediaStreamRef.current = null;
}
setIsSelectionMode(false);
setSelectionStart(null);
setSelectionEnd(null);
setIsCapturing(false);
});
mediaStreamRef.current = stream;
// Initialize video element if needed
if (!videoRef.current) {
const video = document.createElement('video');
video.style.opacity = '0';
video.style.position = 'fixed';
video.style.pointerEvents = 'none';
video.style.zIndex = '-1';
document.body.appendChild(video);
videoRef.current = video;
}
// Set up video with the stream
videoRef.current.srcObject = stream;
await videoRef.current.play();
} catch (error) {
console.error('Failed to initialize stream:', error);
setIsSelectionMode(false);
toast.error('Failed to initialize screen capture');
}
}
return mediaStreamRef.current;
};
const handleCopySelection = useCallback(async () => {
if (!isSelectionMode || !selectionStart || !selectionEnd || !containerRef.current) {
return;
}
setIsCapturing(true);
try {
const stream = await initializeStream();
if (!stream || !videoRef.current) {
return;
}
// Wait for video to be ready
await new Promise((resolve) => setTimeout(resolve, 300));
// Create temporary canvas for full screenshot
const tempCanvas = document.createElement('canvas');
tempCanvas.width = videoRef.current.videoWidth;
tempCanvas.height = videoRef.current.videoHeight;
const tempCtx = tempCanvas.getContext('2d');
if (!tempCtx) {
throw new Error('Failed to get temporary canvas context');
}
// Draw the full video frame
tempCtx.drawImage(videoRef.current, 0, 0);
// Calculate scale factor between video and screen
const scaleX = videoRef.current.videoWidth / window.innerWidth;
const scaleY = videoRef.current.videoHeight / window.innerHeight;
// Get window scroll position
const scrollX = window.scrollX;
const scrollY = window.scrollY + 40;
// Get the container's position in the page
const containerRect = containerRef.current.getBoundingClientRect();
// Offset adjustments for more accurate clipping
const leftOffset = -9; // Adjust left position
const bottomOffset = -14; // Adjust bottom position
// Calculate the scaled coordinates with scroll offset and adjustments
const scaledX = Math.round(
(containerRect.left + Math.min(selectionStart.x, selectionEnd.x) + scrollX + leftOffset) * scaleX,
);
const scaledY = Math.round(
(containerRect.top + Math.min(selectionStart.y, selectionEnd.y) + scrollY + bottomOffset) * scaleY,
);
const scaledWidth = Math.round(Math.abs(selectionEnd.x - selectionStart.x) * scaleX);
const scaledHeight = Math.round(Math.abs(selectionEnd.y - selectionStart.y) * scaleY);
// Create final canvas for the cropped area
const canvas = document.createElement('canvas');
canvas.width = Math.round(Math.abs(selectionEnd.x - selectionStart.x));
canvas.height = Math.round(Math.abs(selectionEnd.y - selectionStart.y));
const ctx = canvas.getContext('2d');
if (!ctx) {
throw new Error('Failed to get canvas context');
}
// Draw the cropped area
ctx.drawImage(tempCanvas, scaledX, scaledY, scaledWidth, scaledHeight, 0, 0, canvas.width, canvas.height);
// Convert to blob
const blob = await new Promise<Blob>((resolve, reject) => {
canvas.toBlob((blob) => {
if (blob) {
resolve(blob);
} else {
reject(new Error('Failed to create blob'));
}
}, 'image/png');
});
// Create a FileReader to convert blob to base64
const reader = new FileReader();
reader.onload = (e) => {
const base64Image = e.target?.result as string;
// Find the textarea element
const textarea = document.querySelector('textarea');
if (textarea) {
// Get the setters from the BaseChat component
const setUploadedFiles = (window as any).__BOLT_SET_UPLOADED_FILES__;
const setImageDataList = (window as any).__BOLT_SET_IMAGE_DATA_LIST__;
const uploadedFiles = (window as any).__BOLT_UPLOADED_FILES__ || [];
const imageDataList = (window as any).__BOLT_IMAGE_DATA_LIST__ || [];
if (setUploadedFiles && setImageDataList) {
// Update the files and image data
const file = new File([blob], 'screenshot.png', { type: 'image/png' });
setUploadedFiles([...uploadedFiles, file]);
setImageDataList([...imageDataList, base64Image]);
toast.success('Screenshot captured and added to chat');
} else {
toast.error('Could not add screenshot to chat');
}
}
};
reader.readAsDataURL(blob);
} catch (error) {
console.error('Failed to capture screenshot:', error);
toast.error('Failed to capture screenshot');
if (mediaStreamRef.current) {
mediaStreamRef.current.getTracks().forEach((track) => track.stop());
mediaStreamRef.current = null;
}
} finally {
setIsCapturing(false);
setSelectionStart(null);
setSelectionEnd(null);
setIsSelectionMode(false); // Turn off selection mode after capture
}
}, [isSelectionMode, selectionStart, selectionEnd, containerRef, setIsSelectionMode]);
const handleSelectionStart = useCallback(
(e: React.MouseEvent) => {
e.preventDefault();
e.stopPropagation();
if (!isSelectionMode) {
return;
}
const rect = e.currentTarget.getBoundingClientRect();
const x = e.clientX - rect.left;
const y = e.clientY - rect.top;
setSelectionStart({ x, y });
setSelectionEnd({ x, y });
},
[isSelectionMode],
);
const handleSelectionMove = useCallback(
(e: React.MouseEvent) => {
e.preventDefault();
e.stopPropagation();
if (!isSelectionMode || !selectionStart) {
return;
}
const rect = e.currentTarget.getBoundingClientRect();
const x = e.clientX - rect.left;
const y = e.clientY - rect.top;
setSelectionEnd({ x, y });
},
[isSelectionMode, selectionStart],
);
if (!isSelectionMode) {
return null;
}
return (
<div
className="absolute inset-0 cursor-crosshair"
onMouseDown={handleSelectionStart}
onMouseMove={handleSelectionMove}
onMouseUp={handleCopySelection}
onMouseLeave={() => {
if (selectionStart) {
setSelectionStart(null);
}
}}
style={{
backgroundColor: isCapturing ? 'transparent' : 'rgba(0, 0, 0, 0.1)',
userSelect: 'none',
WebkitUserSelect: 'none',
pointerEvents: 'all',
opacity: isCapturing ? 0 : 1,
zIndex: 50,
transition: 'opacity 0.1s ease-in-out',
}}
>
{selectionStart && selectionEnd && !isCapturing && (
<div
className="absolute border-2 border-blue-500 bg-blue-200 bg-opacity-20"
style={{
left: Math.min(selectionStart.x, selectionEnd.x),
top: Math.min(selectionStart.y, selectionEnd.y),
width: Math.abs(selectionEnd.x - selectionStart.x),
height: Math.abs(selectionEnd.y - selectionStart.y),
}}
/>
)}
</div>
);
},
);

View File

@@ -5,7 +5,6 @@ import { renderToReadableStream } from 'react-dom/server';
import { renderHeadToString } from 'remix-island';
import { Head } from './root';
import { themeStore } from '~/lib/stores/theme';
import { initializeModelList } from '~/utils/constants';
export default async function handleRequest(
request: Request,
@@ -14,7 +13,7 @@ export default async function handleRequest(
remixContext: EntryContext,
_loadContext: AppLoadContext,
) {
await initializeModelList();
// await initializeModelList({});
const readable = await renderToReadableStream(<RemixServer context={remixContext} url={request.url} />, {
signal: request.signal,

View File

@@ -1,71 +0,0 @@
/*
* @ts-nocheck
* Preventing TS checks with files presented in the video for a better presentation.
*/
import { env } from 'node:process';
export function getAPIKey(cloudflareEnv: Env, provider: string, userApiKeys?: Record<string, string>) {
/**
* The `cloudflareEnv` is only used when deployed or when previewing locally.
* In development the environment variables are available through `env`.
*/
// First check user-provided API keys
if (userApiKeys?.[provider]) {
return userApiKeys[provider];
}
// Fall back to environment variables
switch (provider) {
case 'Anthropic':
return env.ANTHROPIC_API_KEY || cloudflareEnv.ANTHROPIC_API_KEY;
case 'OpenAI':
return env.OPENAI_API_KEY || cloudflareEnv.OPENAI_API_KEY;
case 'Google':
return env.GOOGLE_GENERATIVE_AI_API_KEY || cloudflareEnv.GOOGLE_GENERATIVE_AI_API_KEY;
case 'Groq':
return env.GROQ_API_KEY || cloudflareEnv.GROQ_API_KEY;
case 'HuggingFace':
return env.HuggingFace_API_KEY || cloudflareEnv.HuggingFace_API_KEY;
case 'OpenRouter':
return env.OPEN_ROUTER_API_KEY || cloudflareEnv.OPEN_ROUTER_API_KEY;
case 'Deepseek':
return env.DEEPSEEK_API_KEY || cloudflareEnv.DEEPSEEK_API_KEY;
case 'Mistral':
return env.MISTRAL_API_KEY || cloudflareEnv.MISTRAL_API_KEY;
case 'OpenAILike':
return env.OPENAI_LIKE_API_KEY || cloudflareEnv.OPENAI_LIKE_API_KEY;
case 'Together':
return env.TOGETHER_API_KEY || cloudflareEnv.TOGETHER_API_KEY;
case 'xAI':
return env.XAI_API_KEY || cloudflareEnv.XAI_API_KEY;
case 'Cohere':
return env.COHERE_API_KEY;
case 'AzureOpenAI':
return env.AZURE_OPENAI_API_KEY;
default:
return '';
}
}
export function getBaseURL(cloudflareEnv: Env, provider: string) {
switch (provider) {
case 'Together':
return env.TOGETHER_API_BASE_URL || cloudflareEnv.TOGETHER_API_BASE_URL || 'https://api.together.xyz/v1';
case 'OpenAILike':
return env.OPENAI_LIKE_API_BASE_URL || cloudflareEnv.OPENAI_LIKE_API_BASE_URL;
case 'LMStudio':
return env.LMSTUDIO_API_BASE_URL || cloudflareEnv.LMSTUDIO_API_BASE_URL || 'http://localhost:1234';
case 'Ollama': {
let baseUrl = env.OLLAMA_API_BASE_URL || cloudflareEnv.OLLAMA_API_BASE_URL || 'http://localhost:11434';
if (env.RUNNING_IN_DOCKER === 'true') {
baseUrl = baseUrl.replace('localhost', 'host.docker.internal');
}
return baseUrl;
}
default:
return '';
}
}

View File

@@ -1,176 +0,0 @@
/*
* @ts-nocheck
* Preventing TS checks with files presented in the video for a better presentation.
*/
import { getAPIKey, getBaseURL } from '~/lib/.server/llm/api-key';
import { createAnthropic } from '@ai-sdk/anthropic';
import { createOpenAI } from '@ai-sdk/openai';
import { createGoogleGenerativeAI } from '@ai-sdk/google';
import { ollama } from 'ollama-ai-provider';
import { createOpenRouter } from '@openrouter/ai-sdk-provider';
import { createMistral } from '@ai-sdk/mistral';
import { createCohere } from '@ai-sdk/cohere';
import type { LanguageModelV1 } from 'ai';
import type { IProviderSetting } from '~/types/model';
export const DEFAULT_NUM_CTX = process.env.DEFAULT_NUM_CTX ? parseInt(process.env.DEFAULT_NUM_CTX, 10) : 32768;
type OptionalApiKey = string | undefined;
export function getAnthropicModel(apiKey: OptionalApiKey, model: string) {
const anthropic = createAnthropic({
apiKey,
});
return anthropic(model);
}
export function getOpenAILikeModel(baseURL: string, apiKey: OptionalApiKey, model: string) {
const openai = createOpenAI({
baseURL,
apiKey,
});
return openai(model);
}
export function getCohereAIModel(apiKey: OptionalApiKey, model: string) {
const cohere = createCohere({
apiKey,
});
return cohere(model);
}
export function getOpenAIModel(apiKey: OptionalApiKey, model: string) {
const openai = createOpenAI({
apiKey,
});
return openai(model);
}
export function getMistralModel(apiKey: OptionalApiKey, model: string) {
const mistral = createMistral({
apiKey,
});
return mistral(model);
}
export function getGoogleModel(apiKey: OptionalApiKey, model: string) {
const google = createGoogleGenerativeAI({
apiKey,
});
return google(model);
}
export function getGroqModel(apiKey: OptionalApiKey, model: string) {
const openai = createOpenAI({
baseURL: 'https://api.groq.com/openai/v1',
apiKey,
});
return openai(model);
}
export function getHuggingFaceModel(apiKey: OptionalApiKey, model: string) {
const openai = createOpenAI({
baseURL: 'https://api-inference.huggingface.co/v1/',
apiKey,
});
return openai(model);
}
export function getOllamaModel(baseURL: string, model: string) {
const ollamaInstance = ollama(model, {
numCtx: DEFAULT_NUM_CTX,
}) as LanguageModelV1 & { config: any };
ollamaInstance.config.baseURL = `${baseURL}/api`;
return ollamaInstance;
}
export function getDeepseekModel(apiKey: OptionalApiKey, model: string) {
const openai = createOpenAI({
baseURL: 'https://api.deepseek.com/beta',
apiKey,
});
return openai(model);
}
export function getOpenRouterModel(apiKey: OptionalApiKey, model: string) {
const openRouter = createOpenRouter({
apiKey,
});
return openRouter.chat(model);
}
export function getLMStudioModel(baseURL: string, model: string) {
const lmstudio = createOpenAI({
baseUrl: `${baseURL}/v1`,
apiKey: '',
});
return lmstudio(model);
}
export function getXAIModel(apiKey: OptionalApiKey, model: string) {
const openai = createOpenAI({
baseURL: 'https://api.x.ai/v1',
apiKey,
});
return openai(model);
}
export function getModel(
provider: string,
model: string,
env: Env,
apiKeys?: Record<string, string>,
providerSettings?: Record<string, IProviderSetting>,
) {
/*
* let apiKey; // Declare first
* let baseURL;
*/
const apiKey = getAPIKey(env, provider, apiKeys); // Then assign
const baseURL = providerSettings?.[provider].baseUrl || getBaseURL(env, provider);
switch (provider) {
case 'Anthropic':
return getAnthropicModel(apiKey, model);
case 'OpenAI':
return getOpenAIModel(apiKey, model);
case 'Groq':
return getGroqModel(apiKey, model);
case 'HuggingFace':
return getHuggingFaceModel(apiKey, model);
case 'OpenRouter':
return getOpenRouterModel(apiKey, model);
case 'Google':
return getGoogleModel(apiKey, model);
case 'OpenAILike':
return getOpenAILikeModel(baseURL, apiKey, model);
case 'Together':
return getOpenAILikeModel(baseURL, apiKey, model);
case 'Deepseek':
return getDeepseekModel(apiKey, model);
case 'Mistral':
return getMistralModel(apiKey, model);
case 'LMStudio':
return getLMStudioModel(baseURL, model);
case 'xAI':
return getXAIModel(apiKey, model);
case 'Cohere':
return getCohereAIModel(apiKey, model);
default:
return getOllamaModel(baseURL, model);
}
}

View File

@@ -1,9 +1,21 @@
import { convertToCoreMessages, streamText as _streamText } from 'ai';
import { getModel } from '~/lib/.server/llm/model';
import { MAX_TOKENS } from './constants';
import { getSystemPrompt } from './prompts';
import { DEFAULT_MODEL, DEFAULT_PROVIDER, getModelList, MODEL_REGEX, PROVIDER_REGEX } from '~/utils/constants';
import { getSystemPrompt } from '~/lib/common/prompts/prompts';
import {
DEFAULT_MODEL,
DEFAULT_PROVIDER,
MODEL_REGEX,
MODIFICATIONS_TAG_NAME,
PROVIDER_LIST,
PROVIDER_REGEX,
WORK_DIR,
} from '~/utils/constants';
import ignore from 'ignore';
import type { IProviderSetting } from '~/types/model';
import { PromptLibrary } from '~/lib/common/prompt-library';
import { allowedHTMLElements } from '~/utils/markdown';
import { LLMManager } from '~/lib/modules/llm/manager';
import { createScopedLogger } from '~/utils/logger';
interface ToolResult<Name extends string, Args, Result> {
toolCallId: string;
@@ -23,6 +35,78 @@ export type Messages = Message[];
export type StreamingOptions = Omit<Parameters<typeof _streamText>[0], 'model'>;
export interface File {
type: 'file';
content: string;
isBinary: boolean;
}
export interface Folder {
type: 'folder';
}
type Dirent = File | Folder;
export type FileMap = Record<string, Dirent | undefined>;
export function simplifyBoltActions(input: string): string {
// Using regex to match boltAction tags that have type="file"
const regex = /(<boltAction[^>]*type="file"[^>]*>)([\s\S]*?)(<\/boltAction>)/g;
// Replace each matching occurrence
return input.replace(regex, (_0, openingTag, _2, closingTag) => {
return `${openingTag}\n ...\n ${closingTag}`;
});
}
// Common patterns to ignore, similar to .gitignore
const IGNORE_PATTERNS = [
'node_modules/**',
'.git/**',
'dist/**',
'build/**',
'.next/**',
'coverage/**',
'.cache/**',
'.vscode/**',
'.idea/**',
'**/*.log',
'**/.DS_Store',
'**/npm-debug.log*',
'**/yarn-debug.log*',
'**/yarn-error.log*',
'**/*lock.json',
'**/*lock.yml',
];
const ig = ignore().add(IGNORE_PATTERNS);
function createFilesContext(files: FileMap) {
let filePaths = Object.keys(files);
filePaths = filePaths.filter((x) => {
const relPath = x.replace('/home/project/', '');
return !ig.ignores(relPath);
});
const fileContexts = filePaths
.filter((x) => files[x] && files[x].type == 'file')
.map((path) => {
const dirent = files[path];
if (!dirent || dirent.type == 'folder') {
return '';
}
const codeWithLinesNumbers = dirent.content
.split('\n')
.map((v, i) => `${i + 1}|${v}`)
.join('\n');
return `<file path="${path}">\n${codeWithLinesNumbers}\n</file>`;
});
return `Below are the code files present in the webcontainer:\ncode format:\n<line number>|<line content>\n <codebase>${fileContexts.join('\n\n')}\n\n</codebase>`;
}
function extractPropertiesFromMessage(message: Message): { model: string; provider: string; content: string } {
const textContent = Array.isArray(message.content)
? message.content.find((item) => item.type === 'text')?.text || ''
@@ -59,40 +143,97 @@ function extractPropertiesFromMessage(message: Message): { model: string; provid
return { model, provider, content: cleanedContent };
}
const logger = createScopedLogger('stream-text');
export async function streamText(props: {
messages: Messages;
env: Env;
options?: StreamingOptions;
apiKeys?: Record<string, string>;
files?: FileMap;
providerSettings?: Record<string, IProviderSetting>;
promptId?: string;
contextOptimization?: boolean;
}) {
const { messages, env, options, apiKeys, providerSettings } = props;
const { messages, env: serverEnv, options, apiKeys, files, providerSettings, promptId, contextOptimization } = props;
// console.log({serverEnv});
let currentModel = DEFAULT_MODEL;
let currentProvider = DEFAULT_PROVIDER.name;
const MODEL_LIST = await getModelList(apiKeys || {}, providerSettings);
const processedMessages = messages.map((message) => {
if (message.role === 'user') {
const { model, provider, content } = extractPropertiesFromMessage(message);
if (MODEL_LIST.find((m) => m.name === model)) {
currentModel = model;
}
currentProvider = provider;
return { ...message, content };
} else if (message.role == 'assistant') {
let content = message.content;
if (contextOptimization) {
content = simplifyBoltActions(content);
}
return { ...message, content };
}
return message;
});
const modelDetails = MODEL_LIST.find((m) => m.name === currentModel);
const provider = PROVIDER_LIST.find((p) => p.name === currentProvider) || DEFAULT_PROVIDER;
const staticModels = LLMManager.getInstance().getStaticModelListFromProvider(provider);
let modelDetails = staticModels.find((m) => m.name === currentModel);
if (!modelDetails) {
const modelsList = [
...(provider.staticModels || []),
...(await LLMManager.getInstance().getModelListFromProvider(provider, {
apiKeys,
providerSettings,
serverEnv: serverEnv as any,
})),
];
if (!modelsList.length) {
throw new Error(`No models found for provider ${provider.name}`);
}
modelDetails = modelsList.find((m) => m.name === currentModel);
if (!modelDetails) {
// Fallback to first model
logger.warn(
`MODEL [${currentModel}] not found in provider [${provider.name}]. Falling back to first model. ${modelsList[0].name}`,
);
modelDetails = modelsList[0];
}
}
const dynamicMaxTokens = modelDetails && modelDetails.maxTokenAllowed ? modelDetails.maxTokenAllowed : MAX_TOKENS;
let systemPrompt =
PromptLibrary.getPropmtFromLibrary(promptId || 'default', {
cwd: WORK_DIR,
allowedHtmlElements: allowedHTMLElements,
modificationTagName: MODIFICATIONS_TAG_NAME,
}) ?? getSystemPrompt();
if (files && contextOptimization) {
const codeContext = createFilesContext(files);
systemPrompt = `${systemPrompt}\n\n ${codeContext}`;
}
logger.info(`Sending llm call to ${provider.name} with model ${modelDetails.name}`);
return _streamText({
model: getModel(currentProvider, currentModel, env, apiKeys, providerSettings) as any,
system: getSystemPrompt(),
model: provider.getModelInstance({
model: currentModel,
serverEnv,
apiKeys,
providerSettings,
}),
system: systemPrompt,
maxTokens: dynamicMaxTokens,
messages: convertToCoreMessages(processedMessages as any),
...options,

View File

@@ -0,0 +1,49 @@
import { getSystemPrompt } from './prompts/prompts';
import optimized from './prompts/optimized';
export interface PromptOptions {
cwd: string;
allowedHtmlElements: string[];
modificationTagName: string;
}
export class PromptLibrary {
static library: Record<
string,
{
label: string;
description: string;
get: (options: PromptOptions) => string;
}
> = {
default: {
label: 'Default Prompt',
description: 'This is the battle tested default system Prompt',
get: (options) => getSystemPrompt(options.cwd),
},
optimized: {
label: 'Optimized Prompt (experimental)',
description: 'an Experimental version of the prompt for lower token usage',
get: (options) => optimized(options),
},
};
static getList() {
return Object.entries(this.library).map(([key, value]) => {
const { label, description } = value;
return {
id: key,
label,
description,
};
});
}
static getPropmtFromLibrary(promptId: string, options: PromptOptions) {
const prompt = this.library[promptId];
if (!prompt) {
throw 'Prompt Now Found';
}
return this.library[promptId]?.get(options);
}
}

View File

@@ -0,0 +1,199 @@
import type { PromptOptions } from '~/lib/common/prompt-library';
export default (options: PromptOptions) => {
const { cwd, allowedHtmlElements, modificationTagName } = options;
return `
You are Bolt, an expert AI assistant and exceptional senior software developer with vast knowledge across multiple programming languages, frameworks, and best practices.
<system_constraints>
- Operating in WebContainer, an in-browser Node.js runtime
- Limited Python support: standard library only, no pip
- No C/C++ compiler, native binaries, or Git
- Prefer Node.js scripts over shell scripts
- Use Vite for web servers
- Databases: prefer libsql, sqlite, or non-native solutions
- When for react dont forget to write vite config and index.html to the project
Available shell commands: cat, cp, ls, mkdir, mv, rm, rmdir, touch, hostname, ps, pwd, uptime, env, node, python3, code, jq, curl, head, sort, tail, clear, which, export, chmod, scho, kill, ln, xxd, alias, getconf, loadenv, wasm, xdg-open, command, exit, source
</system_constraints>
<code_formatting_info>
Use 2 spaces for indentation
</code_formatting_info>
<message_formatting_info>
Available HTML elements: ${allowedHtmlElements.join(', ')}
</message_formatting_info>
<diff_spec>
File modifications in \`<${modificationTagName}>\` section:
- \`<diff path="/path/to/file">\`: GNU unified diff format
- \`<file path="/path/to/file">\`: Full new content
</diff_spec>
<chain_of_thought_instructions>
do not mention the phrase "chain of thought"
Before solutions, briefly outline implementation steps (2-4 lines max):
- List concrete steps
- Identify key components
- Note potential challenges
- Do not write the actual code just the plan and structure if needed
- Once completed planning start writing the artifacts
</chain_of_thought_instructions>
<artifact_info>
Create a single, comprehensive artifact for each project:
- Use \`<boltArtifact>\` tags with \`title\` and \`id\` attributes
- Use \`<boltAction>\` tags with \`type\` attribute:
- shell: Run commands
- file: Write/update files (use \`filePath\` attribute)
- start: Start dev server (only when necessary)
- Order actions logically
- Install dependencies first
- Provide full, updated content for all files
- Use coding best practices: modular, clean, readable code
</artifact_info>
# CRITICAL RULES - NEVER IGNORE
## File and Command Handling
1. ALWAYS use artifacts for file contents and commands - NO EXCEPTIONS
2. When writing a file, INCLUDE THE ENTIRE FILE CONTENT - NO PARTIAL UPDATES
3. For modifications, ONLY alter files that require changes - DO NOT touch unaffected files
## Response Format
4. Use markdown EXCLUSIVELY - HTML tags are ONLY allowed within artifacts
5. Be concise - Explain ONLY when explicitly requested
6. NEVER use the word "artifact" in responses
## Development Process
7. ALWAYS think and plan comprehensively before providing a solution
8. Current working directory: \`${cwd} \` - Use this for all file paths
9. Don't use cli scaffolding to steup the project, use cwd as Root of the project
11. For nodejs projects ALWAYS install dependencies after writing package.json file
## Coding Standards
10. ALWAYS create smaller, atomic components and modules
11. Modularity is PARAMOUNT - Break down functionality into logical, reusable parts
12. IMMEDIATELY refactor any file exceeding 250 lines
13. ALWAYS plan refactoring before implementation - Consider impacts on the entire system
## Artifact Usage
22. Use \`<boltArtifact>\` tags with \`title\` and \`id\` attributes for each project
23. Use \`<boltAction>\` tags with appropriate \`type\` attribute:
- \`shell\`: For running commands
- \`file\`: For writing/updating files (include \`filePath\` attribute)
- \`start\`: For starting dev servers (use only when necessary/ or new dependencies are installed)
24. Order actions logically - dependencies MUST be installed first
25. For Vite project must include vite config and index.html for entry point
26. Provide COMPLETE, up-to-date content for all files - NO placeholders or partial updates
CRITICAL: These rules are ABSOLUTE and MUST be followed WITHOUT EXCEPTION in EVERY response.
Examples:
<examples>
<example>
<user_query>Can you help me create a JavaScript function to calculate the factorial of a number?</user_query>
<assistant_response>
Certainly, I can help you create a JavaScript function to calculate the factorial of a number.
<boltArtifact id="factorial-function" title="JavaScript Factorial Function">
<boltAction type="file" filePath="index.js">
function factorial(n) {
...
}
...
</boltAction>
<boltAction type="shell">
node index.js
</boltAction>
</boltArtifact>
</assistant_response>
</example>
<example>
<user_query>Build a snake game</user_query>
<assistant_response>
Certainly! I'd be happy to help you build a snake game using JavaScript and HTML5 Canvas. This will be a basic implementation that you can later expand upon. Let's create the game step by step.
<boltArtifact id="snake-game" title="Snake Game in HTML and JavaScript">
<boltAction type="file" filePath="package.json">
{
"name": "snake",
"scripts": {
"dev": "vite"
}
...
}
</boltAction>
<boltAction type="shell">
npm install --save-dev vite
</boltAction>
<boltAction type="file" filePath="index.html">
...
</boltAction>
<boltAction type="start">
npm run dev
</boltAction>
</boltArtifact>
Now you can play the Snake game by opening the provided local server URL in your browser. Use the arrow keys to control the snake. Eat the red food to grow and increase your score. The game ends if you hit the wall or your own tail.
</assistant_response>
</example>
<example>
<user_query>Make a bouncing ball with real gravity using React</user_query>
<assistant_response>
Certainly! I'll create a bouncing ball with real gravity using React. We'll use the react-spring library for physics-based animations.
<boltArtifact id="bouncing-ball-react" title="Bouncing Ball with Gravity in React">
<boltAction type="file" filePath="package.json">
{
"name": "bouncing-ball",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "vite build",
"preview": "vite preview"
},
"dependencies": {
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-spring": "^9.7.1"
},
"devDependencies": {
"@types/react": "^18.0.28",
"@types/react-dom": "^18.0.11",
"@vitejs/plugin-react": "^3.1.0",
"vite": "^4.2.0"
}
}
</boltAction>
<boltAction type="file" filePath="index.html">
...
</boltAction>
<boltAction type="file" filePath="src/main.jsx">
...
</boltAction>
<boltAction type="file" filePath="src/index.css">
...
</boltAction>
<boltAction type="file" filePath="src/App.jsx">
...
</boltAction>
<boltAction type="start">
npm run dev
</boltAction>
</boltArtifact>
You can now view the bouncing ball animation in the preview. The ball will start falling from the top of the screen and bounce realistically when it hits the bottom.
</assistant_response>
</example>
</examples>
Always use artifacts for file contents and commands, following the format shown in these examples.
`;
};

View File

@@ -92,7 +92,9 @@ export function useEditChatDescription({
}
const lengthValid = trimmedDesc.length > 0 && trimmedDesc.length <= 100;
const characterValid = /^[a-zA-Z0-9\s]+$/.test(trimmedDesc);
// Allow letters, numbers, spaces, and common punctuation but exclude characters that could cause issues
const characterValid = /^[a-zA-Z0-9\s\-_.,!?()[\]{}'"]+$/.test(trimmedDesc);
if (!lengthValid) {
toast.error('Description must be between 1 and 100 characters.');
@@ -100,7 +102,7 @@ export function useEditChatDescription({
}
if (!characterValid) {
toast.error('Description can only contain alphanumeric characters and spaces.');
toast.error('Description can only contain letters, numbers, spaces, and basic punctuation.');
return false;
}

View File

@@ -23,14 +23,14 @@ const messageParser = new StreamingMessageParser({
logger.trace('onActionOpen', data.action);
// we only add shell actions when when the close tag got parsed because only then we have the content
if (data.action.type !== 'shell') {
if (data.action.type === 'file') {
workbenchStore.addAction(data);
}
},
onActionClose: (data) => {
logger.trace('onActionClose', data.action);
if (data.action.type === 'shell') {
if (data.action.type !== 'file') {
workbenchStore.addAction(data);
}

View File

@@ -1,14 +1,55 @@
import { useStore } from '@nanostores/react';
import { isDebugMode, isLocalModelsEnabled, LOCAL_PROVIDERS, providersStore } from '~/lib/stores/settings';
import {
isDebugMode,
isEventLogsEnabled,
isLocalModelsEnabled,
LOCAL_PROVIDERS,
promptStore,
providersStore,
latestBranchStore,
autoSelectStarterTemplate,
enableContextOptimizationStore,
} from '~/lib/stores/settings';
import { useCallback, useEffect, useState } from 'react';
import Cookies from 'js-cookie';
import type { IProviderSetting, ProviderInfo } from '~/types/model';
import { logStore } from '~/lib/stores/logs'; // assuming logStore is imported from this location
interface CommitData {
commit: string;
version?: string;
}
const versionData: CommitData = {
commit: __COMMIT_HASH,
version: __APP_VERSION,
};
export function useSettings() {
const providers = useStore(providersStore);
const debug = useStore(isDebugMode);
const eventLogs = useStore(isEventLogsEnabled);
const promptId = useStore(promptStore);
const isLocalModel = useStore(isLocalModelsEnabled);
const isLatestBranch = useStore(latestBranchStore);
const autoSelectTemplate = useStore(autoSelectStarterTemplate);
const [activeProviders, setActiveProviders] = useState<ProviderInfo[]>([]);
const contextOptimizationEnabled = useStore(enableContextOptimizationStore);
// Function to check if we're on stable version
const checkIsStableVersion = async () => {
try {
const response = await fetch(
`https://api.github.com/repos/stackblitz-labs/bolt.diy/git/refs/tags/v${versionData.version}`,
);
const data: { object: { sha: string } } = await response.json();
return versionData.commit.slice(0, 7) === data.object.sha.slice(0, 7);
} catch (error) {
console.warn('Error checking stable version:', error);
return false;
}
};
// reading values from cookies on mount
useEffect(() => {
@@ -17,15 +58,18 @@ export function useSettings() {
if (savedProviders) {
try {
const parsedProviders: Record<string, IProviderSetting> = JSON.parse(savedProviders);
Object.keys(parsedProviders).forEach((provider) => {
const currentProvider = providers[provider];
Object.keys(providers).forEach((provider) => {
const currentProviderSettings = parsedProviders[provider];
if (currentProviderSettings) {
providersStore.setKey(provider, {
...currentProvider,
...providers[provider],
settings: {
...parsedProviders[provider],
enabled: parsedProviders[provider].enabled ?? true,
...currentProviderSettings,
enabled: currentProviderSettings.enabled ?? true,
},
});
}
});
} catch (error) {
console.error('Failed to parse providers from cookies:', error);
@@ -39,12 +83,57 @@ export function useSettings() {
isDebugMode.set(savedDebugMode === 'true');
}
// load event logs from cookies
const savedEventLogs = Cookies.get('isEventLogsEnabled');
if (savedEventLogs) {
isEventLogsEnabled.set(savedEventLogs === 'true');
}
// load local models from cookies
const savedLocalModels = Cookies.get('isLocalModelsEnabled');
if (savedLocalModels) {
isLocalModelsEnabled.set(savedLocalModels === 'true');
}
const promptId = Cookies.get('promptId');
if (promptId) {
promptStore.set(promptId);
}
// load latest branch setting from cookies or determine based on version
const savedLatestBranch = Cookies.get('isLatestBranch');
let checkCommit = Cookies.get('commitHash');
if (checkCommit === undefined) {
checkCommit = versionData.commit;
}
if (savedLatestBranch === undefined || checkCommit !== versionData.commit) {
// If setting hasn't been set by user, check version
checkIsStableVersion().then((isStable) => {
const shouldUseLatest = !isStable;
latestBranchStore.set(shouldUseLatest);
Cookies.set('isLatestBranch', String(shouldUseLatest));
Cookies.set('commitHash', String(versionData.commit));
});
} else {
latestBranchStore.set(savedLatestBranch === 'true');
}
const autoSelectTemplate = Cookies.get('autoSelectTemplate');
if (autoSelectTemplate) {
autoSelectStarterTemplate.set(autoSelectTemplate === 'true');
}
const savedContextOptimizationEnabled = Cookies.get('contextOptimizationEnabled');
if (savedContextOptimizationEnabled) {
enableContextOptimizationStore.set(savedContextOptimizationEnabled === 'true');
}
}, []);
// writing values to cookies on change
@@ -80,21 +169,61 @@ export function useSettings() {
const enableDebugMode = useCallback((enabled: boolean) => {
isDebugMode.set(enabled);
logStore.logSystem(`Debug mode ${enabled ? 'enabled' : 'disabled'}`);
Cookies.set('isDebugEnabled', String(enabled));
}, []);
const enableEventLogs = useCallback((enabled: boolean) => {
isEventLogsEnabled.set(enabled);
logStore.logSystem(`Event logs ${enabled ? 'enabled' : 'disabled'}`);
Cookies.set('isEventLogsEnabled', String(enabled));
}, []);
const enableLocalModels = useCallback((enabled: boolean) => {
isLocalModelsEnabled.set(enabled);
logStore.logSystem(`Local models ${enabled ? 'enabled' : 'disabled'}`);
Cookies.set('isLocalModelsEnabled', String(enabled));
}, []);
const setPromptId = useCallback((promptId: string) => {
promptStore.set(promptId);
Cookies.set('promptId', promptId);
}, []);
const enableLatestBranch = useCallback((enabled: boolean) => {
latestBranchStore.set(enabled);
logStore.logSystem(`Main branch updates ${enabled ? 'enabled' : 'disabled'}`);
Cookies.set('isLatestBranch', String(enabled));
}, []);
const setAutoSelectTemplate = useCallback((enabled: boolean) => {
autoSelectStarterTemplate.set(enabled);
logStore.logSystem(`Auto select template ${enabled ? 'enabled' : 'disabled'}`);
Cookies.set('autoSelectTemplate', String(enabled));
}, []);
const enableContextOptimization = useCallback((enabled: boolean) => {
enableContextOptimizationStore.set(enabled);
logStore.logSystem(`Context optimization ${enabled ? 'enabled' : 'disabled'}`);
Cookies.set('contextOptimizationEnabled', String(enabled));
}, []);
return {
providers,
activeProviders,
updateProviderSettings,
debug,
enableDebugMode,
eventLogs,
enableEventLogs,
isLocalModel,
enableLocalModels,
promptId,
setPromptId,
isLatestBranch,
enableLatestBranch,
autoSelectTemplate,
setAutoSelectTemplate,
contextOptimizationEnabled,
enableContextOptimization,
};
}

View File

@@ -0,0 +1,129 @@
import type { LanguageModelV1 } from 'ai';
import type { ProviderInfo, ProviderConfig, ModelInfo } from './types';
import type { IProviderSetting } from '~/types/model';
import { createOpenAI } from '@ai-sdk/openai';
import { LLMManager } from './manager';
export abstract class BaseProvider implements ProviderInfo {
abstract name: string;
abstract staticModels: ModelInfo[];
abstract config: ProviderConfig;
cachedDynamicModels?: {
cacheId: string;
models: ModelInfo[];
};
getApiKeyLink?: string;
labelForGetApiKey?: string;
icon?: string;
getProviderBaseUrlAndKey(options: {
apiKeys?: Record<string, string>;
providerSettings?: IProviderSetting;
serverEnv?: Record<string, string>;
defaultBaseUrlKey: string;
defaultApiTokenKey: string;
}) {
const { apiKeys, providerSettings, serverEnv, defaultBaseUrlKey, defaultApiTokenKey } = options;
let settingsBaseUrl = providerSettings?.baseUrl;
const manager = LLMManager.getInstance();
if (settingsBaseUrl && settingsBaseUrl.length == 0) {
settingsBaseUrl = undefined;
}
const baseUrlKey = this.config.baseUrlKey || defaultBaseUrlKey;
let baseUrl =
settingsBaseUrl ||
serverEnv?.[baseUrlKey] ||
process?.env?.[baseUrlKey] ||
manager.env?.[baseUrlKey] ||
this.config.baseUrl;
if (baseUrl && baseUrl.endsWith('/')) {
baseUrl = baseUrl.slice(0, -1);
}
const apiTokenKey = this.config.apiTokenKey || defaultApiTokenKey;
const apiKey =
apiKeys?.[this.name] || serverEnv?.[apiTokenKey] || process?.env?.[apiTokenKey] || manager.env?.[baseUrlKey];
return {
baseUrl,
apiKey,
};
}
getModelsFromCache(options: {
apiKeys?: Record<string, string>;
providerSettings?: Record<string, IProviderSetting>;
serverEnv?: Record<string, string>;
}): ModelInfo[] | null {
if (!this.cachedDynamicModels) {
// console.log('no dynamic models',this.name);
return null;
}
const cacheKey = this.cachedDynamicModels.cacheId;
const generatedCacheKey = this.getDynamicModelsCacheKey(options);
if (cacheKey !== generatedCacheKey) {
// console.log('cache key mismatch',this.name,cacheKey,generatedCacheKey);
this.cachedDynamicModels = undefined;
return null;
}
return this.cachedDynamicModels.models;
}
getDynamicModelsCacheKey(options: {
apiKeys?: Record<string, string>;
providerSettings?: Record<string, IProviderSetting>;
serverEnv?: Record<string, string>;
}) {
return JSON.stringify({
apiKeys: options.apiKeys?.[this.name],
providerSettings: options.providerSettings?.[this.name],
serverEnv: options.serverEnv,
});
}
storeDynamicModels(
options: {
apiKeys?: Record<string, string>;
providerSettings?: Record<string, IProviderSetting>;
serverEnv?: Record<string, string>;
},
models: ModelInfo[],
) {
const cacheId = this.getDynamicModelsCacheKey(options);
// console.log('caching dynamic models',this.name,cacheId);
this.cachedDynamicModels = {
cacheId,
models,
};
}
// Declare the optional getDynamicModels method
getDynamicModels?(
apiKeys?: Record<string, string>,
settings?: IProviderSetting,
serverEnv?: Record<string, string>,
): Promise<ModelInfo[]>;
abstract getModelInstance(options: {
model: string;
serverEnv: Env;
apiKeys?: Record<string, string>;
providerSettings?: Record<string, IProviderSetting>;
}): LanguageModelV1;
}
type OptionalApiKey = string | undefined;
export function getOpenAILikeModel(baseURL: string, apiKey: OptionalApiKey, model: string) {
const openai = createOpenAI({
baseURL,
apiKey,
});
return openai(model);
}

View File

@@ -0,0 +1,203 @@
import type { IProviderSetting } from '~/types/model';
import { BaseProvider } from './base-provider';
import type { ModelInfo, ProviderInfo } from './types';
import * as providers from './registry';
import { createScopedLogger } from '~/utils/logger';
const logger = createScopedLogger('LLMManager');
export class LLMManager {
private static _instance: LLMManager;
private _providers: Map<string, BaseProvider> = new Map();
private _modelList: ModelInfo[] = [];
private readonly _env: any = {};
private constructor(_env: Record<string, string>) {
this._registerProvidersFromDirectory();
this._env = _env;
}
static getInstance(env: Record<string, string> = {}): LLMManager {
if (!LLMManager._instance) {
LLMManager._instance = new LLMManager(env);
}
return LLMManager._instance;
}
get env() {
return this._env;
}
private async _registerProvidersFromDirectory() {
try {
/*
* Dynamically import all files from the providers directory
* const providerModules = import.meta.glob('./providers/*.ts', { eager: true });
*/
// Look for exported classes that extend BaseProvider
for (const exportedItem of Object.values(providers)) {
if (typeof exportedItem === 'function' && exportedItem.prototype instanceof BaseProvider) {
const provider = new exportedItem();
try {
this.registerProvider(provider);
} catch (error: any) {
logger.warn('Failed To Register Provider: ', provider.name, 'error:', error.message);
}
}
}
} catch (error) {
logger.error('Error registering providers:', error);
}
}
registerProvider(provider: BaseProvider) {
if (this._providers.has(provider.name)) {
logger.warn(`Provider ${provider.name} is already registered. Skipping.`);
return;
}
logger.info('Registering Provider: ', provider.name);
this._providers.set(provider.name, provider);
this._modelList = [...this._modelList, ...provider.staticModels];
}
getProvider(name: string): BaseProvider | undefined {
return this._providers.get(name);
}
getAllProviders(): BaseProvider[] {
return Array.from(this._providers.values());
}
getModelList(): ModelInfo[] {
return this._modelList;
}
async updateModelList(options: {
apiKeys?: Record<string, string>;
providerSettings?: Record<string, IProviderSetting>;
serverEnv?: Record<string, string>;
}): Promise<ModelInfo[]> {
const { apiKeys, providerSettings, serverEnv } = options;
let enabledProviders = Array.from(this._providers.values()).map((p) => p.name);
if (providerSettings) {
enabledProviders = enabledProviders.filter((p) => providerSettings[p].enabled);
}
// Get dynamic models from all providers that support them
const dynamicModels = await Promise.all(
Array.from(this._providers.values())
.filter((provider) => enabledProviders.includes(provider.name))
.filter(
(provider): provider is BaseProvider & Required<Pick<ProviderInfo, 'getDynamicModels'>> =>
!!provider.getDynamicModels,
)
.map(async (provider) => {
const cachedModels = provider.getModelsFromCache(options);
if (cachedModels) {
return cachedModels;
}
const dynamicModels = await provider
.getDynamicModels(apiKeys, providerSettings?.[provider.name], serverEnv)
.then((models) => {
logger.info(`Caching ${models.length} dynamic models for ${provider.name}`);
provider.storeDynamicModels(options, models);
return models;
})
.catch((err) => {
logger.error(`Error getting dynamic models ${provider.name} :`, err);
return [];
});
return dynamicModels;
}),
);
// Combine static and dynamic models
const modelList = [
...dynamicModels.flat(),
...Array.from(this._providers.values()).flatMap((p) => p.staticModels || []),
];
this._modelList = modelList;
return modelList;
}
getStaticModelList() {
return [...this._providers.values()].flatMap((p) => p.staticModels || []);
}
async getModelListFromProvider(
providerArg: BaseProvider,
options: {
apiKeys?: Record<string, string>;
providerSettings?: Record<string, IProviderSetting>;
serverEnv?: Record<string, string>;
},
): Promise<ModelInfo[]> {
const provider = this._providers.get(providerArg.name);
if (!provider) {
throw new Error(`Provider ${providerArg.name} not found`);
}
const staticModels = provider.staticModels || [];
if (!provider.getDynamicModels) {
return staticModels;
}
const { apiKeys, providerSettings, serverEnv } = options;
const cachedModels = provider.getModelsFromCache({
apiKeys,
providerSettings,
serverEnv,
});
if (cachedModels) {
logger.info(`Found ${cachedModels.length} cached models for ${provider.name}`);
return [...cachedModels, ...staticModels];
}
logger.info(`Getting dynamic models for ${provider.name}`);
const dynamicModels = await provider
.getDynamicModels?.(apiKeys, providerSettings?.[provider.name], serverEnv)
.then((models) => {
logger.info(`Got ${models.length} dynamic models for ${provider.name}`);
provider.storeDynamicModels(options, models);
return models;
})
.catch((err) => {
logger.error(`Error getting dynamic models ${provider.name} :`, err);
return [];
});
return [...dynamicModels, ...staticModels];
}
getStaticModelListFromProvider(providerArg: BaseProvider) {
const provider = this._providers.get(providerArg.name);
if (!provider) {
throw new Error(`Provider ${providerArg.name} not found`);
}
return [...(provider.staticModels || [])];
}
getDefaultProvider(): BaseProvider {
const firstProvider = this._providers.values().next().value;
if (!firstProvider) {
throw new Error('No providers registered');
}
return firstProvider;
}
}

View File

@@ -0,0 +1,58 @@
import { BaseProvider } from '~/lib/modules/llm/base-provider';
import type { ModelInfo } from '~/lib/modules/llm/types';
import type { LanguageModelV1 } from 'ai';
import type { IProviderSetting } from '~/types/model';
import { createAnthropic } from '@ai-sdk/anthropic';
export default class AnthropicProvider extends BaseProvider {
name = 'Anthropic';
getApiKeyLink = 'https://console.anthropic.com/settings/keys';
config = {
apiTokenKey: 'ANTHROPIC_API_KEY',
};
staticModels: ModelInfo[] = [
{
name: 'claude-3-5-sonnet-latest',
label: 'Claude 3.5 Sonnet (new)',
provider: 'Anthropic',
maxTokenAllowed: 8000,
},
{
name: 'claude-3-5-sonnet-20240620',
label: 'Claude 3.5 Sonnet (old)',
provider: 'Anthropic',
maxTokenAllowed: 8000,
},
{
name: 'claude-3-5-haiku-latest',
label: 'Claude 3.5 Haiku (new)',
provider: 'Anthropic',
maxTokenAllowed: 8000,
},
{ name: 'claude-3-opus-latest', label: 'Claude 3 Opus', provider: 'Anthropic', maxTokenAllowed: 8000 },
{ name: 'claude-3-sonnet-20240229', label: 'Claude 3 Sonnet', provider: 'Anthropic', maxTokenAllowed: 8000 },
{ name: 'claude-3-haiku-20240307', label: 'Claude 3 Haiku', provider: 'Anthropic', maxTokenAllowed: 8000 },
];
getModelInstance: (options: {
model: string;
serverEnv: Env;
apiKeys?: Record<string, string>;
providerSettings?: Record<string, IProviderSetting>;
}) => LanguageModelV1 = (options) => {
const { apiKeys, providerSettings, serverEnv, model } = options;
const { apiKey } = this.getProviderBaseUrlAndKey({
apiKeys,
providerSettings,
serverEnv: serverEnv as any,
defaultBaseUrlKey: '',
defaultApiTokenKey: 'ANTHROPIC_API_KEY',
});
const anthropic = createAnthropic({
apiKey,
});
return anthropic(model);
};
}

View File

@@ -0,0 +1,54 @@
import { BaseProvider } from '~/lib/modules/llm/base-provider';
import type { ModelInfo } from '~/lib/modules/llm/types';
import type { IProviderSetting } from '~/types/model';
import type { LanguageModelV1 } from 'ai';
import { createCohere } from '@ai-sdk/cohere';
export default class CohereProvider extends BaseProvider {
name = 'Cohere';
getApiKeyLink = 'https://dashboard.cohere.com/api-keys';
config = {
apiTokenKey: 'COHERE_API_KEY',
};
staticModels: ModelInfo[] = [
{ name: 'command-r-plus-08-2024', label: 'Command R plus Latest', provider: 'Cohere', maxTokenAllowed: 4096 },
{ name: 'command-r-08-2024', label: 'Command R Latest', provider: 'Cohere', maxTokenAllowed: 4096 },
{ name: 'command-r-plus', label: 'Command R plus', provider: 'Cohere', maxTokenAllowed: 4096 },
{ name: 'command-r', label: 'Command R', provider: 'Cohere', maxTokenAllowed: 4096 },
{ name: 'command', label: 'Command', provider: 'Cohere', maxTokenAllowed: 4096 },
{ name: 'command-nightly', label: 'Command Nightly', provider: 'Cohere', maxTokenAllowed: 4096 },
{ name: 'command-light', label: 'Command Light', provider: 'Cohere', maxTokenAllowed: 4096 },
{ name: 'command-light-nightly', label: 'Command Light Nightly', provider: 'Cohere', maxTokenAllowed: 4096 },
{ name: 'c4ai-aya-expanse-8b', label: 'c4AI Aya Expanse 8b', provider: 'Cohere', maxTokenAllowed: 4096 },
{ name: 'c4ai-aya-expanse-32b', label: 'c4AI Aya Expanse 32b', provider: 'Cohere', maxTokenAllowed: 4096 },
];
getModelInstance(options: {
model: string;
serverEnv: Env;
apiKeys?: Record<string, string>;
providerSettings?: Record<string, IProviderSetting>;
}): LanguageModelV1 {
const { model, serverEnv, apiKeys, providerSettings } = options;
const { apiKey } = this.getProviderBaseUrlAndKey({
apiKeys,
providerSettings: providerSettings?.[this.name],
serverEnv: serverEnv as any,
defaultBaseUrlKey: '',
defaultApiTokenKey: 'COHERE_API_KEY',
});
if (!apiKey) {
throw new Error(`Missing API key for ${this.name} provider`);
}
const cohere = createCohere({
apiKey,
});
return cohere(model);
}
}

View File

@@ -0,0 +1,47 @@
import { BaseProvider } from '~/lib/modules/llm/base-provider';
import type { ModelInfo } from '~/lib/modules/llm/types';
import type { IProviderSetting } from '~/types/model';
import type { LanguageModelV1 } from 'ai';
import { createOpenAI } from '@ai-sdk/openai';
export default class DeepseekProvider extends BaseProvider {
name = 'Deepseek';
getApiKeyLink = 'https://platform.deepseek.com/apiKeys';
config = {
apiTokenKey: 'DEEPSEEK_API_KEY',
};
staticModels: ModelInfo[] = [
{ name: 'deepseek-coder', label: 'Deepseek-Coder', provider: 'Deepseek', maxTokenAllowed: 8000 },
{ name: 'deepseek-chat', label: 'Deepseek-Chat', provider: 'Deepseek', maxTokenAllowed: 8000 },
];
getModelInstance(options: {
model: string;
serverEnv: Env;
apiKeys?: Record<string, string>;
providerSettings?: Record<string, IProviderSetting>;
}): LanguageModelV1 {
const { model, serverEnv, apiKeys, providerSettings } = options;
const { apiKey } = this.getProviderBaseUrlAndKey({
apiKeys,
providerSettings: providerSettings?.[this.name],
serverEnv: serverEnv as any,
defaultBaseUrlKey: '',
defaultApiTokenKey: 'DEEPSEEK_API_KEY',
});
if (!apiKey) {
throw new Error(`Missing API key for ${this.name} provider`);
}
const openai = createOpenAI({
baseURL: 'https://api.deepseek.com/beta',
apiKey,
});
return openai(model);
}
}

View File

@@ -0,0 +1,51 @@
import { BaseProvider } from '~/lib/modules/llm/base-provider';
import type { ModelInfo } from '~/lib/modules/llm/types';
import type { IProviderSetting } from '~/types/model';
import type { LanguageModelV1 } from 'ai';
import { createGoogleGenerativeAI } from '@ai-sdk/google';
export default class GoogleProvider extends BaseProvider {
name = 'Google';
getApiKeyLink = 'https://aistudio.google.com/app/apikey';
config = {
apiTokenKey: 'GOOGLE_GENERATIVE_AI_API_KEY',
};
staticModels: ModelInfo[] = [
{ name: 'gemini-1.5-flash-latest', label: 'Gemini 1.5 Flash', provider: 'Google', maxTokenAllowed: 8192 },
{ name: 'gemini-2.0-flash-exp', label: 'Gemini 2.0 Flash', provider: 'Google', maxTokenAllowed: 8192 },
{ name: 'gemini-1.5-flash-002', label: 'Gemini 1.5 Flash-002', provider: 'Google', maxTokenAllowed: 8192 },
{ name: 'gemini-1.5-flash-8b', label: 'Gemini 1.5 Flash-8b', provider: 'Google', maxTokenAllowed: 8192 },
{ name: 'gemini-1.5-pro-latest', label: 'Gemini 1.5 Pro', provider: 'Google', maxTokenAllowed: 8192 },
{ name: 'gemini-1.5-pro-002', label: 'Gemini 1.5 Pro-002', provider: 'Google', maxTokenAllowed: 8192 },
{ name: 'gemini-exp-1206', label: 'Gemini exp-1206', provider: 'Google', maxTokenAllowed: 8192 },
];
getModelInstance(options: {
model: string;
serverEnv: any;
apiKeys?: Record<string, string>;
providerSettings?: Record<string, IProviderSetting>;
}): LanguageModelV1 {
const { model, serverEnv, apiKeys, providerSettings } = options;
const { apiKey } = this.getProviderBaseUrlAndKey({
apiKeys,
providerSettings: providerSettings?.[this.name],
serverEnv: serverEnv as any,
defaultBaseUrlKey: '',
defaultApiTokenKey: 'GOOGLE_GENERATIVE_AI_API_KEY',
});
if (!apiKey) {
throw new Error(`Missing API key for ${this.name} provider`);
}
const google = createGoogleGenerativeAI({
apiKey,
});
return google(model);
}
}

View File

@@ -0,0 +1,51 @@
import { BaseProvider } from '~/lib/modules/llm/base-provider';
import type { ModelInfo } from '~/lib/modules/llm/types';
import type { IProviderSetting } from '~/types/model';
import type { LanguageModelV1 } from 'ai';
import { createOpenAI } from '@ai-sdk/openai';
export default class GroqProvider extends BaseProvider {
name = 'Groq';
getApiKeyLink = 'https://console.groq.com/keys';
config = {
apiTokenKey: 'GROQ_API_KEY',
};
staticModels: ModelInfo[] = [
{ name: 'llama-3.1-8b-instant', label: 'Llama 3.1 8b (Groq)', provider: 'Groq', maxTokenAllowed: 8000 },
{ name: 'llama-3.2-11b-vision-preview', label: 'Llama 3.2 11b (Groq)', provider: 'Groq', maxTokenAllowed: 8000 },
{ name: 'llama-3.2-90b-vision-preview', label: 'Llama 3.2 90b (Groq)', provider: 'Groq', maxTokenAllowed: 8000 },
{ name: 'llama-3.2-3b-preview', label: 'Llama 3.2 3b (Groq)', provider: 'Groq', maxTokenAllowed: 8000 },
{ name: 'llama-3.2-1b-preview', label: 'Llama 3.2 1b (Groq)', provider: 'Groq', maxTokenAllowed: 8000 },
{ name: 'llama-3.3-70b-versatile', label: 'Llama 3.3 70b (Groq)', provider: 'Groq', maxTokenAllowed: 8000 },
];
getModelInstance(options: {
model: string;
serverEnv: Env;
apiKeys?: Record<string, string>;
providerSettings?: Record<string, IProviderSetting>;
}): LanguageModelV1 {
const { model, serverEnv, apiKeys, providerSettings } = options;
const { apiKey } = this.getProviderBaseUrlAndKey({
apiKeys,
providerSettings: providerSettings?.[this.name],
serverEnv: serverEnv as any,
defaultBaseUrlKey: '',
defaultApiTokenKey: 'GROQ_API_KEY',
});
if (!apiKey) {
throw new Error(`Missing API key for ${this.name} provider`);
}
const openai = createOpenAI({
baseURL: 'https://api.groq.com/openai/v1',
apiKey,
});
return openai(model);
}
}

View File

@@ -0,0 +1,111 @@
import { BaseProvider } from '~/lib/modules/llm/base-provider';
import type { ModelInfo } from '~/lib/modules/llm/types';
import type { IProviderSetting } from '~/types/model';
import type { LanguageModelV1 } from 'ai';
import { createOpenAI } from '@ai-sdk/openai';
export default class HuggingFaceProvider extends BaseProvider {
name = 'HuggingFace';
getApiKeyLink = 'https://huggingface.co/settings/tokens';
config = {
apiTokenKey: 'HuggingFace_API_KEY',
};
staticModels: ModelInfo[] = [
{
name: 'Qwen/Qwen2.5-Coder-32B-Instruct',
label: 'Qwen2.5-Coder-32B-Instruct (HuggingFace)',
provider: 'HuggingFace',
maxTokenAllowed: 8000,
},
{
name: '01-ai/Yi-1.5-34B-Chat',
label: 'Yi-1.5-34B-Chat (HuggingFace)',
provider: 'HuggingFace',
maxTokenAllowed: 8000,
},
{
name: 'codellama/CodeLlama-34b-Instruct-hf',
label: 'CodeLlama-34b-Instruct (HuggingFace)',
provider: 'HuggingFace',
maxTokenAllowed: 8000,
},
{
name: 'NousResearch/Hermes-3-Llama-3.1-8B',
label: 'Hermes-3-Llama-3.1-8B (HuggingFace)',
provider: 'HuggingFace',
maxTokenAllowed: 8000,
},
{
name: 'Qwen/Qwen2.5-Coder-32B-Instruct',
label: 'Qwen2.5-Coder-32B-Instruct (HuggingFace)',
provider: 'HuggingFace',
maxTokenAllowed: 8000,
},
{
name: 'Qwen/Qwen2.5-72B-Instruct',
label: 'Qwen2.5-72B-Instruct (HuggingFace)',
provider: 'HuggingFace',
maxTokenAllowed: 8000,
},
{
name: 'meta-llama/Llama-3.1-70B-Instruct',
label: 'Llama-3.1-70B-Instruct (HuggingFace)',
provider: 'HuggingFace',
maxTokenAllowed: 8000,
},
{
name: 'meta-llama/Llama-3.1-405B',
label: 'Llama-3.1-405B (HuggingFace)',
provider: 'HuggingFace',
maxTokenAllowed: 8000,
},
{
name: '01-ai/Yi-1.5-34B-Chat',
label: 'Yi-1.5-34B-Chat (HuggingFace)',
provider: 'HuggingFace',
maxTokenAllowed: 8000,
},
{
name: 'codellama/CodeLlama-34b-Instruct-hf',
label: 'CodeLlama-34b-Instruct (HuggingFace)',
provider: 'HuggingFace',
maxTokenAllowed: 8000,
},
{
name: 'NousResearch/Hermes-3-Llama-3.1-8B',
label: 'Hermes-3-Llama-3.1-8B (HuggingFace)',
provider: 'HuggingFace',
maxTokenAllowed: 8000,
},
];
getModelInstance(options: {
model: string;
serverEnv: Env;
apiKeys?: Record<string, string>;
providerSettings?: Record<string, IProviderSetting>;
}): LanguageModelV1 {
const { model, serverEnv, apiKeys, providerSettings } = options;
const { apiKey } = this.getProviderBaseUrlAndKey({
apiKeys,
providerSettings: providerSettings?.[this.name],
serverEnv: serverEnv as any,
defaultBaseUrlKey: '',
defaultApiTokenKey: 'HuggingFace_API_KEY',
});
if (!apiKey) {
throw new Error(`Missing API key for ${this.name} provider`);
}
const openai = createOpenAI({
baseURL: 'https://api-inference.huggingface.co/v1/',
apiKey,
});
return openai(model);
}
}

View File

@@ -0,0 +1,111 @@
import { BaseProvider } from '~/lib/modules/llm/base-provider';
import type { ModelInfo } from '~/lib/modules/llm/types';
import type { IProviderSetting } from '~/types/model';
import type { LanguageModelV1 } from 'ai';
import { createOpenAI } from '@ai-sdk/openai';
export default class HyperbolicProvider extends BaseProvider {
name = 'Hyperbolic';
getApiKeyLink = 'https://hyperbolic.xyz/settings';
config = {
apiTokenKey: 'HYPERBOLIC_API_KEY',
};
staticModels: ModelInfo[] = [
{
name: 'Qwen/Qwen2.5-Coder-32B-Instruct',
label: 'Qwen 2.5 Coder 32B Instruct',
provider: 'Hyperbolic',
maxTokenAllowed: 8192,
},
{
name: 'Qwen/Qwen2.5-72B-Instruct',
label: 'Qwen2.5-72B-Instruct',
provider: 'Hyperbolic',
maxTokenAllowed: 8192,
},
{
name: 'deepseek-ai/DeepSeek-V2.5',
label: 'DeepSeek-V2.5',
provider: 'Hyperbolic',
maxTokenAllowed: 8192,
},
{
name: 'Qwen/QwQ-32B-Preview',
label: 'QwQ-32B-Preview',
provider: 'Hyperbolic',
maxTokenAllowed: 8192,
},
{
name: 'Qwen/Qwen2-VL-72B-Instruct',
label: 'Qwen2-VL-72B-Instruct',
provider: 'Hyperbolic',
maxTokenAllowed: 8192,
},
];
async getDynamicModels(
apiKeys?: Record<string, string>,
settings?: IProviderSetting,
serverEnv: Record<string, string> = {},
): Promise<ModelInfo[]> {
const { baseUrl: fetchBaseUrl, apiKey } = this.getProviderBaseUrlAndKey({
apiKeys,
providerSettings: settings,
serverEnv,
defaultBaseUrlKey: '',
defaultApiTokenKey: 'HYPERBOLIC_API_KEY',
});
const baseUrl = fetchBaseUrl || 'https://api.hyperbolic.xyz/v1';
if (!apiKey) {
throw `Missing Api Key configuration for ${this.name} provider`;
}
const response = await fetch(`${baseUrl}/models`, {
headers: {
Authorization: `Bearer ${apiKey}`,
},
});
const res = (await response.json()) as any;
const data = res.data.filter((model: any) => model.object === 'model' && model.supports_chat);
return data.map((m: any) => ({
name: m.id,
label: `${m.id} - context ${m.context_length ? Math.floor(m.context_length / 1000) + 'k' : 'N/A'}`,
provider: this.name,
maxTokenAllowed: m.context_length || 8000,
}));
}
getModelInstance(options: {
model: string;
serverEnv: Env;
apiKeys?: Record<string, string>;
providerSettings?: Record<string, IProviderSetting>;
}): LanguageModelV1 {
const { model, serverEnv, apiKeys, providerSettings } = options;
const { apiKey } = this.getProviderBaseUrlAndKey({
apiKeys,
providerSettings: providerSettings?.[this.name],
serverEnv: serverEnv as any,
defaultBaseUrlKey: '',
defaultApiTokenKey: 'HYPERBOLIC_API_KEY',
});
if (!apiKey) {
throw `Missing Api Key configuration for ${this.name} provider`;
}
const openai = createOpenAI({
baseURL: 'https://api.hyperbolic.xyz/v1/',
apiKey,
});
return openai(model);
}
}

View File

@@ -0,0 +1,68 @@
import { BaseProvider } from '~/lib/modules/llm/base-provider';
import type { ModelInfo } from '~/lib/modules/llm/types';
import type { IProviderSetting } from '~/types/model';
import { createOpenAI } from '@ai-sdk/openai';
import type { LanguageModelV1 } from 'ai';
export default class LMStudioProvider extends BaseProvider {
name = 'LMStudio';
getApiKeyLink = 'https://lmstudio.ai/';
labelForGetApiKey = 'Get LMStudio';
icon = 'i-ph:cloud-arrow-down';
config = {
baseUrlKey: 'LMSTUDIO_API_BASE_URL',
baseUrl: 'http://localhost:1234/',
};
staticModels: ModelInfo[] = [];
async getDynamicModels(
apiKeys?: Record<string, string>,
settings?: IProviderSetting,
serverEnv: Record<string, string> = {},
): Promise<ModelInfo[]> {
const { baseUrl } = this.getProviderBaseUrlAndKey({
apiKeys,
providerSettings: settings,
serverEnv,
defaultBaseUrlKey: 'LMSTUDIO_API_BASE_URL',
defaultApiTokenKey: '',
});
if (!baseUrl) {
return [];
}
const response = await fetch(`${baseUrl}/v1/models`);
const data = (await response.json()) as { data: Array<{ id: string }> };
return data.data.map((model) => ({
name: model.id,
label: model.id,
provider: this.name,
maxTokenAllowed: 8000,
}));
}
getModelInstance: (options: {
model: string;
serverEnv: Env;
apiKeys?: Record<string, string>;
providerSettings?: Record<string, IProviderSetting>;
}) => LanguageModelV1 = (options) => {
const { apiKeys, providerSettings, serverEnv, model } = options;
const { baseUrl } = this.getProviderBaseUrlAndKey({
apiKeys,
providerSettings,
serverEnv: serverEnv as any,
defaultBaseUrlKey: 'OLLAMA_API_BASE_URL',
defaultApiTokenKey: '',
});
const lmstudio = createOpenAI({
baseUrl: `${baseUrl}/v1`,
apiKey: '',
});
return lmstudio(model);
};
}

View File

@@ -0,0 +1,53 @@
import { BaseProvider } from '~/lib/modules/llm/base-provider';
import type { ModelInfo } from '~/lib/modules/llm/types';
import type { IProviderSetting } from '~/types/model';
import type { LanguageModelV1 } from 'ai';
import { createMistral } from '@ai-sdk/mistral';
export default class MistralProvider extends BaseProvider {
name = 'Mistral';
getApiKeyLink = 'https://console.mistral.ai/api-keys/';
config = {
apiTokenKey: 'MISTRAL_API_KEY',
};
staticModels: ModelInfo[] = [
{ name: 'open-mistral-7b', label: 'Mistral 7B', provider: 'Mistral', maxTokenAllowed: 8000 },
{ name: 'open-mixtral-8x7b', label: 'Mistral 8x7B', provider: 'Mistral', maxTokenAllowed: 8000 },
{ name: 'open-mixtral-8x22b', label: 'Mistral 8x22B', provider: 'Mistral', maxTokenAllowed: 8000 },
{ name: 'open-codestral-mamba', label: 'Codestral Mamba', provider: 'Mistral', maxTokenAllowed: 8000 },
{ name: 'open-mistral-nemo', label: 'Mistral Nemo', provider: 'Mistral', maxTokenAllowed: 8000 },
{ name: 'ministral-8b-latest', label: 'Mistral 8B', provider: 'Mistral', maxTokenAllowed: 8000 },
{ name: 'mistral-small-latest', label: 'Mistral Small', provider: 'Mistral', maxTokenAllowed: 8000 },
{ name: 'codestral-latest', label: 'Codestral', provider: 'Mistral', maxTokenAllowed: 8000 },
{ name: 'mistral-large-latest', label: 'Mistral Large Latest', provider: 'Mistral', maxTokenAllowed: 8000 },
];
getModelInstance(options: {
model: string;
serverEnv: Env;
apiKeys?: Record<string, string>;
providerSettings?: Record<string, IProviderSetting>;
}): LanguageModelV1 {
const { model, serverEnv, apiKeys, providerSettings } = options;
const { apiKey } = this.getProviderBaseUrlAndKey({
apiKeys,
providerSettings: providerSettings?.[this.name],
serverEnv: serverEnv as any,
defaultBaseUrlKey: '',
defaultApiTokenKey: 'MISTRAL_API_KEY',
});
if (!apiKey) {
throw new Error(`Missing API key for ${this.name} provider`);
}
const mistral = createMistral({
apiKey,
});
return mistral(model);
}
}

View File

@@ -0,0 +1,101 @@
import { BaseProvider } from '~/lib/modules/llm/base-provider';
import type { ModelInfo } from '~/lib/modules/llm/types';
import type { IProviderSetting } from '~/types/model';
import type { LanguageModelV1 } from 'ai';
import { ollama } from 'ollama-ai-provider';
interface OllamaModelDetails {
parent_model: string;
format: string;
family: string;
families: string[];
parameter_size: string;
quantization_level: string;
}
export interface OllamaModel {
name: string;
model: string;
modified_at: string;
size: number;
digest: string;
details: OllamaModelDetails;
}
export interface OllamaApiResponse {
models: OllamaModel[];
}
export const DEFAULT_NUM_CTX = process?.env?.DEFAULT_NUM_CTX ? parseInt(process.env.DEFAULT_NUM_CTX, 10) : 32768;
export default class OllamaProvider extends BaseProvider {
name = 'Ollama';
getApiKeyLink = 'https://ollama.com/download';
labelForGetApiKey = 'Download Ollama';
icon = 'i-ph:cloud-arrow-down';
config = {
baseUrlKey: 'OLLAMA_API_BASE_URL',
};
staticModels: ModelInfo[] = [];
async getDynamicModels(
apiKeys?: Record<string, string>,
settings?: IProviderSetting,
serverEnv: Record<string, string> = {},
): Promise<ModelInfo[]> {
const { baseUrl } = this.getProviderBaseUrlAndKey({
apiKeys,
providerSettings: settings,
serverEnv,
defaultBaseUrlKey: 'OLLAMA_API_BASE_URL',
defaultApiTokenKey: '',
});
if (!baseUrl) {
return [];
}
const response = await fetch(`${baseUrl}/api/tags`);
const data = (await response.json()) as OllamaApiResponse;
// console.log({ ollamamodels: data.models });
return data.models.map((model: OllamaModel) => ({
name: model.name,
label: `${model.name} (${model.details.parameter_size})`,
provider: this.name,
maxTokenAllowed: 8000,
}));
}
getModelInstance: (options: {
model: string;
serverEnv: Env;
apiKeys?: Record<string, string>;
providerSettings?: Record<string, IProviderSetting>;
}) => LanguageModelV1 = (options) => {
const { apiKeys, providerSettings, serverEnv, model } = options;
let { baseUrl } = this.getProviderBaseUrlAndKey({
apiKeys,
providerSettings,
serverEnv: serverEnv as any,
defaultBaseUrlKey: 'OLLAMA_API_BASE_URL',
defaultApiTokenKey: '',
});
// Backend: Check if we're running in Docker
const isDocker = process.env.RUNNING_IN_DOCKER === 'true';
baseUrl = isDocker ? baseUrl.replace('localhost', 'host.docker.internal') : baseUrl;
baseUrl = isDocker ? baseUrl.replace('127.0.0.1', 'host.docker.internal') : baseUrl;
const ollamaInstance = ollama(model, {
numCtx: DEFAULT_NUM_CTX,
}) as LanguageModelV1 & { config: any };
ollamaInstance.config.baseURL = `${baseUrl}/api`;
return ollamaInstance;
};
}

View File

@@ -0,0 +1,131 @@
import { BaseProvider } from '~/lib/modules/llm/base-provider';
import type { ModelInfo } from '~/lib/modules/llm/types';
import type { IProviderSetting } from '~/types/model';
import type { LanguageModelV1 } from 'ai';
import { createOpenRouter } from '@openrouter/ai-sdk-provider';
interface OpenRouterModel {
name: string;
id: string;
context_length: number;
pricing: {
prompt: number;
completion: number;
};
}
interface OpenRouterModelsResponse {
data: OpenRouterModel[];
}
export default class OpenRouterProvider extends BaseProvider {
name = 'OpenRouter';
getApiKeyLink = 'https://openrouter.ai/settings/keys';
config = {
apiTokenKey: 'OPEN_ROUTER_API_KEY',
};
staticModels: ModelInfo[] = [
{
name: 'anthropic/claude-3.5-sonnet',
label: 'Anthropic: Claude 3.5 Sonnet (OpenRouter)',
provider: 'OpenRouter',
maxTokenAllowed: 8000,
},
{
name: 'anthropic/claude-3-haiku',
label: 'Anthropic: Claude 3 Haiku (OpenRouter)',
provider: 'OpenRouter',
maxTokenAllowed: 8000,
},
{
name: 'deepseek/deepseek-coder',
label: 'Deepseek-Coder V2 236B (OpenRouter)',
provider: 'OpenRouter',
maxTokenAllowed: 8000,
},
{
name: 'google/gemini-flash-1.5',
label: 'Google Gemini Flash 1.5 (OpenRouter)',
provider: 'OpenRouter',
maxTokenAllowed: 8000,
},
{
name: 'google/gemini-pro-1.5',
label: 'Google Gemini Pro 1.5 (OpenRouter)',
provider: 'OpenRouter',
maxTokenAllowed: 8000,
},
{ name: 'x-ai/grok-beta', label: 'xAI Grok Beta (OpenRouter)', provider: 'OpenRouter', maxTokenAllowed: 8000 },
{
name: 'mistralai/mistral-nemo',
label: 'OpenRouter Mistral Nemo (OpenRouter)',
provider: 'OpenRouter',
maxTokenAllowed: 8000,
},
{
name: 'qwen/qwen-110b-chat',
label: 'OpenRouter Qwen 110b Chat (OpenRouter)',
provider: 'OpenRouter',
maxTokenAllowed: 8000,
},
{ name: 'cohere/command', label: 'Cohere Command (OpenRouter)', provider: 'OpenRouter', maxTokenAllowed: 4096 },
];
async getDynamicModels(
_apiKeys?: Record<string, string>,
_settings?: IProviderSetting,
_serverEnv: Record<string, string> = {},
): Promise<ModelInfo[]> {
try {
const response = await fetch('https://openrouter.ai/api/v1/models', {
headers: {
'Content-Type': 'application/json',
},
});
const data = (await response.json()) as OpenRouterModelsResponse;
return data.data
.sort((a, b) => a.name.localeCompare(b.name))
.map((m) => ({
name: m.id,
label: `${m.name} - in:$${(m.pricing.prompt * 1_000_000).toFixed(2)} out:$${(m.pricing.completion * 1_000_000).toFixed(2)} - context ${Math.floor(m.context_length / 1000)}k`,
provider: this.name,
maxTokenAllowed: 8000,
}));
} catch (error) {
console.error('Error getting OpenRouter models:', error);
return [];
}
}
getModelInstance(options: {
model: string;
serverEnv: Env;
apiKeys?: Record<string, string>;
providerSettings?: Record<string, IProviderSetting>;
}): LanguageModelV1 {
const { model, serverEnv, apiKeys, providerSettings } = options;
const { apiKey } = this.getProviderBaseUrlAndKey({
apiKeys,
providerSettings: providerSettings?.[this.name],
serverEnv: serverEnv as any,
defaultBaseUrlKey: '',
defaultApiTokenKey: 'OPEN_ROUTER_API_KEY',
});
if (!apiKey) {
throw new Error(`Missing API key for ${this.name} provider`);
}
const openRouter = createOpenRouter({
apiKey,
});
const instance = openRouter.chat(model) as LanguageModelV1;
return instance;
}
}

View File

@@ -0,0 +1,72 @@
import { BaseProvider, getOpenAILikeModel } from '~/lib/modules/llm/base-provider';
import type { ModelInfo } from '~/lib/modules/llm/types';
import type { IProviderSetting } from '~/types/model';
import type { LanguageModelV1 } from 'ai';
export default class OpenAILikeProvider extends BaseProvider {
name = 'OpenAILike';
getApiKeyLink = undefined;
config = {
baseUrlKey: 'OPENAI_LIKE_API_BASE_URL',
apiTokenKey: 'OPENAI_LIKE_API_KEY',
};
staticModels: ModelInfo[] = [];
async getDynamicModels(
apiKeys?: Record<string, string>,
settings?: IProviderSetting,
serverEnv: Record<string, string> = {},
): Promise<ModelInfo[]> {
const { baseUrl, apiKey } = this.getProviderBaseUrlAndKey({
apiKeys,
providerSettings: settings,
serverEnv,
defaultBaseUrlKey: 'OPENAI_LIKE_API_BASE_URL',
defaultApiTokenKey: 'OPENAI_LIKE_API_KEY',
});
if (!baseUrl || !apiKey) {
return [];
}
const response = await fetch(`${baseUrl}/models`, {
headers: {
Authorization: `Bearer ${apiKey}`,
},
});
const res = (await response.json()) as any;
return res.data.map((model: any) => ({
name: model.id,
label: model.id,
provider: this.name,
maxTokenAllowed: 8000,
}));
}
getModelInstance(options: {
model: string;
serverEnv: Env;
apiKeys?: Record<string, string>;
providerSettings?: Record<string, IProviderSetting>;
}): LanguageModelV1 {
const { model, serverEnv, apiKeys, providerSettings } = options;
const { baseUrl, apiKey } = this.getProviderBaseUrlAndKey({
apiKeys,
providerSettings: providerSettings?.[this.name],
serverEnv: serverEnv as any,
defaultBaseUrlKey: 'OPENAI_LIKE_API_BASE_URL',
defaultApiTokenKey: 'OPENAI_LIKE_API_KEY',
});
if (!baseUrl || !apiKey) {
throw new Error(`Missing configuration for ${this.name} provider`);
}
return getOpenAILikeModel(baseUrl, apiKey, model);
}
}

View File

@@ -0,0 +1,49 @@
import { BaseProvider } from '~/lib/modules/llm/base-provider';
import type { ModelInfo } from '~/lib/modules/llm/types';
import type { IProviderSetting } from '~/types/model';
import type { LanguageModelV1 } from 'ai';
import { createOpenAI } from '@ai-sdk/openai';
export default class OpenAIProvider extends BaseProvider {
name = 'OpenAI';
getApiKeyLink = 'https://platform.openai.com/api-keys';
config = {
apiTokenKey: 'OPENAI_API_KEY',
};
staticModels: ModelInfo[] = [
{ name: 'gpt-4o', label: 'GPT-4o', provider: 'OpenAI', maxTokenAllowed: 8000 },
{ name: 'gpt-4o-mini', label: 'GPT-4o Mini', provider: 'OpenAI', maxTokenAllowed: 8000 },
{ name: 'gpt-4-turbo', label: 'GPT-4 Turbo', provider: 'OpenAI', maxTokenAllowed: 8000 },
{ name: 'gpt-4', label: 'GPT-4', provider: 'OpenAI', maxTokenAllowed: 8000 },
{ name: 'gpt-3.5-turbo', label: 'GPT-3.5 Turbo', provider: 'OpenAI', maxTokenAllowed: 8000 },
];
getModelInstance(options: {
model: string;
serverEnv: Env;
apiKeys?: Record<string, string>;
providerSettings?: Record<string, IProviderSetting>;
}): LanguageModelV1 {
const { model, serverEnv, apiKeys, providerSettings } = options;
const { apiKey } = this.getProviderBaseUrlAndKey({
apiKeys,
providerSettings: providerSettings?.[this.name],
serverEnv: serverEnv as any,
defaultBaseUrlKey: '',
defaultApiTokenKey: 'OPENAI_API_KEY',
});
if (!apiKey) {
throw new Error(`Missing API key for ${this.name} provider`);
}
const openai = createOpenAI({
apiKey,
});
return openai(model);
}
}

View File

@@ -0,0 +1,63 @@
import { BaseProvider } from '~/lib/modules/llm/base-provider';
import type { ModelInfo } from '~/lib/modules/llm/types';
import type { IProviderSetting } from '~/types/model';
import type { LanguageModelV1 } from 'ai';
import { createOpenAI } from '@ai-sdk/openai';
export default class PerplexityProvider extends BaseProvider {
name = 'Perplexity';
getApiKeyLink = 'https://www.perplexity.ai/settings/api';
config = {
apiTokenKey: 'PERPLEXITY_API_KEY',
};
staticModels: ModelInfo[] = [
{
name: 'llama-3.1-sonar-small-128k-online',
label: 'Sonar Small Online',
provider: 'Perplexity',
maxTokenAllowed: 8192,
},
{
name: 'llama-3.1-sonar-large-128k-online',
label: 'Sonar Large Online',
provider: 'Perplexity',
maxTokenAllowed: 8192,
},
{
name: 'llama-3.1-sonar-huge-128k-online',
label: 'Sonar Huge Online',
provider: 'Perplexity',
maxTokenAllowed: 8192,
},
];
getModelInstance(options: {
model: string;
serverEnv: Env;
apiKeys?: Record<string, string>;
providerSettings?: Record<string, IProviderSetting>;
}): LanguageModelV1 {
const { model, serverEnv, apiKeys, providerSettings } = options;
const { apiKey } = this.getProviderBaseUrlAndKey({
apiKeys,
providerSettings: providerSettings?.[this.name],
serverEnv: serverEnv as any,
defaultBaseUrlKey: '',
defaultApiTokenKey: 'PERPLEXITY_API_KEY',
});
if (!apiKey) {
throw new Error(`Missing API key for ${this.name} provider`);
}
const perplexity = createOpenAI({
baseURL: 'https://api.perplexity.ai/',
apiKey,
});
return perplexity(model);
}
}

View File

@@ -0,0 +1,95 @@
import { BaseProvider, getOpenAILikeModel } from '~/lib/modules/llm/base-provider';
import type { ModelInfo } from '~/lib/modules/llm/types';
import type { IProviderSetting } from '~/types/model';
import type { LanguageModelV1 } from 'ai';
export default class TogetherProvider extends BaseProvider {
name = 'Together';
getApiKeyLink = 'https://api.together.xyz/settings/api-keys';
config = {
baseUrlKey: 'TOGETHER_API_BASE_URL',
apiTokenKey: 'TOGETHER_API_KEY',
};
staticModels: ModelInfo[] = [
{
name: 'Qwen/Qwen2.5-Coder-32B-Instruct',
label: 'Qwen/Qwen2.5-Coder-32B-Instruct',
provider: 'Together',
maxTokenAllowed: 8000,
},
{
name: 'meta-llama/Llama-3.2-90B-Vision-Instruct-Turbo',
label: 'meta-llama/Llama-3.2-90B-Vision-Instruct-Turbo',
provider: 'Together',
maxTokenAllowed: 8000,
},
{
name: 'mistralai/Mixtral-8x7B-Instruct-v0.1',
label: 'Mixtral 8x7B Instruct',
provider: 'Together',
maxTokenAllowed: 8192,
},
];
async getDynamicModels(
apiKeys?: Record<string, string>,
settings?: IProviderSetting,
serverEnv: Record<string, string> = {},
): Promise<ModelInfo[]> {
const { baseUrl: fetchBaseUrl, apiKey } = this.getProviderBaseUrlAndKey({
apiKeys,
providerSettings: settings,
serverEnv,
defaultBaseUrlKey: 'TOGETHER_API_BASE_URL',
defaultApiTokenKey: 'TOGETHER_API_KEY',
});
const baseUrl = fetchBaseUrl || 'https://api.together.xyz/v1';
if (!baseUrl || !apiKey) {
return [];
}
// console.log({ baseUrl, apiKey });
const response = await fetch(`${baseUrl}/models`, {
headers: {
Authorization: `Bearer ${apiKey}`,
},
});
const res = (await response.json()) as any;
const data = (res || []).filter((model: any) => model.type === 'chat');
return data.map((m: any) => ({
name: m.id,
label: `${m.display_name} - in:$${m.pricing.input.toFixed(2)} out:$${m.pricing.output.toFixed(2)} - context ${Math.floor(m.context_length / 1000)}k`,
provider: this.name,
maxTokenAllowed: 8000,
}));
}
getModelInstance(options: {
model: string;
serverEnv: Env;
apiKeys?: Record<string, string>;
providerSettings?: Record<string, IProviderSetting>;
}): LanguageModelV1 {
const { model, serverEnv, apiKeys, providerSettings } = options;
const { baseUrl, apiKey } = this.getProviderBaseUrlAndKey({
apiKeys,
providerSettings: providerSettings?.[this.name],
serverEnv: serverEnv as any,
defaultBaseUrlKey: 'TOGETHER_API_BASE_URL',
defaultApiTokenKey: 'TOGETHER_API_KEY',
});
if (!baseUrl || !apiKey) {
throw new Error(`Missing configuration for ${this.name} provider`);
}
return getOpenAILikeModel(baseUrl, apiKey, model);
}
}

View File

@@ -0,0 +1,47 @@
import { BaseProvider } from '~/lib/modules/llm/base-provider';
import type { ModelInfo } from '~/lib/modules/llm/types';
import type { IProviderSetting } from '~/types/model';
import type { LanguageModelV1 } from 'ai';
import { createOpenAI } from '@ai-sdk/openai';
export default class XAIProvider extends BaseProvider {
name = 'xAI';
getApiKeyLink = 'https://docs.x.ai/docs/quickstart#creating-an-api-key';
config = {
apiTokenKey: 'XAI_API_KEY',
};
staticModels: ModelInfo[] = [
{ name: 'grok-beta', label: 'xAI Grok Beta', provider: 'xAI', maxTokenAllowed: 8000 },
{ name: 'grok-2-1212', label: 'xAI Grok2 1212', provider: 'xAI', maxTokenAllowed: 8000 },
];
getModelInstance(options: {
model: string;
serverEnv: Env;
apiKeys?: Record<string, string>;
providerSettings?: Record<string, IProviderSetting>;
}): LanguageModelV1 {
const { model, serverEnv, apiKeys, providerSettings } = options;
const { apiKey } = this.getProviderBaseUrlAndKey({
apiKeys,
providerSettings: providerSettings?.[this.name],
serverEnv: serverEnv as any,
defaultBaseUrlKey: '',
defaultApiTokenKey: 'XAI_API_KEY',
});
if (!apiKey) {
throw new Error(`Missing API key for ${this.name} provider`);
}
const openai = createOpenAI({
baseURL: 'https://api.x.ai/v1',
apiKey,
});
return openai(model);
}
}

View File

@@ -0,0 +1,35 @@
import AnthropicProvider from './providers/anthropic';
import CohereProvider from './providers/cohere';
import DeepseekProvider from './providers/deepseek';
import GoogleProvider from './providers/google';
import GroqProvider from './providers/groq';
import HuggingFaceProvider from './providers/huggingface';
import LMStudioProvider from './providers/lmstudio';
import MistralProvider from './providers/mistral';
import OllamaProvider from './providers/ollama';
import OpenRouterProvider from './providers/open-router';
import OpenAILikeProvider from './providers/openai-like';
import OpenAIProvider from './providers/openai';
import PerplexityProvider from './providers/perplexity';
import TogetherProvider from './providers/together';
import XAIProvider from './providers/xai';
import HyperbolicProvider from './providers/hyperbolic';
export {
AnthropicProvider,
CohereProvider,
DeepseekProvider,
GoogleProvider,
GroqProvider,
HuggingFaceProvider,
HyperbolicProvider,
MistralProvider,
OllamaProvider,
OpenAIProvider,
OpenRouterProvider,
OpenAILikeProvider,
PerplexityProvider,
XAIProvider,
TogetherProvider,
LMStudioProvider,
};

View File

@@ -0,0 +1,33 @@
import type { LanguageModelV1 } from 'ai';
import type { IProviderSetting } from '~/types/model';
export interface ModelInfo {
name: string;
label: string;
provider: string;
maxTokenAllowed: number;
}
export interface ProviderInfo {
name: string;
staticModels: ModelInfo[];
getDynamicModels?: (
apiKeys?: Record<string, string>,
settings?: IProviderSetting,
serverEnv?: Record<string, string>,
) => Promise<ModelInfo[]>;
getModelInstance: (options: {
model: string;
serverEnv: Env;
apiKeys?: Record<string, string>;
providerSettings?: Record<string, IProviderSetting>;
}) => LanguageModelV1;
getApiKeyLink?: string;
labelForGetApiKey?: string;
icon?: string;
}
export interface ProviderConfig {
baseUrlKey?: string;
baseUrl?: string;
apiTokenKey?: string;
}

View File

@@ -4,6 +4,7 @@ import { atom } from 'nanostores';
import type { Message } from 'ai';
import { toast } from 'react-toastify';
import { workbenchStore } from '~/lib/stores/workbench';
import { logStore } from '~/lib/stores/logs'; // Import logStore
import {
getMessages,
getNextId,
@@ -43,6 +44,8 @@ export function useChatHistory() {
setReady(true);
if (persistenceEnabled) {
const error = new Error('Chat persistence is unavailable');
logStore.logError('Chat persistence initialization failed', error);
toast.error('Chat persistence is unavailable');
}
@@ -69,6 +72,7 @@ export function useChatHistory() {
setReady(true);
})
.catch((error) => {
logStore.logError('Failed to load chat messages', error);
toast.error(error.message);
});
}

View File

@@ -1,7 +1,7 @@
import { WebContainer } from '@webcontainer/api';
import { atom, map, type MapStore } from 'nanostores';
import * as nodePath from 'node:path';
import type { BoltAction } from '~/types/actions';
import type { ActionAlert, BoltAction } from '~/types/actions';
import { createScopedLogger } from '~/utils/logger';
import { unreachable } from '~/utils/unreachable';
import type { ActionCallbackData } from './message-parser';
@@ -34,16 +34,51 @@ export type ActionStateUpdate =
type ActionsMap = MapStore<Record<string, ActionState>>;
class ActionCommandError extends Error {
readonly _output: string;
readonly _header: string;
constructor(message: string, output: string) {
// Create a formatted message that includes both the error message and output
const formattedMessage = `Failed To Execute Shell Command: ${message}\n\nOutput:\n${output}`;
super(formattedMessage);
// Set the output separately so it can be accessed programmatically
this._header = message;
this._output = output;
// Maintain proper prototype chain
Object.setPrototypeOf(this, ActionCommandError.prototype);
// Set the name of the error for better debugging
this.name = 'ActionCommandError';
}
// Optional: Add a method to get just the terminal output
get output() {
return this._output;
}
get header() {
return this._header;
}
}
export class ActionRunner {
#webcontainer: Promise<WebContainer>;
#currentExecutionPromise: Promise<void> = Promise.resolve();
#shellTerminal: () => BoltShell;
runnerId = atom<string>(`${Date.now()}`);
actions: ActionsMap = map({});
onAlert?: (alert: ActionAlert) => void;
constructor(webcontainerPromise: Promise<WebContainer>, getShellTerminal: () => BoltShell) {
constructor(
webcontainerPromise: Promise<WebContainer>,
getShellTerminal: () => BoltShell,
onAlert?: (alert: ActionAlert) => void,
) {
this.#webcontainer = webcontainerPromise;
this.#shellTerminal = getShellTerminal;
this.onAlert = onAlert;
}
addAction(data: ActionCallbackData) {
@@ -126,7 +161,25 @@ export class ActionRunner {
this.#runStartAction(action)
.then(() => this.#updateAction(actionId, { status: 'complete' }))
.catch(() => this.#updateAction(actionId, { status: 'failed', error: 'Action failed' }));
.catch((err: Error) => {
if (action.abortSignal.aborted) {
return;
}
this.#updateAction(actionId, { status: 'failed', error: 'Action failed' });
logger.error(`[${action.type}]:Action failed\n\n`, err);
if (!(err instanceof ActionCommandError)) {
return;
}
this.onAlert?.({
type: 'error',
title: 'Dev Server Failed',
description: err.header,
content: err.output,
});
});
/*
* adding a delay to avoid any race condition between 2 start actions
@@ -142,9 +195,24 @@ export class ActionRunner {
status: isStreaming ? 'running' : action.abortSignal.aborted ? 'aborted' : 'complete',
});
} catch (error) {
if (action.abortSignal.aborted) {
return;
}
this.#updateAction(actionId, { status: 'failed', error: 'Action failed' });
logger.error(`[${action.type}]:Action failed\n\n`, error);
if (!(error instanceof ActionCommandError)) {
return;
}
this.onAlert?.({
type: 'error',
title: 'Dev Server Failed',
description: error.header,
content: error.output,
});
// re-throw the error to be caught in the promise chain
throw error;
}
@@ -162,11 +230,14 @@ export class ActionRunner {
unreachable('Shell terminal not found');
}
const resp = await shell.executeCommand(this.runnerId.get(), action.content);
const resp = await shell.executeCommand(this.runnerId.get(), action.content, () => {
logger.debug(`[${action.type}]:Aborting Action\n\n`, action);
action.abort();
});
logger.debug(`${action.type} Shell Response: [exit code:${resp?.exitCode}]`);
if (resp?.exitCode != 0) {
throw new Error('Failed To Execute Shell Command');
throw new ActionCommandError(`Failed To Execute Shell Command`, resp?.output || 'No Output Available');
}
}
@@ -186,11 +257,14 @@ export class ActionRunner {
unreachable('Shell terminal not found');
}
const resp = await shell.executeCommand(this.runnerId.get(), action.content);
const resp = await shell.executeCommand(this.runnerId.get(), action.content, () => {
logger.debug(`[${action.type}]:Aborting Action\n\n`, action);
action.abort();
});
logger.debug(`${action.type} Shell Response: [exit code:${resp?.exitCode}]`);
if (resp?.exitCode != 0) {
throw new Error('Failed To Start Application');
throw new ActionCommandError('Failed To Start Application', resp?.output || 'No Output Available');
}
return resp;
@@ -202,8 +276,9 @@ export class ActionRunner {
}
const webcontainer = await this.#webcontainer;
const relativePath = nodePath.relative(webcontainer.workdir, action.filePath);
let folder = nodePath.dirname(action.filePath);
let folder = nodePath.dirname(relativePath);
// remove trailing slashes
folder = folder.replace(/\/+$/g, '');
@@ -218,8 +293,8 @@ export class ActionRunner {
}
try {
await webcontainer.fs.writeFile(action.filePath, action.content);
logger.debug(`File written ${action.filePath}`);
await webcontainer.fs.writeFile(relativePath, action.content);
logger.debug(`File written ${relativePath}`);
} catch (error) {
logger.error('Failed to write file\n\n', error);
}

View File

@@ -52,6 +52,18 @@ interface MessageState {
actionId: number;
}
function cleanoutMarkdownSyntax(content: string) {
const codeBlockRegex = /^\s*```\w*\n([\s\S]*?)\n\s*```\s*$/;
const match = content.match(codeBlockRegex);
// console.log('matching', !!match, content);
if (match) {
return match[1]; // Remove common leading 4-space indent
} else {
return content;
}
}
export class StreamingMessageParser {
#messages = new Map<string, MessageState>();
@@ -95,6 +107,11 @@ export class StreamingMessageParser {
let content = currentAction.content.trim();
if ('type' in currentAction && currentAction.type === 'file') {
// Remove markdown code block syntax if present and file is not markdown
if (!currentAction.filePath.endsWith('.md')) {
content = cleanoutMarkdownSyntax(content);
}
content += '\n';
}
@@ -120,7 +137,11 @@ export class StreamingMessageParser {
i = closeIndex + ARTIFACT_ACTION_TAG_CLOSE.length;
} else {
if ('type' in currentAction && currentAction.type === 'file') {
const content = input.slice(i);
let content = input.slice(i);
if (!currentAction.filePath.endsWith('.md')) {
content = cleanoutMarkdownSyntax(content);
}
this._options.callbacks?.onActionStream?.({
artifactId: currentArtifact.id,

149
app/lib/stores/logs.ts Normal file
View File

@@ -0,0 +1,149 @@
import { atom, map } from 'nanostores';
import Cookies from 'js-cookie';
import { createScopedLogger } from '~/utils/logger';
const logger = createScopedLogger('LogStore');
export interface LogEntry {
id: string;
timestamp: string;
level: 'info' | 'warning' | 'error' | 'debug';
message: string;
details?: Record<string, any>;
category: 'system' | 'provider' | 'user' | 'error';
}
const MAX_LOGS = 1000; // Maximum number of logs to keep in memory
class LogStore {
private _logs = map<Record<string, LogEntry>>({});
showLogs = atom(true);
constructor() {
// Load saved logs from cookies on initialization
this._loadLogs();
}
private _loadLogs() {
const savedLogs = Cookies.get('eventLogs');
if (savedLogs) {
try {
const parsedLogs = JSON.parse(savedLogs);
this._logs.set(parsedLogs);
} catch (error) {
logger.error('Failed to parse logs from cookies:', error);
}
}
}
private _saveLogs() {
const currentLogs = this._logs.get();
Cookies.set('eventLogs', JSON.stringify(currentLogs));
}
private _generateId(): string {
return `${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
}
private _trimLogs() {
const currentLogs = Object.entries(this._logs.get());
if (currentLogs.length > MAX_LOGS) {
const sortedLogs = currentLogs.sort(
([, a], [, b]) => new Date(b.timestamp).getTime() - new Date(a.timestamp).getTime(),
);
const newLogs = Object.fromEntries(sortedLogs.slice(0, MAX_LOGS));
this._logs.set(newLogs);
}
}
addLog(
message: string,
level: LogEntry['level'] = 'info',
category: LogEntry['category'] = 'system',
details?: Record<string, any>,
) {
const id = this._generateId();
const entry: LogEntry = {
id,
timestamp: new Date().toISOString(),
level,
message,
details,
category,
};
this._logs.setKey(id, entry);
this._trimLogs();
this._saveLogs();
return id;
}
// System events
logSystem(message: string, details?: Record<string, any>) {
return this.addLog(message, 'info', 'system', details);
}
// Provider events
logProvider(message: string, details?: Record<string, any>) {
return this.addLog(message, 'info', 'provider', details);
}
// User actions
logUserAction(message: string, details?: Record<string, any>) {
return this.addLog(message, 'info', 'user', details);
}
// Error events
logError(message: string, error?: Error | unknown, details?: Record<string, any>) {
const errorDetails = {
...(details || {}),
error:
error instanceof Error
? {
message: error.message,
stack: error.stack,
}
: error,
};
return this.addLog(message, 'error', 'error', errorDetails);
}
// Warning events
logWarning(message: string, details?: Record<string, any>) {
return this.addLog(message, 'warning', 'system', details);
}
// Debug events
logDebug(message: string, details?: Record<string, any>) {
return this.addLog(message, 'debug', 'system', details);
}
clearLogs() {
this._logs.set({});
this._saveLogs();
}
getLogs() {
return Object.values(this._logs.get()).sort(
(a, b) => new Date(b.timestamp).getTime() - new Date(a.timestamp).getTime(),
);
}
getFilteredLogs(level?: LogEntry['level'], category?: LogEntry['category'], searchQuery?: string) {
return this.getLogs().filter((log) => {
const matchesLevel = !level || level === 'debug' || log.level === level;
const matchesCategory = !category || log.category === category;
const matchesSearch =
!searchQuery ||
log.message.toLowerCase().includes(searchQuery.toLowerCase()) ||
JSON.stringify(log.details).toLowerCase().includes(searchQuery.toLowerCase());
return matchesLevel && matchesCategory && matchesSearch;
});
}
}
export const logStore = new LogStore();

View File

@@ -39,8 +39,20 @@ PROVIDER_LIST.forEach((provider) => {
},
};
});
//TODO: need to create one single map for all these flags
export const providersStore = map<ProviderSetting>(initialProviderSettings);
export const isDebugMode = atom(false);
export const isEventLogsEnabled = atom(false);
export const isLocalModelsEnabled = atom(true);
export const promptStore = atom<string>('default');
export const latestBranchStore = atom(false);
export const autoSelectStarterTemplate = atom(false);
export const enableContextOptimizationStore = atom(false);

View File

@@ -1,4 +1,5 @@
import { atom } from 'nanostores';
import { logStore } from './logs';
export type Theme = 'dark' | 'light';
@@ -26,10 +27,8 @@ function initStore() {
export function toggleTheme() {
const currentTheme = themeStore.get();
const newTheme = currentTheme === 'dark' ? 'light' : 'dark';
themeStore.set(newTheme);
logStore.logSystem(`Theme changed to ${newTheme} mode`);
localStorage.setItem(kTheme, newTheme);
document.querySelector('html')?.setAttribute('data-theme', newTheme);
}

View File

@@ -16,6 +16,8 @@ import * as nodePath from 'node:path';
import { extractRelativePath } from '~/utils/diff';
import { description } from '~/lib/persistence';
import Cookies from 'js-cookie';
import { createSampler } from '~/utils/sampler';
import type { ActionAlert } from '~/types/actions';
export interface ArtifactState {
id: string;
@@ -37,11 +39,15 @@ export class WorkbenchStore {
#editorStore = new EditorStore(this.#filesStore);
#terminalStore = new TerminalStore(webcontainer);
#reloadedMessages = new Set<string>();
artifacts: Artifacts = import.meta.hot?.data.artifacts ?? map({});
showWorkbench: WritableAtom<boolean> = import.meta.hot?.data.showWorkbench ?? atom(false);
currentView: WritableAtom<WorkbenchViewType> = import.meta.hot?.data.currentView ?? atom('code');
unsavedFiles: WritableAtom<Set<string>> = import.meta.hot?.data.unsavedFiles ?? atom(new Set<string>());
actionAlert: WritableAtom<ActionAlert | undefined> =
import.meta.hot?.data.unsavedFiles ?? atom<ActionAlert | undefined>(undefined);
modifiedFiles = new Set<string>();
artifactIdList: string[] = [];
#globalExecutionQueue = Promise.resolve();
@@ -51,6 +57,7 @@ export class WorkbenchStore {
import.meta.hot.data.unsavedFiles = this.unsavedFiles;
import.meta.hot.data.showWorkbench = this.showWorkbench;
import.meta.hot.data.currentView = this.currentView;
import.meta.hot.data.actionAlert = this.actionAlert;
}
}
@@ -88,6 +95,12 @@ export class WorkbenchStore {
get boltTerminal() {
return this.#terminalStore.boltTerminal;
}
get alert() {
return this.actionAlert;
}
clearAlert() {
this.actionAlert.set(undefined);
}
toggleTerminal(value?: boolean) {
this.#terminalStore.toggleTerminal(value);
@@ -232,6 +245,10 @@ export class WorkbenchStore {
// TODO: what do we wanna do and how do we wanna recover from this?
}
setReloadedMessages(messages: string[]) {
this.#reloadedMessages = new Set(messages);
}
addArtifact({ messageId, title, id, type }: ArtifactCallbackData) {
const artifact = this.#getArtifact(messageId);
@@ -248,7 +265,17 @@ export class WorkbenchStore {
title,
closed: false,
type,
runner: new ActionRunner(webcontainer, () => this.boltTerminal),
runner: new ActionRunner(
webcontainer,
() => this.boltTerminal,
(alert) => {
if (this.#reloadedMessages.has(messageId)) {
return;
}
this.actionAlert.set(alert);
},
),
});
}
@@ -262,9 +289,9 @@ export class WorkbenchStore {
this.artifacts.setKey(messageId, { ...artifact, ...state });
}
addAction(data: ActionCallbackData) {
this._addAction(data);
// this._addAction(data);
// this.addToExecutionQueue(()=>this._addAction(data))
this.addToExecutionQueue(() => this._addAction(data));
}
async _addAction(data: ActionCallbackData) {
const { messageId } = data;
@@ -280,7 +307,7 @@ export class WorkbenchStore {
runAction(data: ActionCallbackData, isStreaming: boolean = false) {
if (isStreaming) {
this._runAction(data, isStreaming);
this.actionStreamSampler(data, isStreaming);
} else {
this.addToExecutionQueue(() => this._runAction(data, isStreaming));
}
@@ -294,6 +321,12 @@ export class WorkbenchStore {
unreachable('Artifact not found');
}
const action = artifact.runner.actions.get()[data.actionId];
if (!action || action.executed) {
return;
}
if (data.action.type === 'file') {
const wc = await webcontainer;
const fullPath = nodePath.join(wc.workdir, data.action.filePath);
@@ -323,6 +356,10 @@ export class WorkbenchStore {
}
}
actionStreamSampler = createSampler(async (data: ActionCallbackData, isStreaming: boolean = false) => {
return await this._runAction(data, isStreaming);
}, 100); // TODO: remove this magic number to have it configurable
#getArtifact(id: string) {
const artifacts = this.artifacts.get();
return artifacts[id];

View File

@@ -1,5 +1,6 @@
import { WebContainer } from '@webcontainer/api';
import { WORK_DIR_NAME } from '~/utils/constants';
import { cleanStackTrace } from '~/utils/stacktrace';
interface WebContainerContext {
loaded: boolean;
@@ -22,10 +23,33 @@ if (!import.meta.env.SSR) {
import.meta.hot?.data.webcontainer ??
Promise.resolve()
.then(() => {
return WebContainer.boot({ workdirName: WORK_DIR_NAME });
return WebContainer.boot({
workdirName: WORK_DIR_NAME,
forwardPreviewErrors: true, // Enable error forwarding from iframes
});
})
.then((webcontainer) => {
.then(async (webcontainer) => {
webcontainerContext.loaded = true;
const { workbenchStore } = await import('~/lib/stores/workbench');
// Listen for preview errors
webcontainer.on('preview-message', (message) => {
console.log('WebContainer preview message:', message);
// Handle both uncaught exceptions and unhandled promise rejections
if (message.type === 'PREVIEW_UNCAUGHT_EXCEPTION' || message.type === 'PREVIEW_UNHANDLED_REJECTION') {
const isPromise = message.type === 'PREVIEW_UNHANDLED_REJECTION';
workbenchStore.actionAlert.set({
type: 'preview',
title: isPromise ? 'Unhandled Promise Rejection' : 'Uncaught Exception',
description: message.message,
content: `Error occurred at ${message.pathname}${message.search}${message.hash}\nPort: ${message.port}\n\nStack trace:\n${cleanStackTrace(message.stack || '')}`,
source: 'preview',
});
}
});
return webcontainer;
});

View File

@@ -78,6 +78,23 @@ export function Layout({ children }: { children: React.ReactNode }) {
);
}
import { logStore } from './lib/stores/logs';
export default function App() {
return <Outlet />;
const theme = useStore(themeStore);
useEffect(() => {
logStore.logSystem('Application initialized', {
theme,
platform: navigator.platform,
userAgent: navigator.userAgent,
timestamp: new Date().toISOString(),
});
}, []);
return (
<Layout>
<Outlet />
</Layout>
);
}

View File

@@ -1,25 +1,27 @@
import { type ActionFunctionArgs } from '@remix-run/cloudflare';
import { createDataStream } from 'ai';
import { MAX_RESPONSE_SEGMENTS, MAX_TOKENS } from '~/lib/.server/llm/constants';
import { CONTINUE_PROMPT } from '~/lib/.server/llm/prompts';
import { CONTINUE_PROMPT } from '~/lib/common/prompts/prompts';
import { streamText, type Messages, type StreamingOptions } from '~/lib/.server/llm/stream-text';
import SwitchableStream from '~/lib/.server/llm/switchable-stream';
import type { IProviderSetting } from '~/types/model';
import { createScopedLogger } from '~/utils/logger';
export async function action(args: ActionFunctionArgs) {
return chatAction(args);
}
function parseCookies(cookieHeader: string) {
const cookies: any = {};
const logger = createScopedLogger('api.chat');
function parseCookies(cookieHeader: string): Record<string, string> {
const cookies: Record<string, string> = {};
// Split the cookie string by semicolons and spaces
const items = cookieHeader.split(';').map((cookie) => cookie.trim());
items.forEach((item) => {
const [name, ...rest] = item.split('=');
if (name && rest) {
// Decode the name and value, and join value parts in case it contains '='
const decodedName = decodeURIComponent(name.trim());
const decodedValue = decodeURIComponent(rest.join('=').trim());
cookies[decodedName] = decodedValue;
@@ -30,14 +32,14 @@ function parseCookies(cookieHeader: string) {
}
async function chatAction({ context, request }: ActionFunctionArgs) {
const { messages } = await request.json<{
const { messages, files, promptId, contextOptimization } = await request.json<{
messages: Messages;
model: string;
files: any;
promptId?: string;
contextOptimization: boolean;
}>();
const cookieHeader = request.headers.get('Cookie');
// Parse the cookie's value (returns an object or null if no cookie exists)
const apiKeys = JSON.parse(parseCookies(cookieHeader || '').apiKeys || '{}');
const providerSettings: Record<string, IProviderSetting> = JSON.parse(
parseCookies(cookieHeader || '').providers || '{}',
@@ -45,12 +47,52 @@ async function chatAction({ context, request }: ActionFunctionArgs) {
const stream = new SwitchableStream();
const cumulativeUsage = {
completionTokens: 0,
promptTokens: 0,
totalTokens: 0,
};
try {
const options: StreamingOptions = {
toolChoice: 'none',
onFinish: async ({ text: content, finishReason }) => {
onFinish: async ({ text: content, finishReason, usage }) => {
logger.debug('usage', JSON.stringify(usage));
if (usage) {
cumulativeUsage.completionTokens += usage.completionTokens || 0;
cumulativeUsage.promptTokens += usage.promptTokens || 0;
cumulativeUsage.totalTokens += usage.totalTokens || 0;
}
if (finishReason !== 'length') {
return stream.close();
const encoder = new TextEncoder();
const usageStream = createDataStream({
async execute(dataStream) {
dataStream.writeMessageAnnotation({
type: 'usage',
value: {
completionTokens: cumulativeUsage.completionTokens,
promptTokens: cumulativeUsage.promptTokens,
totalTokens: cumulativeUsage.totalTokens,
},
});
},
onError: (error: any) => `Custom error: ${error.message}`,
}).pipeThrough(
new TransformStream({
transform: (chunk, controller) => {
// Convert the string stream to a byte stream
const str = typeof chunk === 'string' ? chunk : JSON.stringify(chunk);
controller.enqueue(encoder.encode(str));
},
}),
);
await stream.switchSource(usageStream);
await new Promise((resolve) => setTimeout(resolve, 0));
stream.close();
return;
}
if (stream.switches >= MAX_RESPONSE_SEGMENTS) {
@@ -59,20 +101,40 @@ async function chatAction({ context, request }: ActionFunctionArgs) {
const switchesLeft = MAX_RESPONSE_SEGMENTS - stream.switches;
console.log(`Reached max token limit (${MAX_TOKENS}): Continuing message (${switchesLeft} switches left)`);
logger.info(`Reached max token limit (${MAX_TOKENS}): Continuing message (${switchesLeft} switches left)`);
messages.push({ role: 'assistant', content });
messages.push({ role: 'user', content: CONTINUE_PROMPT });
const result = await streamText({ messages, env: context.cloudflare.env, options, apiKeys, providerSettings });
const result = await streamText({
messages,
env: context.cloudflare.env,
options,
apiKeys,
files,
providerSettings,
promptId,
contextOptimization,
});
return stream.switchSource(result.toAIStream());
stream.switchSource(result.toDataStream());
return;
},
};
const result = await streamText({ messages, env: context.cloudflare.env, options, apiKeys, providerSettings });
const result = await streamText({
messages,
env: context.cloudflare.env,
options,
apiKeys,
files,
providerSettings,
promptId,
contextOptimization,
});
stream.switchSource(result.toAIStream());
stream.switchSource(result.toDataStream());
return new Response(stream.readable, {
status: 200,
@@ -81,7 +143,7 @@ async function chatAction({ context, request }: ActionFunctionArgs) {
},
});
} catch (error: any) {
console.log(error);
logger.error(error);
if (error.message?.includes('API key')) {
throw new Response('Invalid or missing API key', {

View File

@@ -1,12 +1,10 @@
import { type ActionFunctionArgs } from '@remix-run/cloudflare';
import { StreamingTextResponse, parseStreamPart } from 'ai';
//import { StreamingTextResponse, parseStreamPart } from 'ai';
import { streamText } from '~/lib/.server/llm/stream-text';
import { stripIndents } from '~/utils/stripIndent';
import type { IProviderSetting, ProviderInfo } from '~/types/model';
const encoder = new TextEncoder();
const decoder = new TextDecoder();
export async function action(args: ActionFunctionArgs) {
return enhancerAction(args);
}
@@ -86,7 +84,7 @@ async function enhancerAction({ context, request }: ActionFunctionArgs) {
- Use professional language
For invalid or unclear prompts:
- Respond with a clear, professional guidance message
- Respond with clear, professional guidance
- Keep responses concise and actionable
- Maintain a helpful, constructive tone
- Focus on what the user should provide
@@ -106,29 +104,12 @@ async function enhancerAction({ context, request }: ActionFunctionArgs) {
providerSettings,
});
const transformStream = new TransformStream({
transform(chunk, controller) {
const text = decoder.decode(chunk);
const lines = text.split('\n').filter((line) => line.trim() !== '');
for (const line of lines) {
try {
const parsed = parseStreamPart(line);
if (parsed.type === 'text') {
controller.enqueue(encoder.encode(parsed.value));
}
} catch (e) {
// skip invalid JSON lines
console.warn('Failed to parse stream part:', line, e);
}
}
return new Response(result.textStream, {
status: 200,
headers: {
'Content-Type': 'text/plain; charset=utf-8',
},
});
const transformedStream = result.toDataStream().pipeThrough(transformStream);
return new StreamingTextResponse(transformedStream);
} catch (error: unknown) {
console.log(error);

163
app/routes/api.llmcall.ts Normal file
View File

@@ -0,0 +1,163 @@
import { type ActionFunctionArgs } from '@remix-run/cloudflare';
//import { StreamingTextResponse, parseStreamPart } from 'ai';
import { streamText } from '~/lib/.server/llm/stream-text';
import type { IProviderSetting, ProviderInfo } from '~/types/model';
import { generateText } from 'ai';
import { getModelList, PROVIDER_LIST } from '~/utils/constants';
import { MAX_TOKENS } from '~/lib/.server/llm/constants';
export async function action(args: ActionFunctionArgs) {
return llmCallAction(args);
}
function parseCookies(cookieHeader: string) {
const cookies: any = {};
// Split the cookie string by semicolons and spaces
const items = cookieHeader.split(';').map((cookie) => cookie.trim());
items.forEach((item) => {
const [name, ...rest] = item.split('=');
if (name && rest) {
// Decode the name and value, and join value parts in case it contains '='
const decodedName = decodeURIComponent(name.trim());
const decodedValue = decodeURIComponent(rest.join('=').trim());
cookies[decodedName] = decodedValue;
}
});
return cookies;
}
async function llmCallAction({ context, request }: ActionFunctionArgs) {
const { system, message, model, provider, streamOutput } = await request.json<{
system: string;
message: string;
model: string;
provider: ProviderInfo;
streamOutput?: boolean;
}>();
const { name: providerName } = provider;
// validate 'model' and 'provider' fields
if (!model || typeof model !== 'string') {
throw new Response('Invalid or missing model', {
status: 400,
statusText: 'Bad Request',
});
}
if (!providerName || typeof providerName !== 'string') {
throw new Response('Invalid or missing provider', {
status: 400,
statusText: 'Bad Request',
});
}
const cookieHeader = request.headers.get('Cookie');
// Parse the cookie's value (returns an object or null if no cookie exists)
const apiKeys = JSON.parse(parseCookies(cookieHeader || '').apiKeys || '{}');
const providerSettings: Record<string, IProviderSetting> = JSON.parse(
parseCookies(cookieHeader || '').providers || '{}',
);
if (streamOutput) {
try {
const result = await streamText({
options: {
system,
},
messages: [
{
role: 'user',
content: `${message}`,
},
],
env: context.cloudflare.env,
apiKeys,
providerSettings,
});
return new Response(result.textStream, {
status: 200,
headers: {
'Content-Type': 'text/plain; charset=utf-8',
},
});
} catch (error: unknown) {
console.log(error);
if (error instanceof Error && error.message?.includes('API key')) {
throw new Response('Invalid or missing API key', {
status: 401,
statusText: 'Unauthorized',
});
}
throw new Response(null, {
status: 500,
statusText: 'Internal Server Error',
});
}
} else {
try {
const MODEL_LIST = await getModelList({ apiKeys, providerSettings, serverEnv: context.cloudflare.env as any });
const modelDetails = MODEL_LIST.find((m) => m.name === model);
if (!modelDetails) {
throw new Error('Model not found');
}
const dynamicMaxTokens = modelDetails && modelDetails.maxTokenAllowed ? modelDetails.maxTokenAllowed : MAX_TOKENS;
const providerInfo = PROVIDER_LIST.find((p) => p.name === provider.name);
if (!providerInfo) {
throw new Error('Provider not found');
}
const result = await generateText({
system,
messages: [
{
role: 'user',
content: `${message}`,
},
],
model: providerInfo.getModelInstance({
model: modelDetails.name,
serverEnv: context.cloudflare.env as any,
apiKeys,
providerSettings,
}),
maxTokens: dynamicMaxTokens,
toolChoice: 'none',
});
return new Response(JSON.stringify(result), {
status: 200,
headers: {
'Content-Type': 'application/json',
},
});
} catch (error: unknown) {
console.log(error);
if (error instanceof Error && error.message?.includes('API key')) {
throw new Response('Invalid or missing API key', {
status: 401,
statusText: 'Unauthorized',
});
}
throw new Response(null, {
status: 500,
statusText: 'Internal Server Error',
});
}
}
}

View File

@@ -4,6 +4,7 @@ import { ClientOnly } from 'remix-utils/client-only';
import { BaseChat } from '~/components/chat/BaseChat';
import { GitUrlImport } from '~/components/git/GitUrlImport.client';
import { Header } from '~/components/header/Header';
import BackgroundRays from '~/components/ui/BackgroundRays';
export const meta: MetaFunction = () => {
return [{ title: 'Bolt' }, { name: 'description', content: 'Talk with Bolt, an AI assistant from StackBlitz' }];
@@ -15,7 +16,8 @@ export async function loader(args: LoaderFunctionArgs) {
export default function Index() {
return (
<div className="flex flex-col h-full w-full">
<div className="flex flex-col h-full w-full bg-bolt-elements-background-depth-1">
<BackgroundRays />
<Header />
<ClientOnly fallback={<BaseChat />}>{() => <GitUrlImport />}</ClientOnly>
</div>

View File

@@ -20,3 +20,11 @@ export interface StartAction extends BaseAction {
export type BoltAction = FileAction | ShellAction | StartAction;
export type BoltActionData = BoltAction | BaseAction;
export interface ActionAlert {
type: string;
title: string;
description: string;
content: string;
source?: 'terminal' | 'preview'; // Add source to differentiate between terminal and preview errors
}

View File

@@ -3,3 +3,11 @@ interface Window {
webkitSpeechRecognition: typeof SpeechRecognition;
SpeechRecognition: typeof SpeechRecognition;
}
interface Performance {
memory?: {
jsHeapSizeLimit: number;
totalJSHeapSize: number;
usedJSHeapSize: number;
};
}

View File

@@ -1,9 +1,14 @@
import type { ModelInfo } from '~/utils/types';
import type { ModelInfo } from '~/lib/modules/llm/types';
export type ProviderInfo = {
staticModels: ModelInfo[];
name: string;
getDynamicModels?: (apiKeys?: Record<string, string>, providerSettings?: IProviderSetting) => Promise<ModelInfo[]>;
getDynamicModels?: (
providerName: string,
apiKeys?: Record<string, string>,
providerSettings?: IProviderSetting,
serverEnv?: Record<string, string>,
) => Promise<ModelInfo[]>;
getApiKeyLink?: string;
labelForGetApiKey?: string;
icon?: string;

8
app/types/template.ts Normal file
View File

@@ -0,0 +1,8 @@
export interface Template {
name: string;
label: string;
description: string;
githubRepo: string;
tags?: string[];
icon?: string;
}

View File

@@ -1,7 +1,8 @@
import Cookies from 'js-cookie';
import type { ModelInfo, OllamaApiResponse, OllamaModel } from './types';
import type { ProviderInfo, IProviderSetting } from '~/types/model';
import { createScopedLogger } from './logger';
import type { IProviderSetting } from '~/types/model';
import { LLMManager } from '~/lib/modules/llm/manager';
import type { ModelInfo } from '~/lib/modules/llm/types';
import type { Template } from '~/types/template';
export const WORK_DIR_NAME = 'project';
export const WORK_DIR = `/home/${WORK_DIR_NAME}`;
@@ -11,515 +12,138 @@ export const PROVIDER_REGEX = /\[Provider: (.*?)\]\n\n/;
export const DEFAULT_MODEL = 'claude-3-5-sonnet-latest';
export const PROMPT_COOKIE_KEY = 'cachedPrompt';
const logger = createScopedLogger('Constants');
const llmManager = LLMManager.getInstance(import.meta.env);
const PROVIDER_LIST: ProviderInfo[] = [
{
name: 'Anthropic',
staticModels: [
{
name: 'claude-3-5-sonnet-latest',
label: 'Claude 3.5 Sonnet (new)',
provider: 'Anthropic',
maxTokenAllowed: 8000,
},
{
name: 'claude-3-5-sonnet-20240620',
label: 'Claude 3.5 Sonnet (old)',
provider: 'Anthropic',
maxTokenAllowed: 8000,
},
{
name: 'claude-3-5-haiku-latest',
label: 'Claude 3.5 Haiku (new)',
provider: 'Anthropic',
maxTokenAllowed: 8000,
},
{ name: 'claude-3-opus-latest', label: 'Claude 3 Opus', provider: 'Anthropic', maxTokenAllowed: 8000 },
{ name: 'claude-3-sonnet-20240229', label: 'Claude 3 Sonnet', provider: 'Anthropic', maxTokenAllowed: 8000 },
{ name: 'claude-3-haiku-20240307', label: 'Claude 3 Haiku', provider: 'Anthropic', maxTokenAllowed: 8000 },
],
getApiKeyLink: 'https://console.anthropic.com/settings/keys',
},
{
name: 'Ollama',
staticModels: [],
getDynamicModels: getOllamaModels,
getApiKeyLink: 'https://ollama.com/download',
labelForGetApiKey: 'Download Ollama',
icon: 'i-ph:cloud-arrow-down',
},
{
name: 'OpenAILike',
staticModels: [],
getDynamicModels: getOpenAILikeModels,
},
{
name: 'Cohere',
staticModels: [
{ name: 'command-r-plus-08-2024', label: 'Command R plus Latest', provider: 'Cohere', maxTokenAllowed: 4096 },
{ name: 'command-r-08-2024', label: 'Command R Latest', provider: 'Cohere', maxTokenAllowed: 4096 },
{ name: 'command-r-plus', label: 'Command R plus', provider: 'Cohere', maxTokenAllowed: 4096 },
{ name: 'command-r', label: 'Command R', provider: 'Cohere', maxTokenAllowed: 4096 },
{ name: 'command', label: 'Command', provider: 'Cohere', maxTokenAllowed: 4096 },
{ name: 'command-nightly', label: 'Command Nightly', provider: 'Cohere', maxTokenAllowed: 4096 },
{ name: 'command-light', label: 'Command Light', provider: 'Cohere', maxTokenAllowed: 4096 },
{ name: 'command-light-nightly', label: 'Command Light Nightly', provider: 'Cohere', maxTokenAllowed: 4096 },
{ name: 'c4ai-aya-expanse-8b', label: 'c4AI Aya Expanse 8b', provider: 'Cohere', maxTokenAllowed: 4096 },
{ name: 'c4ai-aya-expanse-32b', label: 'c4AI Aya Expanse 32b', provider: 'Cohere', maxTokenAllowed: 4096 },
],
getApiKeyLink: 'https://dashboard.cohere.com/api-keys',
},
{
name: 'OpenRouter',
staticModels: [
{ name: 'gpt-4o', label: 'GPT-4o', provider: 'OpenAI', maxTokenAllowed: 8000 },
{
name: 'anthropic/claude-3.5-sonnet',
label: 'Anthropic: Claude 3.5 Sonnet (OpenRouter)',
provider: 'OpenRouter',
maxTokenAllowed: 8000,
},
{
name: 'anthropic/claude-3-haiku',
label: 'Anthropic: Claude 3 Haiku (OpenRouter)',
provider: 'OpenRouter',
maxTokenAllowed: 8000,
},
{
name: 'deepseek/deepseek-coder',
label: 'Deepseek-Coder V2 236B (OpenRouter)',
provider: 'OpenRouter',
maxTokenAllowed: 8000,
},
{
name: 'google/gemini-flash-1.5',
label: 'Google Gemini Flash 1.5 (OpenRouter)',
provider: 'OpenRouter',
maxTokenAllowed: 8000,
},
{
name: 'google/gemini-pro-1.5',
label: 'Google Gemini Pro 1.5 (OpenRouter)',
provider: 'OpenRouter',
maxTokenAllowed: 8000,
},
{ name: 'x-ai/grok-beta', label: 'xAI Grok Beta (OpenRouter)', provider: 'OpenRouter', maxTokenAllowed: 8000 },
{
name: 'mistralai/mistral-nemo',
label: 'OpenRouter Mistral Nemo (OpenRouter)',
provider: 'OpenRouter',
maxTokenAllowed: 8000,
},
{
name: 'qwen/qwen-110b-chat',
label: 'OpenRouter Qwen 110b Chat (OpenRouter)',
provider: 'OpenRouter',
maxTokenAllowed: 8000,
},
{ name: 'cohere/command', label: 'Cohere Command (OpenRouter)', provider: 'OpenRouter', maxTokenAllowed: 4096 },
],
getDynamicModels: getOpenRouterModels,
getApiKeyLink: 'https://openrouter.ai/settings/keys',
},
{
name: 'Google',
staticModels: [
{ name: 'gemini-1.5-flash-latest', label: 'Gemini 1.5 Flash', provider: 'Google', maxTokenAllowed: 8192 },
{ name: 'gemini-2.0-flash-exp', label: 'Gemini 2.0 Flash', provider: 'Google', maxTokenAllowed: 8192 },
{ name: 'gemini-1.5-flash-002', label: 'Gemini 1.5 Flash-002', provider: 'Google', maxTokenAllowed: 8192 },
{ name: 'gemini-1.5-flash-8b', label: 'Gemini 1.5 Flash-8b', provider: 'Google', maxTokenAllowed: 8192 },
{ name: 'gemini-1.5-pro-latest', label: 'Gemini 1.5 Pro', provider: 'Google', maxTokenAllowed: 8192 },
{ name: 'gemini-1.5-pro-002', label: 'Gemini 1.5 Pro-002', provider: 'Google', maxTokenAllowed: 8192 },
{ name: 'gemini-exp-1206', label: 'Gemini exp-1206', provider: 'Google', maxTokenAllowed: 8192 },
],
getApiKeyLink: 'https://aistudio.google.com/app/apikey',
},
{
name: 'Groq',
staticModels: [
{ name: 'llama-3.1-70b-versatile', label: 'Llama 3.1 70b (Groq)', provider: 'Groq', maxTokenAllowed: 8000 },
{ name: 'llama-3.1-8b-instant', label: 'Llama 3.1 8b (Groq)', provider: 'Groq', maxTokenAllowed: 8000 },
{ name: 'llama-3.2-11b-vision-preview', label: 'Llama 3.2 11b (Groq)', provider: 'Groq', maxTokenAllowed: 8000 },
{ name: 'llama-3.2-3b-preview', label: 'Llama 3.2 3b (Groq)', provider: 'Groq', maxTokenAllowed: 8000 },
{ name: 'llama-3.2-1b-preview', label: 'Llama 3.2 1b (Groq)', provider: 'Groq', maxTokenAllowed: 8000 },
],
getApiKeyLink: 'https://console.groq.com/keys',
},
{
name: 'HuggingFace',
staticModels: [
{
name: 'Qwen/Qwen2.5-Coder-32B-Instruct',
label: 'Qwen2.5-Coder-32B-Instruct (HuggingFace)',
provider: 'HuggingFace',
maxTokenAllowed: 8000,
},
{
name: '01-ai/Yi-1.5-34B-Chat',
label: 'Yi-1.5-34B-Chat (HuggingFace)',
provider: 'HuggingFace',
maxTokenAllowed: 8000,
},
{
name: 'codellama/CodeLlama-34b-Instruct-hf',
label: 'CodeLlama-34b-Instruct (HuggingFace)',
provider: 'HuggingFace',
maxTokenAllowed: 8000,
},
{
name: 'NousResearch/Hermes-3-Llama-3.1-8B',
label: 'Hermes-3-Llama-3.1-8B (HuggingFace)',
provider: 'HuggingFace',
maxTokenAllowed: 8000,
},
{
name: 'Qwen/Qwen2.5-Coder-32B-Instruct',
label: 'Qwen2.5-Coder-32B-Instruct (HuggingFace)',
provider: 'HuggingFace',
maxTokenAllowed: 8000,
},
{
name: 'Qwen/Qwen2.5-72B-Instruct',
label: 'Qwen2.5-72B-Instruct (HuggingFace)',
provider: 'HuggingFace',
maxTokenAllowed: 8000,
},
{
name: 'meta-llama/Llama-3.1-70B-Instruct',
label: 'Llama-3.1-70B-Instruct (HuggingFace)',
provider: 'HuggingFace',
maxTokenAllowed: 8000,
},
{
name: 'meta-llama/Llama-3.1-405B',
label: 'Llama-3.1-405B (HuggingFace)',
provider: 'HuggingFace',
maxTokenAllowed: 8000,
},
{
name: '01-ai/Yi-1.5-34B-Chat',
label: 'Yi-1.5-34B-Chat (HuggingFace)',
provider: 'HuggingFace',
maxTokenAllowed: 8000,
},
{
name: 'codellama/CodeLlama-34b-Instruct-hf',
label: 'CodeLlama-34b-Instruct (HuggingFace)',
provider: 'HuggingFace',
maxTokenAllowed: 8000,
},
{
name: 'NousResearch/Hermes-3-Llama-3.1-8B',
label: 'Hermes-3-Llama-3.1-8B (HuggingFace)',
provider: 'HuggingFace',
maxTokenAllowed: 8000,
},
],
getApiKeyLink: 'https://huggingface.co/settings/tokens',
},
export const PROVIDER_LIST = llmManager.getAllProviders();
export const DEFAULT_PROVIDER = llmManager.getDefaultProvider();
{
name: 'OpenAI',
staticModels: [
{ name: 'gpt-4o-mini', label: 'GPT-4o Mini', provider: 'OpenAI', maxTokenAllowed: 8000 },
{ name: 'gpt-4-turbo', label: 'GPT-4 Turbo', provider: 'OpenAI', maxTokenAllowed: 8000 },
{ name: 'gpt-4', label: 'GPT-4', provider: 'OpenAI', maxTokenAllowed: 8000 },
{ name: 'gpt-3.5-turbo', label: 'GPT-3.5 Turbo', provider: 'OpenAI', maxTokenAllowed: 8000 },
],
getApiKeyLink: 'https://platform.openai.com/api-keys',
},
{
name: 'xAI',
staticModels: [{ name: 'grok-beta', label: 'xAI Grok Beta', provider: 'xAI', maxTokenAllowed: 8000 }],
getApiKeyLink: 'https://docs.x.ai/docs/quickstart#creating-an-api-key',
},
{
name: 'Deepseek',
staticModels: [
{ name: 'deepseek-coder', label: 'Deepseek-Coder', provider: 'Deepseek', maxTokenAllowed: 8000 },
{ name: 'deepseek-chat', label: 'Deepseek-Chat', provider: 'Deepseek', maxTokenAllowed: 8000 },
],
getApiKeyLink: 'https://platform.deepseek.com/apiKeys',
},
{
name: 'Mistral',
staticModels: [
{ name: 'open-mistral-7b', label: 'Mistral 7B', provider: 'Mistral', maxTokenAllowed: 8000 },
{ name: 'open-mixtral-8x7b', label: 'Mistral 8x7B', provider: 'Mistral', maxTokenAllowed: 8000 },
{ name: 'open-mixtral-8x22b', label: 'Mistral 8x22B', provider: 'Mistral', maxTokenAllowed: 8000 },
{ name: 'open-codestral-mamba', label: 'Codestral Mamba', provider: 'Mistral', maxTokenAllowed: 8000 },
{ name: 'open-mistral-nemo', label: 'Mistral Nemo', provider: 'Mistral', maxTokenAllowed: 8000 },
{ name: 'ministral-8b-latest', label: 'Mistral 8B', provider: 'Mistral', maxTokenAllowed: 8000 },
{ name: 'mistral-small-latest', label: 'Mistral Small', provider: 'Mistral', maxTokenAllowed: 8000 },
{ name: 'codestral-latest', label: 'Codestral', provider: 'Mistral', maxTokenAllowed: 8000 },
{ name: 'mistral-large-latest', label: 'Mistral Large Latest', provider: 'Mistral', maxTokenAllowed: 8000 },
],
getApiKeyLink: 'https://console.mistral.ai/api-keys/',
},
{
name: 'LMStudio',
staticModels: [],
getDynamicModels: getLMStudioModels,
getApiKeyLink: 'https://lmstudio.ai/',
labelForGetApiKey: 'Get LMStudio',
icon: 'i-ph:cloud-arrow-down',
},
{
name: 'Together',
getDynamicModels: getTogetherModels,
staticModels: [
{
name: 'Qwen/Qwen2.5-Coder-32B-Instruct',
label: 'Qwen/Qwen2.5-Coder-32B-Instruct',
provider: 'Together',
maxTokenAllowed: 8000,
},
{
name: 'meta-llama/Llama-3.2-90B-Vision-Instruct-Turbo',
label: 'meta-llama/Llama-3.2-90B-Vision-Instruct-Turbo',
provider: 'Together',
maxTokenAllowed: 8000,
},
let MODEL_LIST = llmManager.getModelList();
{
name: 'mistralai/Mixtral-8x7B-Instruct-v0.1',
label: 'Mixtral 8x7B Instruct',
provider: 'Together',
maxTokenAllowed: 8192,
},
],
getApiKeyLink: 'https://api.together.xyz/settings/api-keys',
},
];
export const DEFAULT_PROVIDER = PROVIDER_LIST[0];
const staticModels: ModelInfo[] = PROVIDER_LIST.map((p) => p.staticModels).flat();
export let MODEL_LIST: ModelInfo[] = [...staticModels];
export async function getModelList(
apiKeys: Record<string, string>,
providerSettings?: Record<string, IProviderSetting>,
) {
MODEL_LIST = [
...(
await Promise.all(
PROVIDER_LIST.filter(
(p): p is ProviderInfo & { getDynamicModels: () => Promise<ModelInfo[]> } => !!p.getDynamicModels,
).map((p) => p.getDynamicModels(apiKeys, providerSettings?.[p.name])),
)
).flat(),
...staticModels,
];
return MODEL_LIST;
}
async function getTogetherModels(apiKeys?: Record<string, string>, settings?: IProviderSetting): Promise<ModelInfo[]> {
try {
const baseUrl = settings?.baseUrl || import.meta.env.TOGETHER_API_BASE_URL || '';
const provider = 'Together';
if (!baseUrl) {
return [];
}
let apiKey = import.meta.env.OPENAI_LIKE_API_KEY ?? '';
if (apiKeys && apiKeys[provider]) {
apiKey = apiKeys[provider];
}
if (!apiKey) {
return [];
}
const response = await fetch(`${baseUrl}/models`, {
headers: {
Authorization: `Bearer ${apiKey}`,
},
const providerBaseUrlEnvKeys: Record<string, { baseUrlKey?: string; apiTokenKey?: string }> = {};
PROVIDER_LIST.forEach((provider) => {
providerBaseUrlEnvKeys[provider.name] = {
baseUrlKey: provider.config.baseUrlKey,
apiTokenKey: provider.config.apiTokenKey,
};
});
const res = (await response.json()) as any;
const data: any[] = (res || []).filter((model: any) => model.type == 'chat');
return data.map((m: any) => ({
name: m.id,
label: `${m.display_name} - in:$${m.pricing.input.toFixed(
2,
)} out:$${m.pricing.output.toFixed(2)} - context ${Math.floor(m.context_length / 1000)}k`,
provider,
maxTokenAllowed: 8000,
}));
} catch (e) {
console.error('Error getting OpenAILike models:', e);
return [];
}
// Export the getModelList function using the manager
export async function getModelList(options: {
apiKeys?: Record<string, string>;
providerSettings?: Record<string, IProviderSetting>;
serverEnv?: Record<string, string>;
}) {
return await llmManager.updateModelList(options);
}
const getOllamaBaseUrl = (settings?: IProviderSetting) => {
const defaultBaseUrl = settings?.baseUrl || import.meta.env.OLLAMA_API_BASE_URL || 'http://localhost:11434';
// Check if we're in the browser
if (typeof window !== 'undefined') {
// Frontend always uses localhost
return defaultBaseUrl;
}
// Backend: Check if we're running in Docker
const isDocker = process.env.RUNNING_IN_DOCKER === 'true';
return isDocker ? defaultBaseUrl.replace('localhost', 'host.docker.internal') : defaultBaseUrl;
};
async function getOllamaModels(apiKeys?: Record<string, string>, settings?: IProviderSetting): Promise<ModelInfo[]> {
/*
* if (typeof window === 'undefined') {
* return [];
* }
*/
try {
const baseUrl = getOllamaBaseUrl(settings);
const response = await fetch(`${baseUrl}/api/tags`);
const data = (await response.json()) as OllamaApiResponse;
return data.models.map((model: OllamaModel) => ({
name: model.name,
label: `${model.name} (${model.details.parameter_size})`,
provider: 'Ollama',
maxTokenAllowed: 8000,
}));
} catch (e: any) {
logger.warn('Failed to get Ollama models: ', e.message || '');
return [];
}
}
async function getOpenAILikeModels(
apiKeys?: Record<string, string>,
settings?: IProviderSetting,
): Promise<ModelInfo[]> {
try {
const baseUrl = settings?.baseUrl || import.meta.env.OPENAI_LIKE_API_BASE_URL || '';
if (!baseUrl) {
return [];
}
let apiKey = '';
if (apiKeys && apiKeys.OpenAILike) {
apiKey = apiKeys.OpenAILike;
}
const response = await fetch(`${baseUrl}/models`, {
headers: {
Authorization: `Bearer ${apiKey}`,
},
async function initializeModelList(options: {
env?: Record<string, string>;
providerSettings?: Record<string, IProviderSetting>;
apiKeys?: Record<string, string>;
}): Promise<ModelInfo[]> {
const { providerSettings, apiKeys, env } = options;
const list = await getModelList({
apiKeys,
providerSettings,
serverEnv: env,
});
const res = (await response.json()) as any;
MODEL_LIST = list || MODEL_LIST;
return res.data.map((model: any) => ({
name: model.id,
label: model.id,
provider: 'OpenAILike',
}));
} catch (e) {
console.error('Error getting OpenAILike models:', e);
return [];
}
return list;
}
type OpenRouterModelsResponse = {
data: {
name: string;
id: string;
context_length: number;
pricing: {
prompt: number;
completion: number;
};
}[];
};
// initializeModelList({})
export { initializeModelList, providerBaseUrlEnvKeys, MODEL_LIST };
async function getOpenRouterModels(): Promise<ModelInfo[]> {
const data: OpenRouterModelsResponse = await (
await fetch('https://openrouter.ai/api/v1/models', {
headers: {
'Content-Type': 'application/json',
// starter Templates
export const STARTER_TEMPLATES: Template[] = [
{
name: 'bolt-astro-basic',
label: 'Astro Basic',
description: 'Lightweight Astro starter template for building fast static websites',
githubRepo: 'thecodacus/bolt-astro-basic-template',
tags: ['astro', 'blog', 'performance'],
icon: 'i-bolt:astro',
},
{
name: 'bolt-nextjs-shadcn',
label: 'Next.js with shadcn/ui',
description: 'Next.js starter fullstack template integrated with shadcn/ui components and styling system',
githubRepo: 'thecodacus/bolt-nextjs-shadcn-template',
tags: ['nextjs', 'react', 'typescript', 'shadcn', 'tailwind'],
icon: 'i-bolt:nextjs',
},
{
name: 'bolt-qwik-ts',
label: 'Qwik TypeScript',
description: 'Qwik framework starter with TypeScript for building resumable applications',
githubRepo: 'thecodacus/bolt-qwik-ts-template',
tags: ['qwik', 'typescript', 'performance', 'resumable'],
icon: 'i-bolt:qwik',
},
{
name: 'bolt-remix-ts',
label: 'Remix TypeScript',
description: 'Remix framework starter with TypeScript for full-stack web applications',
githubRepo: 'thecodacus/bolt-remix-ts-template',
tags: ['remix', 'typescript', 'fullstack', 'react'],
icon: 'i-bolt:remix',
},
{
name: 'bolt-slidev',
label: 'Slidev Presentation',
description: 'Slidev starter template for creating developer-friendly presentations using Markdown',
githubRepo: 'thecodacus/bolt-slidev-template',
tags: ['slidev', 'presentation', 'markdown'],
icon: 'i-bolt:slidev',
},
{
name: 'bolt-sveltekit',
label: 'SvelteKit',
description: 'SvelteKit starter template for building fast, efficient web applications',
githubRepo: 'bolt-sveltekit-template',
tags: ['svelte', 'sveltekit', 'typescript'],
icon: 'i-bolt:svelte',
},
{
name: 'vanilla-vite',
label: 'Vanilla + Vite',
description: 'Minimal Vite starter template for vanilla JavaScript projects',
githubRepo: 'thecodacus/vanilla-vite-template',
tags: ['vite', 'vanilla-js', 'minimal'],
icon: 'i-bolt:vite',
},
{
name: 'bolt-vite-react',
label: 'React + Vite + typescript',
description: 'React starter template powered by Vite for fast development experience',
githubRepo: 'thecodacus/bolt-vite-react-ts-template',
tags: ['react', 'vite', 'frontend'],
icon: 'i-bolt:react',
},
{
name: 'bolt-vite-ts',
label: 'Vite + TypeScript',
description: 'Vite starter template with TypeScript configuration for type-safe development',
githubRepo: 'thecodacus/bolt-vite-ts-template',
tags: ['vite', 'typescript', 'minimal'],
icon: 'i-bolt:typescript',
},
{
name: 'bolt-vue',
label: 'Vue.js',
description: 'Vue.js starter template with modern tooling and best practices',
githubRepo: 'thecodacus/bolt-vue-template',
tags: ['vue', 'typescript', 'frontend'],
icon: 'i-bolt:vue',
},
{
name: 'bolt-angular',
label: 'Angular Starter',
description: 'A modern Angular starter template with TypeScript support and best practices configuration',
githubRepo: 'thecodacus/bolt-angular-template',
tags: ['angular', 'typescript', 'frontend', 'spa'],
icon: 'i-bolt:angular',
},
})
).json();
return data.data
.sort((a, b) => a.name.localeCompare(b.name))
.map((m) => ({
name: m.id,
label: `${m.name} - in:$${(m.pricing.prompt * 1_000_000).toFixed(
2,
)} out:$${(m.pricing.completion * 1_000_000).toFixed(2)} - context ${Math.floor(m.context_length / 1000)}k`,
provider: 'OpenRouter',
maxTokenAllowed: 8000,
}));
}
async function getLMStudioModels(_apiKeys?: Record<string, string>, settings?: IProviderSetting): Promise<ModelInfo[]> {
if (typeof window === 'undefined') {
return [];
}
try {
const baseUrl = settings?.baseUrl || import.meta.env.LMSTUDIO_API_BASE_URL || 'http://localhost:1234';
const response = await fetch(`${baseUrl}/v1/models`);
const data = (await response.json()) as any;
return data.data.map((model: any) => ({
name: model.id,
label: model.id,
provider: 'LMStudio',
}));
} catch (e: any) {
logger.warn('Failed to get LMStudio models: ', e.message || '');
return [];
}
}
async function initializeModelList(providerSettings?: Record<string, IProviderSetting>): Promise<ModelInfo[]> {
let apiKeys: Record<string, string> = {};
try {
const storedApiKeys = Cookies.get('apiKeys');
if (storedApiKeys) {
const parsedKeys = JSON.parse(storedApiKeys);
if (typeof parsedKeys === 'object' && parsedKeys !== null) {
apiKeys = parsedKeys;
}
}
} catch (error: any) {
logger.warn(`Failed to fetch apikeys from cookies: ${error?.message}`);
}
MODEL_LIST = [
...(
await Promise.all(
PROVIDER_LIST.filter(
(p): p is ProviderInfo & { getDynamicModels: () => Promise<ModelInfo[]> } => !!p.getDynamicModels,
).map((p) => p.getDynamicModels(apiKeys, providerSettings?.[p.name])),
)
).flat(),
...staticModels,
];
return MODEL_LIST;
}
export {
getOllamaModels,
getOpenAILikeModels,
getLMStudioModels,
initializeModelList,
getOpenRouterModels,
PROVIDER_LIST,
};

View File

@@ -1,4 +1,7 @@
export type DebugLevel = 'trace' | 'debug' | 'info' | 'warn' | 'error';
import { Chalk } from 'chalk';
const chalk = new Chalk({ level: 3 });
type LoggerFunction = (...messages: any[]) => void;
@@ -13,9 +16,6 @@ interface Logger {
let currentLevel: DebugLevel = (import.meta.env.VITE_LOG_LEVEL ?? import.meta.env.DEV) ? 'debug' : 'info';
const isWorker = 'HTMLRewriter' in globalThis;
const supportsColor = !isWorker;
export const logger: Logger = {
trace: (...messages: any[]) => log('trace', undefined, messages),
debug: (...messages: any[]) => log('debug', undefined, messages),
@@ -63,14 +63,8 @@ function log(level: DebugLevel, scope: string | undefined, messages: any[]) {
return `${acc} ${current}`;
}, '');
if (!supportsColor) {
console.log(`[${level.toUpperCase()}]`, allMessages);
return;
}
const labelBackgroundColor = getColorForLevel(level);
const labelTextColor = level === 'warn' ? 'black' : 'white';
const labelTextColor = level === 'warn' ? '#000000' : '#FFFFFF';
const labelStyles = getLabelStyles(labelBackgroundColor, labelTextColor);
const scopeStyles = getLabelStyles('#77828D', 'white');
@@ -81,7 +75,21 @@ function log(level: DebugLevel, scope: string | undefined, messages: any[]) {
styles.push('', scopeStyles);
}
let labelText = formatText(` ${level.toUpperCase()} `, labelTextColor, labelBackgroundColor);
if (scope) {
labelText = `${labelText} ${formatText(` ${scope} `, '#FFFFFF', '77828D')}`;
}
if (typeof window !== 'undefined') {
console.log(`%c${level.toUpperCase()}${scope ? `%c %c${scope}` : ''}`, ...styles, allMessages);
} else {
console.log(`${labelText}`, allMessages);
}
}
function formatText(text: string, color: string, bg: string) {
return chalk.bgHex(bg)(chalk.hex(color)(text));
}
function getLabelStyles(color: string, textColor: string) {
@@ -104,7 +112,7 @@ function getColorForLevel(level: DebugLevel): string {
return '#EE4744';
}
default: {
return 'black';
return '#000000';
}
}
}

49
app/utils/sampler.ts Normal file
View File

@@ -0,0 +1,49 @@
/**
* Creates a function that samples calls at regular intervals and captures trailing calls.
* - Drops calls that occur between sampling intervals
* - Takes one call per sampling interval if available
* - Captures the last call if no call was made during the interval
*
* @param fn The function to sample
* @param sampleInterval How often to sample calls (in ms)
* @returns The sampled function
*/
export function createSampler<T extends (...args: any[]) => any>(fn: T, sampleInterval: number): T {
let lastArgs: Parameters<T> | null = null;
let lastTime = 0;
let timeout: NodeJS.Timeout | null = null;
// Create a function with the same type as the input function
const sampled = function (this: any, ...args: Parameters<T>) {
const now = Date.now();
lastArgs = args;
// If we're within the sample interval, just store the args
if (now - lastTime < sampleInterval) {
// Set up trailing call if not already set
if (!timeout) {
timeout = setTimeout(
() => {
timeout = null;
lastTime = Date.now();
if (lastArgs) {
fn.apply(this, lastArgs);
lastArgs = null;
}
},
sampleInterval - (now - lastTime),
);
}
return;
}
// If we're outside the interval, execute immediately
lastTime = now;
fn.apply(this, args);
lastArgs = null;
} as T;
return sampled;
}

View File

@@ -0,0 +1,300 @@
import ignore from 'ignore';
import type { ProviderInfo } from '~/types/model';
import type { Template } from '~/types/template';
import { STARTER_TEMPLATES } from './constants';
const starterTemplateSelectionPrompt = (templates: Template[]) => `
You are an experienced developer who helps people choose the best starter template for their projects.
Available templates:
<template>
<name>blank</name>
<description>Empty starter for simple scripts and trivial tasks that don't require a full template setup</description>
<tags>basic, script</tags>
</template>
${templates
.map(
(template) => `
<template>
<name>${template.name}</name>
<description>${template.description}</description>
${template.tags ? `<tags>${template.tags.join(', ')}</tags>` : ''}
</template>
`,
)
.join('\n')}
Response Format:
<selection>
<templateName>{selected template name}</templateName>
<title>{a proper title for the project}</title>
</selection>
Examples:
<example>
User: I need to build a todo app
Response:
<selection>
<templateName>react-basic-starter</templateName>
<title>Simple React todo application</title>
</selection>
</example>
<example>
User: Write a script to generate numbers from 1 to 100
Response:
<selection>
<templateName>blank</templateName>
<title>script to generate numbers from 1 to 100</title>
</selection>
</example>
Instructions:
1. For trivial tasks and simple scripts, always recommend the blank template
2. For more complex projects, recommend templates from the provided list
3. Follow the exact XML format
4. Consider both technical requirements and tags
5. If no perfect match exists, recommend the closest option
Important: Provide only the selection tags in your response, no additional text.
`;
const templates: Template[] = STARTER_TEMPLATES.filter((t) => !t.name.includes('shadcn'));
const parseSelectedTemplate = (llmOutput: string): { template: string; title: string } | null => {
try {
// Extract content between <templateName> tags
const templateNameMatch = llmOutput.match(/<templateName>(.*?)<\/templateName>/);
const titleMatch = llmOutput.match(/<title>(.*?)<\/title>/);
if (!templateNameMatch) {
return null;
}
return { template: templateNameMatch[1].trim(), title: titleMatch?.[1].trim() || 'Untitled Project' };
} catch (error) {
console.error('Error parsing template selection:', error);
return null;
}
};
export const selectStarterTemplate = async (options: { message: string; model: string; provider: ProviderInfo }) => {
const { message, model, provider } = options;
const requestBody = {
message,
model,
provider,
system: starterTemplateSelectionPrompt(templates),
};
const response = await fetch('/api/llmcall', {
method: 'POST',
body: JSON.stringify(requestBody),
});
const respJson: { text: string } = await response.json();
console.log(respJson);
const { text } = respJson;
const selectedTemplate = parseSelectedTemplate(text);
if (selectedTemplate) {
return selectedTemplate;
} else {
console.log('No template selected, using blank template');
return {
template: 'blank',
title: '',
};
}
};
const getGitHubRepoContent = async (
repoName: string,
path: string = '',
): Promise<{ name: string; path: string; content: string }[]> => {
const baseUrl = 'https://api.github.com';
try {
// Fetch contents of the path
const response = await fetch(`${baseUrl}/repos/${repoName}/contents/${path}`, {
headers: {
Accept: 'application/vnd.github.v3+json',
// Add your GitHub token if needed
Authorization: 'token ' + import.meta.env.VITE_GITHUB_ACCESS_TOKEN,
},
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data: any = await response.json();
// If it's a single file, return its content
if (!Array.isArray(data)) {
if (data.type === 'file') {
// If it's a file, get its content
const content = atob(data.content); // Decode base64 content
return [
{
name: data.name,
path: data.path,
content,
},
];
}
}
// Process directory contents recursively
const contents = await Promise.all(
data.map(async (item: any) => {
if (item.type === 'dir') {
// Recursively get contents of subdirectories
return await getGitHubRepoContent(repoName, item.path);
} else if (item.type === 'file') {
// Fetch file content
const fileResponse = await fetch(item.url, {
headers: {
Accept: 'application/vnd.github.v3+json',
Authorization: 'token ' + import.meta.env.VITE_GITHUB_ACCESS_TOKEN,
},
});
const fileData: any = await fileResponse.json();
const content = atob(fileData.content); // Decode base64 content
return [
{
name: item.name,
path: item.path,
content,
},
];
}
return [];
}),
);
// Flatten the array of contents
return contents.flat();
} catch (error) {
console.error('Error fetching repo contents:', error);
throw error;
}
};
export async function getTemplates(templateName: string, title?: string) {
const template = STARTER_TEMPLATES.find((t) => t.name == templateName);
if (!template) {
return null;
}
const githubRepo = template.githubRepo;
const files = await getGitHubRepoContent(githubRepo);
let filteredFiles = files;
/*
* ignoring common unwanted files
* exclude .git
*/
filteredFiles = filteredFiles.filter((x) => x.path.startsWith('.git') == false);
// exclude lock files
const comminLockFiles = ['package-lock.json', 'yarn.lock', 'pnpm-lock.yaml'];
filteredFiles = filteredFiles.filter((x) => comminLockFiles.includes(x.name) == false);
// exclude .bolt
filteredFiles = filteredFiles.filter((x) => x.path.startsWith('.bolt') == false);
// check for ignore file in .bolt folder
const templateIgnoreFile = files.find((x) => x.path.startsWith('.bolt') && x.name == 'ignore');
const filesToImport = {
files: filteredFiles,
ignoreFile: [] as typeof filteredFiles,
};
if (templateIgnoreFile) {
// redacting files specified in ignore file
const ignorepatterns = templateIgnoreFile.content.split('\n').map((x) => x.trim());
const ig = ignore().add(ignorepatterns);
// filteredFiles = filteredFiles.filter(x => !ig.ignores(x.path))
const ignoredFiles = filteredFiles.filter((x) => ig.ignores(x.path));
filesToImport.files = filteredFiles;
filesToImport.ignoreFile = ignoredFiles;
}
const assistantMessage = `
<boltArtifact id="imported-files" title="${title || 'Importing Starter Files'}" type="bundled">
${filesToImport.files
.map(
(file) =>
`<boltAction type="file" filePath="${file.path}">
${file.content}
</boltAction>`,
)
.join('\n')}
</boltArtifact>
`;
let userMessage = ``;
const templatePromptFile = files.filter((x) => x.path.startsWith('.bolt')).find((x) => x.name == 'prompt');
if (templatePromptFile) {
userMessage = `
TEMPLATE INSTRUCTIONS:
${templatePromptFile.content}
IMPORTANT: Dont Forget to install the dependencies before running the app
---
`;
}
if (filesToImport.ignoreFile.length > 0) {
userMessage =
userMessage +
`
STRICT FILE ACCESS RULES - READ CAREFULLY:
The following files are READ-ONLY and must never be modified:
${filesToImport.ignoreFile.map((file) => `- ${file.path}`).join('\n')}
Permitted actions:
✓ Import these files as dependencies
✓ Read from these files
✓ Reference these files
Strictly forbidden actions:
❌ Modify any content within these files
❌ Delete these files
❌ Rename these files
❌ Move these files
❌ Create new versions of these files
❌ Suggest changes to these files
Any attempt to modify these protected files will result in immediate termination of the operation.
If you need to make changes to functionality, create new files instead of modifying the protected ones listed above.
---
`;
}
userMessage += `
---
template import is done, and you can now use the imported files,
edit only the files that need to be changed, and you can create new files as needed.
NO NOT EDIT/WRITE ANY FILES THAT ALREADY EXIST IN THE PROJECT AND DOES NOT NEED TO BE MODIFIED
---
Now that the Template is imported please continue with my original request
`;
return {
assistantMessage,
userMessage,
};
}

View File

@@ -60,7 +60,9 @@ export class BoltShell {
#webcontainer: WebContainer | undefined;
#terminal: ITerminal | undefined;
#process: WebContainerProcess | undefined;
executionState = atom<{ sessionId: string; active: boolean; executionPrms?: Promise<any> } | undefined>();
executionState = atom<
{ sessionId: string; active: boolean; executionPrms?: Promise<any>; abort?: () => void } | undefined
>();
#outputStream: ReadableStreamDefaultReader<string> | undefined;
#shellInputStream: WritableStreamDefaultWriter<string> | undefined;
@@ -93,18 +95,23 @@ export class BoltShell {
return this.#process;
}
async executeCommand(sessionId: string, command: string): Promise<ExecutionResult> {
async executeCommand(sessionId: string, command: string, abort?: () => void): Promise<ExecutionResult> {
if (!this.process || !this.terminal) {
return undefined;
}
const state = this.executionState.get();
if (state?.active && state.abort) {
state.abort();
}
/*
* interrupt the current execution
* this.#shellInputStream?.write('\x03');
*/
this.terminal.input('\x03');
await this.waitTillOscCode('prompt');
if (state && state.executionPrms) {
await state.executionPrms;
@@ -115,11 +122,19 @@ export class BoltShell {
//wait for the execution to finish
const executionPromise = this.getCurrentExecutionResult();
this.executionState.set({ sessionId, active: true, executionPrms: executionPromise });
this.executionState.set({ sessionId, active: true, executionPrms: executionPromise, abort });
const resp = await executionPromise;
this.executionState.set({ sessionId, active: false });
if (resp) {
try {
resp.output = cleanTerminalOutput(resp.output);
} catch (error) {
console.log('failed to format terminal output', error);
}
}
return resp;
}
@@ -215,6 +230,65 @@ export class BoltShell {
}
}
/**
* Cleans and formats terminal output while preserving structure and paths
* Handles ANSI, OSC, and various terminal control sequences
*/
export function cleanTerminalOutput(input: string): string {
// Step 1: Remove OSC sequences (including those with parameters)
const removeOsc = input
.replace(/\x1b\](\d+;[^\x07\x1b]*|\d+[^\x07\x1b]*)\x07/g, '')
.replace(/\](\d+;[^\n]*|\d+[^\n]*)/g, '');
// Step 2: Remove ANSI escape sequences and color codes more thoroughly
const removeAnsi = removeOsc
// Remove all escape sequences with parameters
.replace(/\u001b\[[\?]?[0-9;]*[a-zA-Z]/g, '')
.replace(/\x1b\[[\?]?[0-9;]*[a-zA-Z]/g, '')
// Remove color codes
.replace(/\u001b\[[0-9;]*m/g, '')
.replace(/\x1b\[[0-9;]*m/g, '')
// Clean up any remaining escape characters
.replace(/\u001b/g, '')
.replace(/\x1b/g, '');
// Step 3: Clean up carriage returns and newlines
const cleanNewlines = removeAnsi
.replace(/\r\n/g, '\n')
.replace(/\r/g, '\n')
.replace(/\n{3,}/g, '\n\n');
// Step 4: Add newlines at key breakpoints while preserving paths
const formatOutput = cleanNewlines
// Preserve prompt line
.replace(/^([~\/][^\n]+)/m, '$1\n')
// Add newline before command output indicators
.replace(/(?<!^|\n)>/g, '\n>')
// Add newline before error keywords without breaking paths
.replace(/(?<!^|\n|\w)(error|failed|warning|Error|Failed|Warning):/g, '\n$1:')
// Add newline before 'at' in stack traces without breaking paths
.replace(/(?<!^|\n|\/)(at\s+(?!async|sync))/g, '\nat ')
// Ensure 'at async' stays on same line
.replace(/\bat\s+async/g, 'at async')
// Add newline before npm error indicators
.replace(/(?<!^|\n)(npm ERR!)/g, '\n$1');
// Step 5: Clean up whitespace while preserving intentional spacing
const cleanSpaces = formatOutput
.split('\n')
.map((line) => line.trim())
.filter((line) => line.length > 0)
.join('\n');
// Step 6: Final cleanup
return cleanSpaces
.replace(/\n{3,}/g, '\n\n') // Replace multiple newlines with double newlines
.replace(/:\s+/g, ': ') // Normalize spacing after colons
.replace(/\s{2,}/g, ' ') // Remove multiple spaces
.replace(/^\s+|\s+$/g, '') // Trim start and end
.replace(/\u0000/g, ''); // Remove null characters
}
export function newBoltShellProcess() {
return new BoltShell();
}

27
app/utils/stacktrace.ts Normal file
View File

@@ -0,0 +1,27 @@
/**
* Cleans webcontainer URLs from stack traces to show relative paths instead
*/
export function cleanStackTrace(stackTrace: string): string {
// Function to clean a single URL
const cleanUrl = (url: string): string => {
const regex = /^https?:\/\/[^\/]+\.webcontainer-api\.io(\/.*)?$/;
if (!regex.test(url)) {
return url;
}
const pathRegex = /^https?:\/\/[^\/]+\.webcontainer-api\.io\/(.*?)$/;
const match = url.match(pathRegex);
return match?.[1] || '';
};
// Split the stack trace into lines and process each line
return stackTrace
.split('\n')
.map((line) => {
// Match any URL in the line that contains webcontainer-api.io
return line.replace(/(https?:\/\/[^\/]+\.webcontainer-api\.io\/[^\s\)]+)/g, (match) => cleanUrl(match));
})
.join('\n');
}

View File

@@ -19,10 +19,3 @@ export interface OllamaModel {
export interface OllamaApiResponse {
models: OllamaModel[];
}
export interface ModelInfo {
name: string;
label: string;
provider: string;
maxTokenAllowed: number;
}

2
app/vite-env.d.ts vendored Normal file
View File

@@ -0,0 +1,2 @@
declare const __COMMIT_HASH: string;
declare const __APP_VERSION: string;

View File

@@ -1,808 +1,68 @@
# Release v0.0.1
# 🚀 Release v0.0.4
### 🎉 First Release
## What's Changed 🌟
#### ✨ Features
### 🔄 Changes since v0.0.3
- add login
- use tailwind-compat
- refactor layout and introduce workspace panel and fix some bugs
- add first version of workbench, increase token limit, improve system prompt
- improve prompt, add ability to abort streaming, improve message parser
- add support for message continuation (#1)
- chat autoscroll (#6)
- add simple api error handling (#9)
- initial persistence (#3)
- submit file changes to the llm (#11)
- add 'Open in StackBlitz' button to header (#10)
- add terminal and simple shortcut system (#16)
- use artifact id in urls, store metadata in history (#15)
- oauth-based login (#7)
- allow to disable auth during development (#21)
- allow to open up to three terminals (#22)
- tweak ui for redirect screen (#23)
- initial chat history ui (#25)
- add ability to change preview URL (#26)
- implement light and dark theme (#30)
- add basic analytics (#29)
- send analytics event for token usage (#37)
- add dropdown to select preview port (#17)
- add file tree breadcrumb (#40)
- rework ux for deleting chats (#46)
- navigate away when deleting current chat (#44)
- add avatar (#47)
- sanitize user messages (#42)
- remove authentication (#1)
- add readme image (#4)
- add readme image (#4)
- added sync files to selected local folder function is created. Yarn package manager fixes, styling fixes. Sass module fix. Added Claude model for open router.
- add ability to enter API keys in the UI
- added bolt dedicated shell
- hyperlinked on "Start application" actionto switch to preview in workbench
- add custom unique filename when doanload as zip
- add Together AI integration and provider implementation guide
- better prompt enhancement
- prompt caching
- search chats
- Connections Tabs
### ✨ Features
* add xAI grok-2-1212 model ([#800](https://github.com/stackblitz-labs/bolt.diy/pull/800))
* providers list is now 2 columns (75ec49b) by Dustin Loring
* enhanced Terminal Error Handling and Alert System ([#797](https://github.com/stackblitz-labs/bolt.diy/pull/797))
* add Starter template menu in homepage ([#884](https://github.com/stackblitz-labs/bolt.diy/pull/884))
* catch errors from web container preview and show in actionable alert so user can send them to AI for fixing ([#856](https://github.com/stackblitz-labs/bolt.diy/pull/856))
* redact file contents from chat and put latest files into system prompt ([#904](https://github.com/stackblitz-labs/bolt.diy/pull/904))
* added Automatic Code Template Detection And Import ([#867](https://github.com/stackblitz-labs/bolt.diy/pull/867))
* added hyperbolic llm models ([#943](https://github.com/stackblitz-labs/bolt.diy/pull/943))
#### 🐛 Bug Fixes
### 🐛 Bug Fixes
- buttons after switching to tailwind-compat reset
- update system prompt
- do not use path mapping for worker function
- make file tree scrollable (#14)
- always parse all assistant messages (#13)
- issue with generating a new url id every time (#18)
- use jose for cloudflare compatibility (#20)
- typo in example prompt
- adjust system prompt (#32)
- update dependencies to fix type validation error (#33)
- user avatar (#51)
- remove monorepo
- add issue templates (#2)
- update repo name
- rename template
- rename template
- add license
- update README.md (#3)
- typo
- remove duplicated bug_report template
- update links
- add screen recordings section to bug_report.yml
- typo
- remove duplicated bug_report template
- update links
- add screen recordings section to bug_report.yml
- remove logout button (#130)
- typo in README.md (#117)
- typo in README.md (#151)
- typos in CONTRIBUTING.md (#165)
- don't always show scrollbars (#548)
- don't always show scrollbars (#548)
- working
- Resolved
- adds missing -t for dockerbuild:prod command in package.json
- bug #245
- added scroll fix for file browser
- global execution queue added
- enhance prompt "Invalid or missing provider" bad request error
- prettier issue
- silent eslint issues
- add browser environment check for local API calls
- sidebar scroll always showing up
- tooltip UI
- typo in docker-compose.yaml
- updated ci
- Added some minor UI fix
- artifact loop fix
- clean up
- small bug
- correction
- grammar/typos in system prompt
- grammar
- re-capitalize "NEW"
- dev command
* chat title character restriction (e064803) by Dustin Loring
* fixed model not loading/working, even after baseUrl set in .env file ([#816](https://github.com/stackblitz-labs/bolt.diy/pull/816))
* added wait till terminal prompt for bolt shell execution ([#789](https://github.com/stackblitz-labs/bolt.diy/pull/789))
* fixed console error for SettingsWIndow & Removed ts-nocheck ([#714](https://github.com/stackblitz-labs/bolt.diy/pull/714))
* add Message Processing Throttling to Prevent Browser Crashes ([#848](https://github.com/stackblitz-labs/bolt.diy/pull/848))
* provider menu dropdown fix (ghost providers) ([#862](https://github.com/stackblitz-labs/bolt.diy/pull/862))
* ollama provider module base url hotfix for docker ([#863](https://github.com/stackblitz-labs/bolt.diy/pull/863))
* check for updates does not look for commit.json now ([#861](https://github.com/stackblitz-labs/bolt.diy/pull/861))
* detect and remove markdown block syntax that llms sometimes hallucinate for file actions ([#886](https://github.com/stackblitz-labs/bolt.diy/pull/886))
* add defaults for LMStudio to work out of the box ([#928](https://github.com/stackblitz-labs/bolt.diy/pull/928))
* import folder filtering ([#939](https://github.com/stackblitz-labs/bolt.diy/pull/939))
* refresh model list after api key changes ([#944](https://github.com/stackblitz-labs/bolt.diy/pull/944))
* better model loading ui feedback and model list update ([#954](https://github.com/stackblitz-labs/bolt.diy/pull/954))
* updated logger and model caching minor bugfix #release ([#895](https://github.com/stackblitz-labs/bolt.diy/pull/895))
#### 📚 Documentation
### 📚 Documentation
- fix typo in CONTRIBUTING.md (#158)
- fix typos in README.md (#164)
- docs added to readme
- add link to bolt.new issue tracker
- added socials
* simplified setup ([#817](https://github.com/stackblitz-labs/bolt.diy/pull/817))
* toc for readme (de64007) by Dustin Loring
* faq style change, toc added to index (636f87f) by Dustin Loring
* setup updated (ab5cde3) by Dustin Loring
* updated Docs ([#845](https://github.com/stackblitz-labs/bolt.diy/pull/845))
* updated download link ([#850](https://github.com/stackblitz-labs/bolt.diy/pull/850))
* updated env.example of OLLAMA & LMSTUDIO base url ([#877](https://github.com/stackblitz-labs/bolt.diy/pull/877))
#### ♻️ Code Refactoring
### ♻️ Code Refactoring
- workbench store and move logic into action runner (#4)
- improve history item hover states and interactions
- settinge menu refactored with useSettings hook
* updated vite config to inject add version metadata into the app on build ([#841](https://github.com/stackblitz-labs/bolt.diy/pull/841))
* refactored LLM Providers: Adapting Modular Approach ([#832](https://github.com/stackblitz-labs/bolt.diy/pull/832))
#### ⚙️ CI
### ⚙️ CI
- use correct versions (#2)
- deploy to cloudflare (#19)
- remove deployment workflow
* updated the docs ci to only trigger if any files changed in the docs folder ([#849](https://github.com/stackblitz-labs/bolt.diy/pull/849))
* improved change-log generation script and cleaner release ci action ([#896](https://github.com/stackblitz-labs/bolt.diy/pull/896))
#### 🔧 Chores
### 🔍 Other Changes
- make sure that husky hooks are executed
- update readme
- update gitignore
- disable css shorthand to avoid conflicts
- better clarify readme (#41)
- update readme
- create bug report template
- update readme (#3)
- update readme
- create MAIN-FOLDER-README.md
- update MAIN-FOLDER-README.md
- rename README.md to CONTRIBUTING.md
- rename MAIN-FOLDER-README.md to README.md
- update readme
- update contributing guide
- update contributing guide
- update readme
- update readme (#7)
- Add environment variables for OpenAI API Like integration
- Update environment variable names for OpenAI Like integration
- Update environment variable names for OpenAI Like integration
- cleanup logging
- reverted pnpm package version to match ghaction
- reverted pnpm lock
- recreated the lock file
- ui fix
- fixed lock file
- update commit hash to 31e7b48e057d12008a9790810433179bf88b9a32
- update commit hash to 0a9f04fe3d6001efb863eee7bd2210b5a889e04e
- update commit hash to 95e38e020cc8a4d865172187fc25c94b39806275
- update commit hash to 5b6b26bc9ce287e6e351ca443ad0f411d1371a7f
- update commit hash to 67f63aaf31f406379daa97708d6a1a9f8ac41d43
- update commit hash to 33d87a1b0eaf5ec36232bb54b3ba9e44e228024d
- update commit hash to db8c65ec2ba2f28382cb5e792a3f7495fb9a8e03
- update commit hash to d9ae9d5afbd0310a976fc4c9aee4b9256edef79a
- update commit hash to 7269c8246f7e89d29a4dd7b446617d66be2bb8da
- update commit hash to 9758e6c2a00bb9104f4338f67a5757945c69bfa1
- update commit hash to ac2f42d2d1398f218ec430dd8ba5667011f9d452
- update commit hash to b4978ca8193afa277f6df0d80e5fbdf787a3524a
- update commit hash to 5aeb52ae01aee1bc98605f41a0c747ef26dc8739
- update commit hash to eddf5603c3865536f96774fc3358cf24760fb613
- update commit hash to 225042bf5ffbf34868cf28ea1091c35a63f76599
- update commit hash to 1466b6e8777932ce0ab26199126c912373532637
- update commit hash to 46ad914d1869a7ebb37c67ee68aa7e65333e462f
- update commit hash to 61a6e133783565ac33fd3e1100a1484debad7c0d
- update commit hash to 3c71e4e1a1ea6179f0550d3f7628a2f6a75db286
- update commit hash to 1d5ad998b911dcf7deb3fa34516f73ee46901d1e
- update commit hash to fa526a643b3529dad86574af5c7ded33388901a2
- update commit hash to 7d202a4cc737183b29531dcb6336bdb77d899974
- update commit hash to 62bc87b6f31f5db69cde4874db02739ce8df9ded
- update commit hash to 154935cdeb054d2cc22dfb0c7e6cf084f02b95d0
- update commit hash to 7d482ace3d20d62d73107777a51c4ccc375c5969
- update commit hash to ab08f52aa0b13350cdfe0d0136b668af5e1cd108
- update commit hash to fd2c17c384a69ab5e7a40113342caa7de405b944
- update commit hash to c8a7ed9eb02a3626a6e1d591545102765bf762cb
- update commit hash to f682216515e6e594c6a55cf4520eb67d63939b60
- update commit hash to 8f3b4cd08249d26b14397e66241b9d099d3eb205
- update commit hash to 5e1936f5de539324f840305bd94a22260c339511
- update commit hash to f6329c28c6941fd5c6457a10c209b4b66402e8d5
- update commit hash to 0b9fd89c7089e98cfc2c17b6fd6ed7cdd6517f1a
- update commit hash to e7859a34ae64dfac73bbf6fb9e243dc0a7be0a09
- update commit hash to acd61fea8b6f5c6bbc6d2c7906ac88a6c6aaee5a
- update commit hash to 4b36601061652ec2ec3cb1f1d5c7cc5649690bbb
- update commit hash to b0c2f69dca041736f3dd7a8d48df3b5c44fe0948
- update commit hash to fb1ec72b505a0da0f03a6f1282845844afd7d61c
- update commit hash to 91ec049b72fcf42d807eb0aa1c8caa01611a4e1d
- fix workflow permission
- update commit hash to cbad04f035f017a4797768c75e180f10920c0e17
- update commit hash to 3f706702b2486e72efe1602e710ccef6c387c82a
- versioning workflow fix
- update commit hash to 212ab4a020245c96e3d126c9ef5522d4e9db1edf
- update commit hash to 0969aacb3533b94887cd63883b30c7fb91d2a957
- added workflow permission
- update commit hash to 5c1b4de26a861113ac727b521dfaae07b5f6856b
- update commit hash to b4104962b7c33202f004bcd05ed75d29c641f014
- adding workflow
- update commit hash to 6cb536a9a32e04b4ebc1f3788d6fae06c5bce5ac
* fix hotfix for version metadata issue ([#853](https://github.com/stackblitz-labs/bolt.diy/pull/853))
* feat; data tab added to the settings (1f938fc) by Dustin Loring
#### 🔍 Other Changes
- add file tree and hook up editor
- sync file changes back to webcontainer (#5)
- enforce consistent import paths (#8)
- remove settings button
- add slider to switch between code or preview (#12)
- adjust system prompt (#24)
- style sidebar and landing page (#27)
- hidden file patterns (#31)
- show tooltip when the editor is read-only (#34)
- allow to minimize chat (#35)
- correctly sort file tree (#36)
- encrypt data and fix renewal (#38)
- disable eslint
- Create bug_report.yml
- Update README.md
- Update README.md
- Update README.md
- Update README.md
- Update README.md
- Create MAIN-FOLDER-README.md
- Update MAIN-FOLDER-README.md
- Update MAIN-FOLDER-README.md
- Update MAIN-FOLDER-README.md
- Rename README.md to CONTRIBUTING.md
- Rename MAIN-FOLDER-README.md to README.md
- Update README.md
- Update CONTRIBUTING.md
- Update CONTRIBUTING.md
- Update README.md
- Update README.md (#7)
- don't render directly in body
- Add support for docker dev in bolt
- Update node version and enable host network
- don't render directly in body
- Merge branch 'main' into add-docker-support
- fix hanging shells (#153)
- show issue page (#157)
- fix hanging shells (#159)
- Merge branch 'main' into add-docker-support
- Update Dockerfile
- Add corepack to setup pnpm
- Added the ability to use practically any LLM you can dream of within Bolt.new
- Added the OpenRouter provider and a few models from OpenRouter (easily extendable to include more!)
- Add provider filtering on model list
- Set default provider from constants
- added Google Generative AI (gemini) integration
- use correct issues url (#514)
- let the ollama models be auto generated from ollama api
- added download code button
- Merge pull request #1 from ocodo/main
- Merge pull request #2 from jonathands/main
- Merge branch 'main' into main
- Merge pull request #5 from yunatamos/main
- Merge pull request #6 from fabwaseem/download-code
- Fixing up codebase after merging pull requests
- Updated README with new providers and a running list of features to add to the fork
- Adding together to the list of integration requests
- added Google Generative AI (gemini) integration
- Update README.md
- Update README.md
- add planning step + organize shell commands
- Update prompts.ts
- Update max_tokens in constants.ts
- More feature requests!!
- Merge pull request #7 from ocodo/main
- Docker Additions
- Added GitHub push functionality
- Create github-build-push.yml
- moved action
- Update github-build-push.yml
- Update github-build-push.yml
- Update github-build-push.yml
- Update github-build-push.yml
- Update README.md
- Merge pull request #28 from kofi-bhr/patch-1
- Merge pull request #8 from yunatamos/patch-1
- Merge pull request #1 from coleam00/main
- add mistral models
- mistral models added
- removed pixtral
- Merge branch 'coleam00:main' into main
- Update types.ts
- Update constants.ts
- Merge branch 'main' into add-docker-support
- Added deepseek models
- Merge branch 'main' of https://github.com/zenith110/bolt.new-any-llm
- Added more instructions for newbs
- Merge pull request #1 from mayurjobanputra/mayurjobanputra-patch-1
- Update docker-compose.yml
- Merge branch 'main' from coleam00 into add-docker-support
- Merge pull request #1 from ZerxZ/main
- Enabled boh dev and production docker images. Added convenience scripts and deconflicted start and dockerstart scripts
- updated ollama to use defined base URL for model calls
- Adding CONTRIBUTING.md specifically for this fork.
- Merge branch 'main' into main
- Merge pull request #11 from kofi-bhr/main
- Merge pull request #12 from fernsdavid25/patch-1
- Merge pull request #23 from aaronbolton/main
- Merge pull request #24 from goncaloalves/main
- Merge branch 'main' into main
- Merge pull request #30 from muzafferkadir/main
- Merge pull request #36 from ArulGandhi/main
- Merge pull request #44 from TarekS93/main
- Merge branch 'main' into main
- Merge pull request #51 from zenith110/main
- Merge branch 'main' into main
- Merge pull request #60 from ZerxZ/main
- Merge branch 'main' into main
- Merge pull request #64 from noobydp/main
- Cleanup and fixing Ollama models not showing up after merging changes
- Updating README with finished implementations and reorder the list of priorities
- Update constants.ts
- Enhancing Dockerfile to use a staged build, and docker-compose-yaml to use profiles, either 'development' or 'producion'. Adding nixpacks.toml to enable robust coolify support
- Corrected nixpacks.toml filename
- Merge pull request #70 from ArulGandhi/main
- Corrected nixpacks.toml filename
- Merge branch 'add-docker-support' of github.com:hillct/bolt.new-any-llm into add-docker-support Just a little cleanup... nixpax.toml is no more. Embedding Coolify config in Dockerfile and docker-compose.yaml
- Adding hints for Coolify config into docker-compose.yaml
- Adding full suffix o cocker-compose.yaml for ompatibiliy
- Merge branch 'main' into add-docker-support
- Corrected oudated docker build convenience script target
- Merge branch 'coleam00:main' into main
- main
- create .dockerignore file
- Added Docker Deployment documentation to CONTRIBUTING.md
- LM Studio Integration
- Remove Package-lock.json
- Added DEEPSEEK_API_KEY to .env.example
- Changed mode.ts to add BaseURL. Thanks @alumbs
- Merge branch 'coleam00:main' into main
- More feature requests! Will look at pull requests soon
- Merge pull request #55 from mayurjobanputra/main
- Merge pull request #71 from hillct/add-docker-support
- Fixing up Docker Compose to work with hot reloads in development and environment variables
- Merge pull request #77 from ajshovon/main
- Fixing up setup + installation instructions in README
- Small mention of hot reloading even when running in container
- Fix createGoogleGenerativeAI arguments
- Instructions on making Ollama models work well
- Merge branch 'coleam00:main' into main
- Update README.md changed .env to .env.local
- Making Ollama work within the Docker container, very important fix
- Moved provider and setProvider variables to the higher level component so that it can be accessed in sendMessage. Added provider to message queue in sendMessage. Changed streamText to extract both model and provider.
- Added sanitization for user messages. Use regex defined in constants.ts instead of redefining.
- Merge branch 'coleam00:main' into main
- Added support for xAI Grok Beta
- Added the XAI_API_KEY variable to the .env.example
- Merge pull request #196 from milutinke/x-ai
- Added the latest Sonnet 3.5 and Haiku 3.5
- Set numCtx = 32768 for Ollama models
- Merge pull request #209 from patrykwegrzyn/main
- added code streaming to editor while AI is writing code
- Show which model name and provider is used in user message.
- Merge branch 'main' into main
- Merge branch 'main' into new_bolt1
- Merge pull request #101 from ali00209/new_bolt1
- feat(bolt-terminal) bolt terminal integrated with the system
- Merge branch 'main' into respect-provider-choice
- Merge pull request #188 from TommyHolmberg/respect-provider-choice
- Fixing merge conflicts in BaseChat.tsx
- Noting that API key will still work if set in .env file
- Merge branch 'coleam00:main' into main
- Merge pull request #178 from albahrani/patch-1
- Merge branch 'main' into main
- Merge branch 'main' into claude-new-sonnet-and-haiku
- Merge pull request #205 from milutinke/claude-new-sonnet-and-haiku
- Update README.md
- Delete github-build-push.yml
- Merge branch 'main' of https://github.com/aaronbolton/bolt.new-any-llm
- Merge pull request #242 from aaronbolton/main
- Merge branch 'coleam00:main' into main
- @wonderwhy-er suggestion fix pr
- Merge branch 'main' of https://github.com/karrot0/bolt.new-any-llm
- Merge pull request #104 from karrot0/main
- Refactor/standartize model providers, add "get provider key" for those who have it for first time users
- Merge pull request #254 from ali00209/new_bolt5
- Merge pull request #247 from JNN5/main
- Bug fixes
- Merge pull request #228 from thecodacus/feature--bolt-shell
- Temporarily removing semantic-pr.yaml in order to verify otherwise ready for review PRs.
- Merge pull request #261 from chrismahoney/fix/remove-ghaction-titlecheck
- Merge branch 'main' into code-streaming
- temporary removed lock file
- recreated the lock file
- made types optional and, workbench get repo fix
- type fix
- Merge pull request #213 from thecodacus/code-streaming
- Merge remote-tracking branch 'coleam00/main' into addGetKeyLinks
- Use cookies instead of request body that is stale sometimes
- Added dynamic openrouter model list
- Fix google api key bug
- Various bug fixes around model/provider selection
- Merge branch 'coleam00:main' into main
- TypeCheck fix
- added rey effects for the UI as decorative elements
- More type fixes
- One more fix
- Update README.md
- Merge pull request #251 from wonderwhy-er/addGetKeyLinks
- Merge pull request #285 from cardonasMind/patch-1
- Merge pull request #158 from dmaksimov/main
- Removing console log of provider info
- Fix missing key for React.Fragment in Array map listing
- Merge pull request #296 from chrismahoney/fix/provider-consolelog
- Merge pull request #304 from thecodacus/fix-filetree-scroll-fix
- Merge pull request #118 from armfuls/main
- Add ability to return to older chat message state
- clean up unnecesary files
- excluded the action from execution pipeline
- .gitignore
- Add ability to duplicate chat in sidebar
- Huggingface Models Integrated
- Add windows start command
- Fix package.json
- Should not provide hard-coded OLLAMA_API_BASE_URL value in .env.example
- Merge pull request #321 from chrismahoney/fix/revert-ollamaurl
- Added tooltips and fork
- Show revert and fork only on AI messages
- Fix lost rewind functionality
- Lock file
- Created DEFAULT_NUM_CTX VAR with a deafult of 32768
- [UX] click shortcut in chat to go to source file in workbench
- revert spaces
- image-upload
- add module lucide-react
- Delete yarn.lock
- DEFAULT_NUM_CTX additions
- Merge pull request #314 from ahsan3219/main
- Merge pull request #305 from wonderwhy-er/Rewind-to-older-message
- Update the Google Gemini models list
- Fix the list of names to include the correct model
- Merge pull request #309 from thecodacus/fix-project-reload-execution-order
- Revert useless changes
- Merge pull request #330 from hgosansn/ux-click-open-file-in-chat
- Merge remote-tracking branch 'upstream/main'
- changing based on PR review
- Merge pull request #338 from kekePower/kekePower/update-google-models
- update comment to reflect the the codeline
- use a descriptive anique filename when downloading the files to zip
- Updating README with new features and a link to our community
- Merge pull request #347 from SujalXplores/fix/enhance-prompt
- .gitignore
- Add background for chat window
- Cohere support added
- max token is now dynamically handle for each model
- Merge pull request #350 from wonderwhy-er/Add-background-for-chat-window
- Merge branch 'coleam00:main' into main
- console message removed
- README.md updated
- flash fix
- another theme switch fix
- removed the background color from rays
- fixes for PR #332
- .
- model pickup
- Update stream-text.ts dynamic model max Token updated
- Merge pull request #351 from hasanraiyan/main
- mobile friendly
- mobile friendly editor scrollable option buttons
- Added speech to text capability
- Clear speech to text, listening upon submission
- Revert constant change
- Merge pull request #361 from qwikode/feature/mobile-friendly
- Limit linting to app
- Lint-fix all files in app
- Ignore some stackblitz specific linting rules
- header gradient and textarea border effect
- remove commented code
- picking right model
- Merge branch 'main' into main
- Merge pull request #328 from aaronbolton/main
- Merge remote-tracking branch 'upstream/main'
- merge with upstream
- Update to Gemini exp-1121
- Export chat from sidebar
- Fix linting issues
- Make tooltip easier to reuse across the app
- Added export button
- Merge remote-tracking branch 'upstream/main' into linting
- Merge pull request #371 from kekePower/update-google-gemini
- Merge remote-tracking branch 'upstream/main' into linting
- Lint and fix recent changes from main
- Added 3 new models to Huggingface
- Merge pull request #380 from kekePower/update-huggingface-models
- Merge remote-tracking branch 'upstream/main' into linting
- adds Husky 🐶 for pre-commit linting
- Add information about the linting pre-commit to the contributions guideline
- Merge pull request #367 from mrsimpson/linting
- Add import, fix export
- Merge remote-tracking branch 'coleam00/main' into import-export-individual-chats
- Lint fixes
- Type fixes
- Don't fix linting-issues pre-commit
- Terminal render too many times causing performance freeze
- Small change to make review easier
- Couple of bugfixes
- adding docs
- updated
- Merge pull request #372 from wonderwhy-er/import-export-individual-chats
- Small-cleanup-of-base-chat-component
- Proof of concept for folder import
- Merge pull request #412 from wonderwhy-er/Cleanup-extract-import-button
- work in progress poc git import
- Created FAQ at bottom of README
- Added roadmap to README FAQ
- Added parsing if ignore file and added handling of binary files
- Merge remote-tracking branch 'coleam00/main' into Import-folder
- Merge with master fixes
- Merge pull request #414 from SujalXplores/fix/eslint-issues
- Merge pull request #378 from mrsimpson/force-local-linting
- Merge pull request #411 from SujalXplores/fix/prettier-issue
- Merge pull request #422 from SujalXplores/feat/improve-sidebar
- Merge pull request #413 from wonderwhy-er/Import-folder
- Refinement of folder import
- shell commands failing on app reload
- artifact actionlist rendering in chat
- add prompt caching to README
- upload new files
- added faq
- Merge branch 'main' into docs
- updated name
- pipeline fix
- updated CI name
- reduced the filesize by over 7x, reduced image size to 1200x600
- Bump the npm_and_yarn group across 1 directory with 9 updates
- Merge pull request #456 from oTToDev-CE/dependabot/npm_and_yarn/npm_and_yarn-4762c9dd00
- Merge pull request #455 from oTToDev-CE/image-size
- fix
- Merge branch 'docs'
- Merge pull request #445 from thecodacus/docs
- Merge pull request #460 from oTToDev-CE/ollama-model-not-respected
- Merge pull request #440 from SujalXplores/feat/search-chats
- Merge branch 'coleam00:main' into main
- Update action-runner.ts
- Merge pull request #427 from PuneetP16/fix-app-reload
- merge with upstream/main
- adjusting spaces for X button in file-preview
- Merge pull request #488 from thecodacus/github-action-fix-for-docs
- Updated README Headings and Ollama Section
- liniting fix
- Merge pull request #9 from lassecapel/feat-add-custom-project-name
- Update constants.ts
- Update docker-compose.yaml
- added collapsable chat area
- Update ExamplePrompts.tsx
- Merge pull request #11 from PuneetP16/fix-artifact-code-block-rendering
- Merge pull request #10 from SujalXplores/feat/prompt-caching
- Update BaseChat.module.scss
- Update BaseChat.tsx
- Merge pull request #16 from dustinwloring1988/default-prompt-change
- Merge pull request #17 from dustinwloring1988/collapsible-model-and-provider
- Merge pull request #18 from dustinwloring1988/pretty-up
- Merge pull request #20 from dustinwloring1988/readme-heading-ollama-section
- Merge pull request #15 from dustinwloring1988/artifact-code-block
- Merge pull request #19 from dustinwloring1988/unique-name-on-download-zip
- Merge branch 'stable-additions' into linting-fix
- Merge pull request #21 from dustinwloring1988/linting-fix
- lint fix
- fixed path
- Merge pull request #22 from dustinwloring1988/stable-additions
- Merge pull request #23 from dustinwloring1988/prompt-caching
- Merge branch 'dev' into ui-glow
- Merge pull request #26 from dustinwloring1988/stable-additions
- Merge pull request #25 from dustinwloring1988/ui-glow
- small fixes
- Update ImportFolderButton.tsx
- last test fix
- hotfix
- hotfix for test and lint done
- updated packages
- Merge branch 'stable-additions' into stable-plus-ui-glow
- Merge pull request #491 from dustinwloring1988/stable-additions
- Updated features being developed in README
- Merge branch 'main' into stable-plus-ui-glow
- Merge pull request #493 from dustinwloring1988/stable-plus-ui-glow
- added example buttons
- Merge pull request #1 from dustinwloring1988/example-buttons
- Merge pull request #2 from hgosansn/main
- Merge pull request #7 from ibrain-one/feature/307-together-ai-integration
- improved start
- fixed typo
- fixed typo
- Merge pull request #11 from oTToDev-CE/improve-start
- Update package.json
- moved faq to its own page
- Update README.md
- Update README.md
- Merge pull request #21 from oTToDev-CE/readme-faq-mod
- Update README.md
- Update FAQ.md
- Update FAQ.md
- Updated SCSS to use @use instead of @import via sass-migrator
- Merge pull request #1 from oTToDev-CE/stable-changes
- pre commit lint
- Merge pull request #1 from dustinwloring1988/main
- Merge pull request #2 from calvinvette/main
- precommit lint
- new lint rules
- prompt enhanchment
- Merge pull request #2 from oTToDev-CE/main
- Update .env.example
- lint rules added and fixed
- Merge pull request #3 from oTToDev-CE/main
- added last lint rule for this update
- Merge pull request #4 from oTToDev-CE/main
- added the v3_lazyRouteDiscovery flag
- added artifact bundling for custom long artifacts like uploading folder
- Merge pull request #498 from dustinwloring1988/main
- Create main.yml
- Merge pull request #505 from oTToDev-CE/main
- Update README.md
- Merge pull request #506 from dustinwloring1988/doc-addition
- Update and rename main.yml to stale.yml
- Merge branch 'main' into docs-added-to-readme
- Merge remote-tracking branch 'origin/main' into bundle-artifact
- Merge pull request #508 from thecodacus/docs-added-to-readme
- Update stale.yml
- Merge remote-tracking branch 'coleam00/main' into Folder-import-refinement
- adding to display the image in the chat conversation. and paste image too. tnx to @Stijnus
- Update linting-failed-message in pre-commit
- Merge pull request #512 from mrsimpson/fix-lint-failed-message
- merge with upstream
- together AI Dynamic Models
- clean up
- Merge branch 'main' into github-import
- adding drag and drop images to text area
- added context to history
- fixed test cases
- added nvm for husky
- Implement chat description editing in sidebar and header, add visual cue for active chat in sidebar
- added bundled artifact
- added cookies storage for git
- updated pnpm.lock
- skipped images
- Merge branch 'main' into feat/improve-prompt-enhancement
- Merge pull request #428 from SujalXplores/feat/improve-prompt-enhancement
- Merge pull request #471 from sci3ma/patch-1
- Merge branch 'main' into fix/ui-gradient
- Merge pull request #368 from qwikode/fix/ui-gradient
- removed package lock file as this is not needed for pnpm repo, also added nvm support for husky
- added nvm support for husky
- Merge branch 'main' into improve-start-command-on-windows
- Merge pull request #316 from wonderwhy-er/improve-start-command-on-windows
- Merge pull request #519 from thecodacus/package-lock-removed
- Update bug_report.yml
- Merge pull request #520 from oTToDev-CE/doc/issue-template-update
- some minor fix
- fixed action-runner linting
- Merge pull request #483 from PuneetP16/feat/enhance-chat-description-management
- Merge branch 'main' into github-import
- Hardcode url for together ai as fallback if not set in env
- Hardcode url for together ai as fallback if not set in env
- Merge pull request #332 from atrokhym/main
- Updating README now that image attaching is merged, changing order of items in README list.
- Hardcode url for together ai as fallback if not set in env
- Split code a little bit
- lock file
- Merge pull request #537 from wonderwhy-er/Voice-input-with-fixes
- Added Fullscreen and Resizing to Preview
- Lint fix
- Merge pull request #550 from wonderwhy-er/pr-549
- Merge branch 'main' into together-ai-dynamic-model-list
- list fix
- Merge pull request #513 from thecodacus/together-ai-dynamic-model-list
- Merge pull request #533 from wonderwhy-er/harcode-together-ai-api-url-as-fallback
- added spinner
- Merge pull request #504 from thecodacus/bundle-artifact
- Merge branch 'main' into github-import
- Update BaseChat.tsx
- lint fix
- artifact bugfix
- Merge pull request #569 from thecodacus/fix-artifact-bug
- Merge branch 'main' into github-import
- fix bundling
- linting
- added lock file ignore
- Merge pull request #571 from thecodacus/artifact-bugfix
- Update to Gemini exp-1206
- Merge branch 'main' into github-import
- Added a tabbed setting modal
- Merge branch 'coleam00:main' into ui/model-dropdown
- Merge pull request #421 from thecodacus/github-import
- Merge branch 'main' into Folder-import-refinement
- add vue support for codemirror
- Merge branch 'main' into ui-background-rays
- background rays and changed the theme color to purple
- updated theme color
- Merge pull request #580 from oTToDev-CE/feat/add-tabbed-setting-modal
- Merge branch 'coleam00:main' into ui/model-dropdown
- fix position issue
- typecheck fix
- Merge pull request #565 from oTToDev-CE/ui/model-dropdown
- import from url
- Merge branch 'main' into git-import-from-url
- Small Style Update
- Update folderImport.ts
- Update ImportFolderButton.tsx
- Changed Colors
- Merge pull request #426 from wonderwhy-er/Folder-import-refinement
- Reuse automatic setup commands for git import
- Update readme
- Merge pull request #589 from wonderwhy-er/Add-command-detection-to-git-import-flow
- Merge branch 'main' into git-import-from-url
- added setup command
- More styling changes
- update to styles
- Merge pull request #585 from thecodacus/git-import-from-url
- Merge pull request #592 from oTToDev-CE/ui/settings-style
- Merge pull request #581 from mark-when/vue
- refactor(SettingWindow):Updated Settings Tab Styling
- updated padding
- added backdrop blur
- delete lock file
- added lockfile back
- Merge branch 'main' into update-setting-modal-styles
- added lock file
- Merge pull request #600 from thecodacus/update-setting-modal-styles
- Merge pull request #573 from kekePower/update-gemini-models
- Update docs
- Merge pull request #605 from dustinwloring1988/doc/removed-ollama-modelfile-section
- Update FAQ.md
- Merge pull request #606 from dustinwloring1988/doc/faq-clean-up
- removed test connection button
- fixed toggle not displaying in feature tab
- moved local models to the experimental features
- Remembers Settings In Features
- Merge pull request #610 from oTToDev-CE/ui/features-toggle-fix
- Merge branch 'main' into ui/add-tab-connections
- fix formatting error on conflict resolve
- Merge pull request #607 from oTToDev-CE/ui/add-tab-connections
- remaining changes
- Merge branch 'main' into ui-background-rays
- Merge pull request #282 from thecodacus/ui-background-rays
- added logo
- Merge pull request #625 from thecodacus/updated-logo-in-header
- console error fix due to duplicate keys
- moved log to only print on change, and changed error logs to warnings
- lint fix
- some more logs cleanup
- Replaced images to match new style
- Add files via upload
- Merge pull request #628 from thecodacus/console-error-fox-due-to-duplicate-keys-in-model-selector
- Add files via upload
- updated to adapth baseurl setup
- Merge pull request #629 from oTToDev-CE/doc/images-replace
- Updating name to Bolt.diy in README
- Updating git clone url in README.
- Fixing typo.
- Merge branch 'main' of https://github.com/stackblitz-labs/bolt.diy
- Update SettingsWindow.tsx
- Updating documentation link in README.
- Merge branch 'main' of https://github.com/stackblitz-labs/bolt.diy
- Merge pull request #635 from Bolt-CE/main
- updated docs with new name
- Changed Docs URL
- Merge pull request #637 from thecodacus/fix-docs
- fix Title
- Merge pull request #639 from thecodacus/fix-docs
- Merge pull request #638 from Bolt-CE/main
- merge
- Merge pull request #645 from wonderwhy-er/pr-620
- Remove other oTToDev mentions
- Merge pull request #648 from wonderwhy-er/Remove-ottodev-mentions
- Add gemini flash 2.0
- Merge pull request #649 from wonderwhy-er/Add-Gemini-2.0-flash
- Update prompts.ts
- Merge pull request #654 from Badbird5907/fix/prompt
- settings bugfix
- Merge pull request #662 from thecodacus/settings-bugfix
- Merge pull request #665 from AriPerkkio/docs/issue-template-link
- added start message for dev server
- Merge pull request #668 from thecodacus/terminal-start-log-for-dev-server
- Merge pull request #682 from thecodacus/bug/prestart-script
- added default value to true
- Merge pull request #683 from thecodacus/setting-default-value
- added verioning system and stable branch
- imporoved version for versioning system
- Merge pull request #688 from thecodacus/stable-branch-workflow
- Merge branch 'main' into chore--fix-versioning-workflow
- updated flow to use pnpm
- Merge pull request #689 from thecodacus/chore--fix-versioning-workflow
- fix the creds issue in workflow
- Merge pull request #690 from thecodacus/update-stable-workflow
- Merge pull request #691 from thecodacus/workflow-fix
- Merge pull request #692 from thecodacus/versioning-workflow
- updated workflow
- Merge pull request #695 from thecodacus/fix-versioning
- Merge pull request #696 from thecodacus/fix/workflow-permission
- Merge branch 'main' into update-socials
- Merge pull request #697 from thecodacus/update-socials
- Merge pull request #701 from thecodacus/auto-versioning #release
- skipping commit version
## 📈 Stats
**Full Changelog**: [`v0.0.3..v0.0.4`](https://github.com/stackblitz-labs/bolt.diy/compare/v0.0.3...v0.0.4)

View File

@@ -1,218 +1,219 @@
# Contribution Guidelines
## DEFAULT_NUM_CTX
Welcome! This guide provides all the details you need to contribute effectively to the project. Thank you for helping us make **bolt.diy** a better tool for developers worldwide. 💡
The `DEFAULT_NUM_CTX` environment variable can be used to limit the maximum number of context values used by the qwen2.5-coder model. For example, to limit the context to 24576 values (which uses 32GB of VRAM), set `DEFAULT_NUM_CTX=24576` in your `.env.local` file.
First off, thank you for considering contributing to Bolt.diy! This fork aims to expand the capabilities of the original project by integrating multiple LLM providers and enhancing functionality. Every contribution helps make Bolt.diy a better tool for developers worldwide.
---
## 📋 Table of Contents
- [Code of Conduct](#code-of-conduct)
- [How Can I Contribute?](#how-can-i-contribute)
- [Pull Request Guidelines](#pull-request-guidelines)
- [Coding Standards](#coding-standards)
- [Development Setup](#development-setup)
- [Deploymnt with Docker](#docker-deployment-documentation)
## Code of Conduct
1. [Code of Conduct](#code-of-conduct)
2. [How Can I Contribute?](#how-can-i-contribute)
3. [Pull Request Guidelines](#pull-request-guidelines)
4. [Coding Standards](#coding-standards)
5. [Development Setup](#development-setup)
6. [Testing](#testing)
7. [Deployment](#deployment)
8. [Docker Deployment](#docker-deployment)
9. [VS Code Dev Containers Integration](#vs-code-dev-containers-integration)
This project and everyone participating in it is governed by our Code of Conduct. By participating, you are expected to uphold this code. Please report unacceptable behavior to the project maintainers.
---
## How Can I Contribute?
## 🛡️ Code of Conduct
### 🐞 Reporting Bugs and Feature Requests
- Check the issue tracker to avoid duplicates
- Use the issue templates when available
- Include as much relevant information as possible
- For bugs, add steps to reproduce the issue
This project is governed by our **Code of Conduct**. By participating, you agree to uphold this code. Report unacceptable behavior to the project maintainers.
### 🔧 Code Contributions
1. Fork the repository
2. Create a new branch for your feature/fix
3. Write your code
4. Submit a pull request
---
### ✨ Becoming a Core Contributor
We're looking for dedicated contributors to help maintain and grow this project. If you're interested in becoming a core contributor, please fill out our [Contributor Application Form](https://forms.gle/TBSteXSDCtBDwr5m7).
## 🛠️ How Can I Contribute?
## Pull Request Guidelines
### 1⃣ Reporting Bugs or Feature Requests
- Check the [issue tracker](#) to avoid duplicates.
- Use issue templates (if available).
- Provide detailed, relevant information and steps to reproduce bugs.
### 📝 PR Checklist
- [ ] Branch from the main branch
- [ ] Update documentation if needed
- [ ] Manually verify all new functionality works as expected
- [ ] Keep PRs focused and atomic
### 2⃣ Code Contributions
1. Fork the repository.
2. Create a feature or fix branch.
3. Write and test your code.
4. Submit a pull request (PR).
### 👀 Review Process
1. Manually test the changes
2. At least one maintainer review required
3. Address all review comments
4. Maintain clean commit history
### 3⃣ Join as a Core Contributor
Interested in maintaining and growing the project? Fill out our [Contributor Application Form](https://forms.gle/TBSteXSDCtBDwr5m7).
## Coding Standards
---
### 💻 General Guidelines
- Follow existing code style
- Comment complex logic
- Keep functions focused and small
- Use meaningful variable names
## ✅ Pull Request Guidelines
## Development Setup
### PR Checklist
- Branch from the **main** branch.
- Update documentation, if needed.
- Test all functionality manually.
- Focus on one feature/bug per PR.
### 🔄 Initial Setup
1. Clone the repository:
### Review Process
1. Manual testing by reviewers.
2. At least one maintainer review required.
3. Address review comments.
4. Maintain a clean commit history.
---
## 📏 Coding Standards
### General Guidelines
- Follow existing code style.
- Comment complex logic.
- Keep functions small and focused.
- Use meaningful variable names.
---
## 🖥️ Development Setup
### 1⃣ Initial Setup
- Clone the repository:
```bash
git clone https://github.com/stackblitz-labs/bolt.diy.git
```
2. Install dependencies:
- Install dependencies:
```bash
pnpm install
```
3. Set up environment variables:
- Rename `.env.example` to `.env.local`
- Add your LLM API keys (only set the ones you plan to use):
- Set up environment variables:
1. Rename `.env.example` to `.env.local`.
2. Add your API keys:
```bash
GROQ_API_KEY=XXX
HuggingFace_API_KEY=XXX
OPENAI_API_KEY=XXX
ANTHROPIC_API_KEY=XXX
...
```
- Optionally set debug level:
```bash
VITE_LOG_LEVEL=debug
```
3. Optionally set:
- Debug level: `VITE_LOG_LEVEL=debug`
- Context size: `DEFAULT_NUM_CTX=32768`
- Optionally set context size:
```bash
DEFAULT_NUM_CTX=32768
```
**Note**: Never commit your `.env.local` file to version control. Its already in `.gitignore`.
Some Example Context Values for the qwen2.5-coder:32b models are.
* DEFAULT_NUM_CTX=32768 - Consumes 36GB of VRAM
* DEFAULT_NUM_CTX=24576 - Consumes 32GB of VRAM
* DEFAULT_NUM_CTX=12288 - Consumes 26GB of VRAM
* DEFAULT_NUM_CTX=6144 - Consumes 24GB of VRAM
**Important**: Never commit your `.env.local` file to version control. It's already included in .gitignore.
### 🚀 Running the Development Server
### 2⃣ Run Development Server
```bash
pnpm run dev
```
**Tip**: Use **Google Chrome Canary** for local testing.
**Note**: You will need Google Chrome Canary to run this locally if you use Chrome! It's an easy install and a good browser for web development anyway.
---
## Testing
## 🧪 Testing
Run the test suite with:
```bash
pnpm test
```
## Deployment
---
To deploy the application to Cloudflare Pages:
## 🚀 Deployment
### Deploy to Cloudflare Pages
```bash
pnpm run deploy
```
Ensure you have required permissions and that Wrangler is configured.
Make sure you have the necessary permissions and Wrangler is correctly configured for your Cloudflare account.
---
# Docker Deployment Documentation
## 🐳 Docker Deployment
This guide outlines various methods for building and deploying the application using Docker.
This section outlines the methods for deploying the application using Docker. The processes for **Development** and **Production** are provided separately for clarity.
## Build Methods
---
### 1. Using Helper Scripts
### 🧑‍💻 Development Environment
NPM scripts are provided for convenient building:
#### Build Options
**Option 1: Helper Scripts**
```bash
# Development build
npm run dockerbuild
```
**Option 2: Direct Docker Build Command**
```bash
docker build . --target bolt-ai-development
```
**Option 3: Docker Compose Profile**
```bash
docker-compose --profile development up
```
#### Running the Development Container
```bash
docker run -p 5173:5173 --env-file .env.local bolt-ai:development
```
---
### 🏭 Production Environment
#### Build Options
**Option 1: Helper Scripts**
```bash
# Production build
npm run dockerbuild:prod
```
### 2. Direct Docker Build Commands
You can use Docker's target feature to specify the build environment:
**Option 2: Direct Docker Build Command**
```bash
# Development build
docker build . --target bolt-ai-development
# Production build
docker build . --target bolt-ai-production
```
### 3. Docker Compose with Profiles
Use Docker Compose profiles to manage different environments:
**Option 3: Docker Compose Profile**
```bash
# Development environment
docker-compose --profile development up
# Production environment
docker-compose --profile production up
```
## Running the Application
After building using any of the methods above, run the container with:
#### Running the Production Container
```bash
# Development
docker run -p 5173:5173 --env-file .env.local bolt-ai:development
# Production
docker run -p 5173:5173 --env-file .env.local bolt-ai:production
```
## Deployment with Coolify
---
[Coolify](https://github.com/coollabsio/coolify) provides a straightforward deployment process:
### Coolify Deployment
1. Import your Git repository as a new project
2. Select your target environment (development/production)
3. Choose "Docker Compose" as the Build Pack
4. Configure deployment domains
5. Set the custom start command:
For an easy deployment process, use [Coolify](https://github.com/coollabsio/coolify):
1. Import your Git repository into Coolify.
2. Choose **Docker Compose** as the build pack.
3. Configure environment variables (e.g., API keys).
4. Set the start command:
```bash
docker compose --profile production up
```
6. Configure environment variables
- Add necessary AI API keys
- Adjust other environment variables as needed
7. Deploy the application
## VS Code Integration
---
The `docker-compose.yaml` configuration is compatible with VS Code dev containers:
## 🛠️ VS Code Dev Containers Integration
1. Open the command palette in VS Code
2. Select the dev container configuration
3. Choose the "development" profile from the context menu
The `docker-compose.yaml` configuration is compatible with **VS Code Dev Containers**, making it easy to set up a development environment directly in Visual Studio Code.
## Environment Files
### Steps to Use Dev Containers
Ensure you have the appropriate `.env.local` file configured before running the containers. This file should contain:
- API keys
- Environment-specific configurations
- Other required environment variables
1. Open the command palette in VS Code (`Ctrl+Shift+P` or `Cmd+Shift+P` on macOS).
2. Select **Dev Containers: Reopen in Container**.
3. Choose the **development** profile when prompted.
4. VS Code will rebuild the container and open it with the pre-configured environment.
## Notes
---
- Port 5173 is exposed and mapped for both development and production environments
- Environment variables are loaded from `.env.local`
- Different profiles (development/production) can be used for different deployment scenarios
- The configuration supports both local development and production deployment
## 🔑 Environment Variables
Ensure `.env.local` is configured correctly with:
- API keys.
- Context-specific configurations.
Example for the `DEFAULT_NUM_CTX` variable:
```bash
DEFAULT_NUM_CTX=24576 # Uses 32GB VRAM
```

Some files were not shown because too many files have changed in this diff Show More