320 Commits

Author SHA1 Message Date
713a3db8ce fix(build): pnpm install --prod=false so devDeps (remix, husky) are present during docker build
Some checks failed
Mark Stale Issues and Pull Requests / stale (push) Has been cancelled
2026-04-30 22:15:16 +00:00
d9eea2adaf fix(build): make prepare script tolerant of missing husky in production install 2026-04-30 22:14:02 +00:00
6fd45ff34c feat: rebrand to Slate (logo, palette, copy, Launch button)
- Wordmark SVG + favicon (#FF1F8F → #00D4FF gradient)
- Page title: Slate — AI App Builder
- Header logo via inline component (no external font deps)
- Deploy button label -> Launch
- Chat placeholder + example prompt rebranded
- Replace upstream accent palette with magenta primary, add cyan2 for accents
- Settings tab notes upstream remains stackblitz-labs/bolt.diy
2026-04-30 22:08:08 +00:00
github-actions[bot]
5d3fb1d7de chore: release version 1.0.0 2025-05-12 01:53:53 +00:00
github-actions[bot]
dac37b4344 chore: release version 1.0.0 2025-05-12 01:53:52 +00:00
KevIsDev
ebd840263c fix: replace non existent icons with existing icons #release:major 2025-05-12 02:51:05 +01:00
KevIsDev
c1474d85e5 Merge branch 'main' into stable 2025-05-12 02:45:27 +01:00
KevIsDev
553fa5d138 fix: revert back to previous commit 2025-05-12 02:43:08 +01:00
KevIsDev
a76013f031 ci: reorder steps and add env vars for Electron build #release:major 2025-05-12 02:17:11 +01:00
KevIsDev
3779000ec5 Revert "ci: reorder steps and add env vars for Electron build #release:major"
This reverts commit 9c0e898d17.
2025-05-12 02:15:31 +01:00
KevIsDev
9c0e898d17 ci: reorder steps and add env vars for Electron build #release:major
Reordered the "Commit and Tag Release" step to ensure it runs before uploading release assets. Added environment variables `GH_TOKEN`, `GITHUB_TOKEN`, and `NODE_OPTIONS` to the Electron build, added authentication and memory allocation during the build process.
2025-05-12 02:12:32 +01:00
KevIsDev
dee7fb0545 Merge branch 'main' into stable 2025-05-12 01:56:42 +01:00
KevIsDev
e9df523a79 fix: icon classes to existing icons #release:major
- Replace specific file type icons that are non existent with generic 'file-code' icon.
2025-05-12 01:50:28 +01:00
KevIsDev
5630be7f54 Revert "fix: fix icon classes for consistency and clarity #release:major"
This reverts commit 6e9a1b6874.
2025-05-12 01:44:51 +01:00
KevIsDev
6e9a1b6874 fix: fix icon classes for consistency and clarity #release:major
- Replace specific file type icons that are non existent with generic 'file-code' icon.
2025-05-12 01:37:03 +01:00
KevIsDev
0e31267078 Merge branch 'main' into stable 2025-05-12 01:31:47 +01:00
KevIsDev
73442dde87 ci: add Electron build process to release workflow
Add steps to build and upload Electron app artifacts as part of the release workflow. This includes setting up Node.js, installing dependencies, and building the app for different platforms (Windows, macOS, Linux). The built artifacts are then uploaded as release assets.
2025-05-12 01:08:34 +01:00
KevIsDev
4354ad45b9 git push origin mainRevert "fix: fix icon classes for consistency and clarity #release:major"
This reverts commit 870828d551.
2025-05-12 00:15:16 +01:00
github-actions[bot]
e6fd901e55 chore: release version 1.0.0 2025-05-11 23:03:05 +00:00
KevIsDev
870828d551 fix: fix icon classes for consistency and clarity #release:major
- Replace specific file type icons that are non existent with generic 'file-code' icon.

- We now Include the electron builds with each release only
2025-05-12 00:02:28 +01:00
KevIsDev
b089a4b7f1 Merge pull request #1688 from xKevIsDev/main
refactor: optimize error handling and npm install performance
2025-05-10 13:29:28 +01:00
KevIsDev
9a748177ef refactor: optimize error handling and npm install performance
Remove redundant error type handling in webcontainer to simplify logic and improve maintainability. Additionally, comment out lock file patterns to speed up npm install process.
2025-05-10 13:24:08 +01:00
Stijnus
870bfc58ee feat: github fix and ui improvements (#1685)
* feat: Add reusable UI components and fix GitHub repository display

* style: Fix linting issues in UI components

* fix: Add close icon to GitHub Connection Required dialog

* fix: Add CloseButton component to fix white background issue in dialog close icons

* Fix close button styling in dialog components to address ghost white issue in dark mode

* fix: update icon color to tertiary for consistency

The icon color was changed from `text-bolt-elements-icon-info` to `text-bolt-elements-icon-tertiary`

* fix: improve repository selection dialog tab styling for dark mode

- Update tab menu styling to prevent white background in dark mode
- Use explicit color values for better dark/light mode compatibility
- Improve hover and active states for better visual hierarchy
- Remove unused Tabs imports

---------

Co-authored-by: KevIsDev <zennerd404@gmail.com>
2025-05-09 15:23:20 +02:00
Stijnus
9a5076d8c6 feat: lock files (#1681)
* Add persistent file locking feature with enhanced UI

* Fix file locking to be scoped by chat ID

* Add folder locking functionality

* Update CHANGES.md to include folder locking functionality

* Add early detection of locked files/folders in user prompts

* Improve locked files detection with smarter pattern matching and prevent AI from attempting to modify locked files

* Add detection for unlocked files to allow AI to continue with modifications in the same chat session

* Implement dialog-based Lock Manager with improved styling for dark/light modes

* Add remaining files for file locking implementation

* refactor(lock-manager): simplify lock management UI and remove scoped lock options

Consolidate lock management UI by removing scoped lock options and integrating LockManager directly into the EditorPanel. Simplify the lock management interface by removing the dialog and replacing it with a tab-based view. This improves maintainability and user experience by reducing complexity and streamlining the lock management process.

Change Lock & Unlock action to use toast instead of alert.

Remove LockManagerDialog as it is now tab based.

* Optimize file locking mechanism for better performance

- Add in-memory caching to reduce localStorage reads
- Implement debounced localStorage writes
- Use Map data structures for faster lookups
- Add batch operations for locking/unlocking multiple items
- Reduce polling frequency and add event-based updates
- Add performance monitoring and cross-tab synchronization

* refactor(file-locking): simplify file locking mechanism and remove scoped locks

This commit removes the scoped locking feature and simplifies the file locking mechanism. The `LockMode` type and related logic have been removed, and all locks are now treated as full locks. The `isLocked` property has been standardized across the codebase, replacing the previous `locked` and `lockMode` properties. Additionally, the `useLockedFilesChecker` hook and `LockAlert` component have been removed as they are no longer needed with the simplified locking system.

This gives the LLM a clear understanding of locked files and strict instructions not to make any changes to these files

* refactor: remove debug console.log statements

---------

Co-authored-by: KevIsDev <zennerd404@gmail.com>
2025-05-08 00:07:32 +02:00
KevIsDev
5c9d413344 Merge pull request #1682 from Stijnus/origin/ACT_BoltDYI_BUGFIX_SEARCH
fix: invalid line number error in search functionality
2025-05-04 23:19:38 +01:00
Stijnus
15a84f2e24 Fix invalid line number error in search functionality 2025-05-03 23:54:21 +02:00
KevIsDev
844da4b1c2 Merge pull request #1677 from xKevIsDev/improvements
ci: remove macOS code signing credentials from workflow
2025-05-01 19:33:44 +01:00
KevIsDev
9bf677ce74 ci: remove macOS code signing credentials from workflow
The code signing credentials for macOS were removed from the GitHub Actions workflow and the identity field in the electron-builder.yml was set to null. This change was made to include unsigned .dmg releases
2025-05-01 19:30:51 +01:00
KevIsDev
5224dea39e Merge pull request #1676 from xKevIsDev/improvements
feat: implement a search functionality to search codebase
2025-05-01 19:18:49 +01:00
KevIsDev
d6a4aff7b7 ci(workflow): re-enable macos-latest in build matrix
Re-enable macos-latest in the build matrix for the Electron workflow. This allows testing on macOS (unsigned .dmg)
2025-05-01 17:27:45 +01:00
KevIsDev
b3e1048fa4 refactor(Search): improve search UX with loader timing and state management
Enhance the search experience by ensuring the loader is displayed for a minimum duration to avoid flickering. Additionally, introduce a `hasSearched` state to accurately display "No results found" only after a search has been performed.
2025-05-01 17:19:29 +01:00
KevIsDev
fcaf8f66f0 feat: enhance error handling and add new search feature
- Add support for `PREVIEW_CONSOLE_ERROR` in WebContainer error handling

- Introduce new Search component for text search functionality

- Extend `ScrollPosition` interface to include `line` and `column`
- Implement scroll-to-line functionality in CodeMirrorEditor
- Add tab-based navigation for files and search in EditorPanel

This commit introduces several enhancements to the editor, including improved error handling, better scrolling capabilities, and a new search feature. The changes are focused on improving the user experience and adding new functionality to the editor components.
2025-05-01 15:56:08 +01:00
KevIsDev
9d5c66cd50 Merge pull request #1675 from xKevIsDev/improvements
chore: update @webcontainer/api to version 1.6.1-internal.1
fix: fix: make diff button consistent with other toolbar buttons originally fixed in PR #1601 but had been overwritten
2025-05-01 11:56:10 +01:00
KevIsDev
3b2e869651 chore: update @webcontainer/api to version 1.6.1-internal.1
update to latest version of webcontainer

fix: make diff button consistent with other toolbar buttons
2025-05-01 11:51:19 +01:00
KevIsDev
837e64a605 Merge pull request #1651 from xKevIsDev/improvements
feat: add expo app creation, enhance ui, and refactor code
2025-04-30 12:48:15 +01:00
KevIsDev
0dd8fb7707 refactor(chat): move modern-scrollbar class to conditional styling
Improves maintainability by moving the 'modern-scrollbar' class to the conditional styling block in BaseChat.tsx, making the code more consistent and easier to manage.
2025-04-30 12:43:54 +01:00
KevIsDev
9454c73992 style: add modern-scrollbar class to improve scrollbar appearance
Introduce the modern-scrollbar class to enhance the visual consistency of scrollbars across the application. This class provides a cleaner and more modern look for scrollbars in WebKit and Firefox browsers.
2025-04-30 12:23:35 +01:00
KevIsDev
e30035cec5 feat(templates): add Vite Shadcn starter template
Introduce a new starter template for Vite with shadcn/ui integration. The template includes React, TypeScript, and Tailwind, and is added to the STARTER_TEMPLATES list. Additionally, update the styling in StarterTemplates component to better accommodate the new template and add the shadcn.svg icon.
2025-04-30 11:37:29 +01:00
KevIsDev
f430443aef refactor: remove debug logging statements
Clean up code by removing unnecessary debug logging statements in `StarterTemplates.tsx` and `useShortcuts.ts`. Making it easier to debug issues in console
2025-04-30 02:11:54 +01:00
KevIsDev
a83f864fa1 refactor): provider dropdown and model selector
Refactor the existing provider selector to improve code clarity and match the model selection dropdown.
2025-04-30 01:57:47 +01:00
KevIsDev
e6dae47ce4 refactor(prompts): update and refine UI design and content guidelines
Refine the UI design and content guidelines in the prompts to ensure consistency and professionalism. Add detailed instructions for animations, color schemes, typography, and layout.

Remove redundant console log in the LLM stream-text module.
2025-04-30 01:24:31 +01:00
KevIsDev
51762835d5 refactor(llm): simplify streamText function and remove unused code
Remove unused imports, files parameter, and redundant multimodal handling logic. Streamline the function by directly passing processed messages to _streamText. Also, add specific handling to remove package-lock.json content to reduce token usage
2025-04-30 00:50:00 +01:00
KevIsDev
3a894d0516 feat(chat): add dynamic title support for bundled artifacts
Introduce dynamic titles for bundled artifacts based on their state and ID. This improves user experience by providing more context during project creation or restoration. Also, pass the `title` parameter to the `getTemplates` function to customize the artifact title.
2025-04-29 14:37:17 +01:00
KevIsDev
902166efee fix(chat): ensure artifact actions are correctly evaluated for completion
The dependency array in the Artifact component was missing `artifact.type` and `allActionFinished`, which could lead to incorrect evaluation of action completion. Additionally, the logic for determining if all actions are finished was updated to account for 'start' actions that are 'running'. This ensures that the component accurately reflects the state of bundled artifacts.
2025-04-28 14:34:07 +01:00
KevIsDev
cfbc215001 fix(chat): update artifact ID check for restored project setup
The artifact ID check was updated from 'imported-files' to 'restored-project-setup' to correctly identify the restored project setup action. This ensures the UI displays the appropriate message based on the artifact's state.
2025-04-28 14:29:06 +01:00
KevIsDev
42eaa2f5e1 refactor(chat): improve UI layout, artifact handling, and template naming
- Restructured alert components in BaseChat for better layout organization
- Updated artifact component to display dynamic titles based on state
- Simplified template names in constants for better readability
- Enhanced snapshot restoration process by consolidating command actions into a single artifact
2025-04-28 14:03:58 +01:00
KevIsDev
bf03b6f0fe refactor(chat): move ScrollToBottom function outside BaseChat component
Improve code maintainability by relocating the ScrollToBottom function outside the BaseChat component. This reduces complexity and enhances readability.
2025-04-28 11:10:51 +01:00
KevIsDev
d5ced7e305 refactor: update prompt to be more specific with install and run commands
remove gemini model as this is now fetched dynamically
2025-04-25 00:54:01 +01:00
KevIsDev
65b78280d0 feat(chat): add scroll-to-bottom button for chat messages
Introduce a `ScrollToBottom` component that displays a button when the user is not at the bottom of the chat, allowing them to quickly scroll to the latest message. This improves user experience by making it easier to navigate long chat histories.
2025-04-24 13:31:23 +01:00
KevIsDev
deef4d9c4d style(FilePreview): remove border and adjust styling for better UI consistency
The border around the image was removed to simplify the design, and the bottom text container was updated to include a background color and rounded corners for better visual coherence
2025-04-24 12:08:08 +01:00
KevIsDev
cdabfc3f6f style(chat): update button variants and improve file preview styling
Change button variants from 'outline' to 'default' for consistency across components. Enhance FilePreview component with better spacing, borders, and file name display to improve visual clarity and user experience.
2025-04-24 11:55:14 +01:00
KevIsDev
516dc9dc28 refactor(constants): remove duplicate tag and add 'app' tag
The 'mobile app' tag was duplicated in the STARTER_TEMPLATES array, so it was removed. Additionally, the 'app' tag was added to the React + Vite + typescript template to better categorize it.
2025-04-24 11:17:37 +01:00
KevIsDev
3cafbb6f59 feat(prompts): add fine-tuned prompt and update mobile app instructions
Introduce a new fine-tuned prompt for better results and update mobile app development instructions to ensure comprehensive guidance. The changes include enhanced design guidelines, improved database handling, and clearer artifact creation rules for better project setup.
2025-04-24 10:59:29 +01:00
KevIsDev
02401b90aa refactor(qr-code): replace react-qr-code with react-qrcode-logo
- Updated package.json and pnpm-lock.yaml to use react-qrcode-logo v3.0.0
- Modified ExpoQrModal.tsx to use the new QRCode component with enhanced styling and logo support
- Removed filtering of lock.json files in useChatHistory.ts and stream-text.ts for consistency
- Updated mobile app instructions in prompts.ts to ensure clarity and alignment with best practices
2025-04-23 16:43:01 +01:00
KevIsDev
f06dd8a7b1 docs(prompts): refine and expand design instructions for clarity
Update the design instructions to emphasize the importance of content richness and realistic placeholders. This ensures applications feel functional and visually appealing immediately, avoiding generic templates and empty screens.
2025-04-23 12:40:51 +01:00
KevIsDev
fe37f5ceea refactor: migrate snapshot storage from localStorage to IndexedDB
To improve data consistency and reliability, snapshot storage has been migrated from localStorage to IndexedDB. This change includes adding a new 'snapshots' object store, updating database version to 2, and modifying related functions to use IndexedDB for snapshot operations. The migration ensures better handling of snapshots alongside chat data and removes dependency on localStorage preventing UI lag.
2025-04-23 12:17:06 +01:00
KevIsDev
5c44cb4e00 docs(prompts): update mobile app development instructions and styling guidelines
Refine mobile app development instructions to ensure clarity and consistency. Enhance styling guidelines with detailed design system requirements, including color, typography, and responsive design. Update critical requirements for components, animations, and error handling to align with best practices.
2025-04-22 22:26:29 +01:00
KevIsDev
b009b02057 refactor(chat): replace useSnapScroll with StickToBottom for smoother scrolling
The useSnapScroll hook has been replaced with the StickToBottom component to improve the scrolling behavior in the chat interface. This change ensures smoother and more consistent scrolling, especially when new messages are added. The StickToBottom component provides better control over the scroll position and handles edge cases more effectively.
2025-04-22 21:33:40 +01:00
KevIsDev
b41691f6f2 feat(previews): add refreshAllPreviews method to refresh all previews
This commit introduces the `refreshAllPreviews` method in the `PreviewsStore` class, which iterates through all previews and triggers a file change broadcast for each. This ensures that all previews are updated after a file save operation.

refactor(CodeBlock): handle unsupported languages by falling back to plaintext

The `CodeBlock` component now defaults to 'plaintext' when an unsupported language is detected, improving the user experience by avoiding unsupported language errors.

prompts: update dependency installation instructions

The prompts documentation has been updated to clarify the process of installing dependencies, emphasizing the importance of updating `package.json` first and avoiding individual package installations.
2025-04-22 20:42:38 +01:00
KevIsDev
458c263931 docs(prompts): update mobile app development and design instructions
Refactor and consolidate mobile app development and design guidelines in the prompts files. Remove redundant information and ensure clarity and consistency in the instructions. The changes aim to provide a more structured and concise set of guidelines for developers working on mobile apps using Expo and React Native.
2025-04-22 13:00:03 +01:00
KevIsDev
ffac7bfbfc docs(prompts): update artifact and design instructions
- Clarify critical instructions regarding artifact creation and image files
- Add detailed design instructions for visual identity, UX, and layout
- Include guidance on using Unsplash for stock photos and realistic placeholder content
2025-04-22 11:56:30 +01:00
KevIsDev
443dc646fb refactor(files): optimize file deletion logic for better performance
Refactor the file deletion logic in FilesStore to precompute prefixes and iterate through files only once. This reduces the complexity of nested loops and improves performance by applying all deletions in a single update to the store. Additionally, remove a redundant console.log statement in Chat.client.tsx and update the prompts documentation for clarity.
2025-04-19 12:57:14 +01:00
KevIsDev
9b4736921f refactor(workbench): simplify URL handling and improve PortDropdown UI
- Replace `url` state with `displayPath` in Preview component to focus on path handling
- Update PortDropdown to display active port and improve styling
- Remove redundant URL validation logic
2025-04-19 00:47:14 +01:00
KevIsDev
685677b986 style(icons): update icon classes and add netlify.svg
Update icon classes across multiple components to improve consistency and add the netlify.svg file for the Netlify icon.
2025-04-19 00:05:04 +01:00
Leex
81168093cf Merge pull request #1601 from mark-when/overflow
fix: make diff button consistent with other toolbar buttons
2025-04-19 00:20:00 +02:00
KevIsDev
adcdc8efdf feat(llm): add new models for xAI and Google providers
Add 'grok-3-beta' to xAI provider and 'gemini-2.5-flash-preview-04-17' to Google provider. Also, ensure file saving when content is updated in WorkbenchStore and update streaming indicator styling in chat messages.
2025-04-18 13:45:11 +01:00
KevIsDev
c08be2f1fb refactor: move qrCodeStore to lib/stores for better organization
The qrCodeStore has been relocated from the app/stores directory to app/lib/stores to maintain a more consistent and organized project structure. This change improves maintainability by centralizing store-related files in a dedicated directory.
2025-04-18 11:45:14 +01:00
KevIsDev
f90fd79064 feat(chat): add new example prompt for bolt.diy app
This commit introduces a new example prompt in the chat component to guide users in creating a mobile app about bolt.diy
2025-04-17 14:54:50 +01:00
KevIsDev
3b5d404330 refactor: remove unused qrCodeAtom and update mobile app prompts
Remove the unused `qrCodeAtom` from the QR code store to clean up the codebase. Additionally, update the mobile app development prompts to emphasize critical requirements, such as creating a default route, ensuring high-quality UI/UX, and following Expo best practices.
2025-04-17 13:43:48 +01:00
KevIsDev
9039653ae0 feat: add Expo QR code generation and modal for mobile preview
Introduce Expo QR code functionality to allow users to preview their projects on mobile devices. Added a new QR code modal component, integrated it into the chat and preview components, and implemented Expo URL detection in the shell process. This enhances the mobile development workflow by providing a seamless way to test Expo projects directly on devices.

- Clean up and consolidate Preview icon buttons while removing redundant ones.
2025-04-17 13:03:41 +01:00
KevIsDev
cbc22cdbdb style(chat): adjust spacing and margins in chat components
- Reduce gap between elements in BaseChat component from `gap-4` to `gap-2`
- Remove bottom margin from AssistantMessage component for cleaner layout
- Add expo.svg icon to the icons directory for future use
2025-04-16 13:17:55 +01:00
KevIsDev
3ca85875f1 feat(chat): adjust chat layout and add rewind/fork functionality
- Modify chat max/min width for better responsiveness
- Update UserMessage and AssistantMessage components for improved alignment
- Add rewind and fork functionality to AssistantMessage
- Refactor Artifact component to handle bundled artifacts more clearly
2025-04-15 22:54:00 +01:00
KevIsDev
682ed764a9 docs(mobile_app_instructions): update project structure and requirements
Clarify the mobile app development process by adding a required home page and emphasizing the importance of following the provided project structure. Remove outdated sections like accessibility, development workflow, and common pitfalls to streamline the instructions.
2025-04-15 21:37:18 +01:00
KevIsDev
76ed2bef69 style: fix code formatting and remove unused imports
- Fix indentation in Preview.tsx and normalize quotes
- Remove unused import in selectStarterTemplate.ts
- Improve code readability in api.github-template.ts
2025-04-15 15:33:12 +01:00
KevIsDev
63129a93cd feat: add webcontainer connect route and new preview functionality
- Add new route `webcontainer.connect.$id.tsx` for WebContainer connection
- Implement `openInNewTab` function in `Preview.tsx` for opening previews in new tabs
- Update GitHub template fetching logic to include lock files for improved install times
- Add new Expo starter template to constants
- Extend prompts with mobile app development instructions
-Templates now use Releases from github as a work around for rate limits
2025-04-15 15:32:40 +01:00
KevIsDev
2f09d512bc Merge pull request #1644 from xKevIsDev/webcontainer-upgrade
fix: optimize file watch paths for preview updates and fix npm crashes
2025-04-14 14:15:18 +01:00
KevIsDev
37504a354c Merge pull request #1625 from Derek-X-Wang/fix-electron-load-build-dep-mismatch
fix(electron): fix load server build problem by fix dep version
2025-04-14 13:51:39 +01:00
KevIsDev
92e7e868d5 chore: update @webcontainer/api to version 1.5.3-internal.2
Update the dependency to leverage the latest internal features and improvements.
2025-04-14 13:38:31 +01:00
KevIsDev
7615c956c2 fix: optimize file watch paths for preview updates and fix npm crashes.
Update the file watch paths in the previews store to only include relevant file types (e.g., HTML, CSS, JS) and exclude unnecessary directories (e.g., node_modules, dist). This reduces unnecessary file system events and improves performance.

Also, update the @webcontainer/api dependency to the latest internal version for enhanced functionality, node20 etc.
2025-04-14 13:34:33 +01:00
Derek Wang
0339f4fb62 fix: remove unusable scripts 2025-04-09 15:25:44 -07:00
Derek Wang
7fefee4bc5 fix(electron): fix load server build problem by fix dep version 2025-04-09 02:45:12 -07:00
Stijnus
0202aefad9 feat: fix for push private repo (#1618)
* feat: push private repo

# GitHub Integration Changelog

## Fixed
- Fixed issue where repositories marked as private weren't being created with private visibility
- Added support for changing repository visibility (public/private) when pushing to existing repositories
- Fixed 404 errors when pushing files after changing repository visibility

## Added
- Added clear user warnings when changing repository visibility from public to private or vice versa
- Implemented delays after visibility changes to allow GitHub API to fully process the change
- Added retry mechanism (up to 3 attempts with increasing delays) for pushing files after visibility changes
- Added repository data refresh before pushing to ensure latest reference data

## Improved
- Enhanced error logging and handling for all GitHub API operations
- Updated return value handling to use actual repository URLs from the API response
- Added comprehensive logging to track repository creation and update operations

* cleanup

* Update Workbench.client.tsx
2025-04-08 22:20:54 +02:00
Stijnus
552f08acea feat: update connectiontab and datatab security fix (#1614)
* feat: update connectiontab and datatab security fix

# Connection Components and Diagnostics Updates

## GitHub Connection Component Changes
- Updated the disconnect button styling to match Vercel's design:
  - Changed from `<Button>` component to native `<button>` element
  - Added red background (`bg-red-500`) with hover effect (`hover:bg-red-600`)
  - Updated icon from `i-ph:sign-out` to `i-ph:plug`
  - Simplified text to just "Disconnect"
  - Added connection status indicator with check-circle icon and "Connected to GitHub" text

## ConnectionDiagnostics Tab Updates
### Added New Connection Diagnostics
- Implemented diagnostics for Vercel and Supabase connections
- Added new helper function `safeJsonParse` for safer JSON parsing operations

### Diagnostic Checks Added
- **Vercel Diagnostics:**
  - LocalStorage token verification
  - API endpoint connectivity test
  - Connection status validation
  - Reset functionality for Vercel connection

- **Supabase Diagnostics:**
  - LocalStorage credentials verification
  - API endpoint connectivity test
  - Connection status validation
  - Reset functionality for Supabase connection

### UI Enhancements
- Added new status cards for Vercel and Supabase
- Implemented reset buttons with consistent styling
- Added loading states during diagnostics
- Enhanced error handling and user feedback

### Function Updates
- Extended `runDiagnostics` function to include Vercel and Supabase checks
- Added new reset helper functions for each connection type
- Improved error handling and status reporting
- Enhanced toast notifications for better user feedback

### Visual Consistency
- Matched styling of new diagnostic cards with existing GitHub and Netlify cards
- Consistent use of icons and status indicators
- Uniform button styling across all connection types
- Maintained consistent spacing and layout patterns

### Code Structure
- Organized diagnostic checks into clear, separate sections
- Improved error handling and type safety
- Enhanced code readability and maintainability
- Added comprehensive status compilation for all connections

These changes ensure a consistent user experience across all connection types while providing robust diagnostic capabilities for troubleshooting connection issues.

# DataTab.tsx Changes

## Code Cleanup
- Removed unused variables from useDataOperations hook:
  - Removed `handleExportAPIKeys`
  - Removed `handleUndo`
  - Removed `lastOperation`

This change improves code quality by removing unused variables and resolves ESLint warnings without affecting any functionality.

* Test commit to verify pre-commit hook
2025-04-08 13:06:43 +02:00
KevIsDev
8c70dd6123 Merge pull request #1613 from xKevIsDev/vercel-fix
refactor: remove success toast and prioritize public domain URL
2025-04-08 11:56:00 +01:00
KevIsDev
8d1d1506ad Merge pull request #1602 from mark-when/overflow2
feat: consolidate sync & export items into an overflow menu
2025-04-07 23:20:41 +01:00
KevIsDev
03349f8517 refactor: remove success toast and prioritize public domain URL
Remove redundant success toast messages from Vercel and Netlify deploy components. Additionally, prioritize the public domain URL over the private domain in the Vercel deploy action for consistency and clarity.
2025-04-07 23:07:58 +01:00
KevIsDev
6996b807d5 Merge pull request #1590 from xKevIsDev/main
fix: simplify the SHA-1 hash function in netlify deploy by using the crypto module directly
2025-04-07 12:19:02 +01:00
KevIsDev
b3d753dcc9 Merge pull request #1598 from mark-when/filetypes
fix: whitelist vue and svelte files
2025-04-06 22:45:02 +01:00
Stijnus
b54d160a3b feat: bulk delete chats from sidebar (#1586)
* feat: Bulk Delete Chats from Sidebar

feat(sidebar): Implement bulk chat deletion

Adds the ability for users to select multiple chats from the history sidebar and delete them in bulk.

**Key Changes:**

*   **Selection Mode:** Introduced a selection mode toggled by a dedicated button next to "Start new chat".
*   **Checkboxes:** Added checkboxes to each `HistoryItem` visible only when selection mode is active.
*   **Bulk Actions:** Added "Select All" / "Deselect All" and "Delete Selected" buttons (`Button` component with `ghost` variant) that appear above the chat list in selection mode.
*   **Confirmation Dialog:** Implemented a confirmation dialog (`Dialog` component) to prevent accidental deletion, listing the chats selected for removal.
*   **Deletion Logic:** Updated `Menu.client.tsx` to handle the selection state and perform bulk deletion using `deleteById` from persistence layer.
*   **Styling:** Ensured all new UI elements (`Checkbox`, `Button`) adhere to the existing project design system and support both light and dark themes using appropriate CSS classes and UnoCSS icons (`i-ph:` prefix).
*   **Refinement:** Replaced initial plain `<button>` elements with the project's `Button` component for consistency. Fixed incorrect icon prefixes.

* Fix selection and Dark mode
2025-04-06 20:36:53 +02:00
KevIsDev
03736df1ce Merge pull request #1577 from Derek-X-Wang/ci/electron-action-release-name
ci: only draft release for branch build
2025-04-05 23:33:01 +01:00
Rob Koch
ba9de84ac4 consolidate sync & export items into an overflow menu 2025-04-04 21:09:09 -07:00
Rob Koch
6942fba4a8 make diff button consistent with other toolbar buttonss 2025-04-04 19:15:18 -07:00
Rob Koch
be54fa0037 whitelist vue and svelte files 2025-04-04 05:54:34 -07:00
KevIsDev
33305c4326 feat(deploy): add deploy alert system for build and deployment status
Introduce a new `DeployAlert` interface and related components to provide visual feedback on build and deployment stages. This includes status updates for Vercel and Netlify deployments, with progress visualization and error handling. The changes enhance user experience by offering real-time updates during the deployment process.
2025-04-04 11:22:56 +01:00
KevIsDev
cdbf9ba730 refactor: update node polyfills and add buffer-polyfill plugin
Modify the node polyfills configuration to include additional modules and add a new buffer-polyfill plugin to handle Buffer imports in env.mjs files. This change ensures compatibility with required Node.js modules in the Vite environment.
2025-04-02 21:38:50 +01:00
KevIsDev
c63732d2f4 fix: simplify the SHA-1 hash function in api.netlify-deploy.ts by using the crypto module directly this allows it to work in both dev and prod environments.
also extract Netlify and Vercel deploy logic into separate components

Move the Netlify and Vercel deployment logic from HeaderActionButtons.client.tsx into dedicated components (NetlifyDeploy.client.tsx and VercelDeploy.client.tsx) to improve code maintainability and reusability.
2025-04-02 16:47:04 +01:00
KevIsDev
53a674dc58 Merge pull request #1559 from xKevIsDev/main
feat: add Vercel integration for project deployment
2025-03-31 10:36:37 +01:00
KevIsDev
7c18e7ddf6 Merge branch 'main' into main 2025-03-31 10:31:40 +01:00
Stijnus
61dd4aeaf5 fix: update stream-text.ts (#1582)
* Update stream-text.ts

* Update stream-text.ts
2025-03-30 17:39:00 +02:00
Derek Wang
fc0715d8d9 ci: fix tag name 2025-03-29 17:23:36 -07:00
Derek Wang
1fdb575c7e ci: fix logic, only draft for branch build 2025-03-29 17:08:33 -07:00
Derek Wang
2dc3961ae8 ci: name release and only draft for branch build 2025-03-29 16:31:42 -07:00
Stijnus
24ca7be11b feat: rework Task Manager Real Data (#1483)
* Update TaskManagerTab.tsx

* Rework Taskmanager

* bug fixes

* Update TaskManagerTab.tsx
2025-03-29 21:40:17 +01:00
Stijnus
0487ed1438 feat: new improvement for the GitHub API Authentication Fix (#1537)
* Add environment variables section to ConnectionsTab and fallback token to git-info

* Add remaining code from original branch

* Import Repo Fix

* refactor the UI

* add a rate limit counter

* Update GithubConnection.tsx

* Update NetlifyConnection.tsx

* fix: ui style

* Sync with upstream and preserve GitHub connection and DataTab fixes

* fix disconnect buttons

* revert commits

* Update api.git-proxy.$.ts

* Update api.git-proxy.$.ts
2025-03-29 21:12:47 +01:00
Stijnus
1c561a0615 feat: bolt dyi preview final (#1569)
* V1

## [Unreleased] - 2025-03-28

###  Fixed
- Fixed deployment errors on Cloudflare Pages caused by:
  - Missing or outdated `compatibility_date` and `compatibility_flags` in `wrangler.toml`
  - Use of Node.js built-ins (`crypto`, `stream`) in functions without proper polyfilling
  - Invalid Wrangler CLI options (`--log-level`) used during deployment
  - Type error when importing the Remix server build

### 🛠 Changed
- `wrangler.toml` updated:
  ```toml
  name = "bolt"
  compatibility_date = "2025-03-28"
  compatibility_flags = ["nodejs_compat"]
  pages_build_output_dir = "./build/client"
  send_metrics = false
  ```
- `functions/[[path]].ts` updated:
  ```ts
  import type { ServerBuild } from '@remix-run/cloudflare';
  import { createPagesFunctionHandler } from '@remix-run/cloudflare-pages';
  import * as serverBuild from '../build/server';

  export const onRequest = createPagesFunctionHandler({
    build: serverBuild as unknown as ServerBuild,
  });
  ```

### 🚀 Deployment
- Successful deployment to:
  - Preview: https://979e2ca9.bolt-55b.pages.dev
  - Production: https://main.bolt-55b.pages.dev

* V1

## [Unreleased] - 2025-03-28

###  Fixed
- Fixed deployment errors on Cloudflare Pages caused by:
  - Missing or outdated `compatibility_date` and `compatibility_flags` in `wrangler.toml`
  - Use of Node.js built-ins (`crypto`, `stream`) in functions without proper polyfilling
  - Invalid Wrangler CLI options (`--log-level`) used during deployment
  - Type error when importing the Remix server build

### 🛠 Changed
- `wrangler.toml` updated:
  ```toml
  name = "bolt"
  compatibility_date = "2025-03-28"
  compatibility_flags = ["nodejs_compat"]
  pages_build_output_dir = "./build/client"
  send_metrics = false
  ```
- `functions/[[path]].ts` updated:
  ```ts
  import type { ServerBuild } from '@remix-run/cloudflare';
  import { createPagesFunctionHandler } from '@remix-run/cloudflare-pages';
  import * as serverBuild from '../build/server';

  export const onRequest = createPagesFunctionHandler({
    build: serverBuild as unknown as ServerBuild,
  });
  ```

### 🚀 Deployment
- Successful deployment to:
  - Preview: https://979e2ca9.bolt-55b.pages.dev
  - Production: https://main.bolt-55b.pages.dev

* feat: small bugfix

* Update Preview.tsx
2025-03-29 20:57:41 +01:00
Stijnus
b86fd63700 feat: bolt dyi datatab (#1570)
* Update DataTab.tsx

## API Key Import Fix

We identified and fixed an issue with the API key import functionality in the DataTab component. The problem was that API keys were being stored in localStorage instead of cookies, and the key format was being incorrectly processed.

### Changes Made:

1. **Updated `handleImportAPIKeys` function**:
   - Changed to store API keys in cookies instead of localStorage
   - Modified to use provider names directly as keys (e.g., "OpenAI", "Google")
   - Added logic to skip comment fields (keys starting with "_")
   - Added page reload after successful import to apply changes immediately

2. **Updated `handleDownloadTemplate` function**:
   - Changed template format to use provider names as keys
   - Added explanatory comment in the template
   - Removed URL-related keys that weren't being used properly

3. **Fixed template format**:
   - Template now uses the correct format with provider names as keys
   - Added support for all available providers including Hyperbolic

These changes ensure that when users download the template, fill it with their API keys, and import it back, the keys are properly stored in cookies with the correct format that the application expects.

* backwards compatible old import template

* Update the export / import settings

Settings Export/Import Improvements
We've completely redesigned the settings export and import functionality to ensure all application settings are properly backed up and restored:
Key Improvements
Comprehensive Export Format: Now captures ALL settings from both localStorage and cookies, organized into logical categories (core, providers, features, UI, connections, debug, updates)
Robust Import System: Automatically detects format version and handles both new and legacy formats with detailed error handling
Complete Settings Coverage: Properly exports and imports settings from ALL tabs including:
Local provider configurations (Ollama, LMStudio, etc.)
Cloud provider API keys (OpenAI, Anthropic, etc.)
Feature toggles and preferences
UI configurations and tab settings
Connection settings (GitHub, Netlify)
Debug configurations and logs
Technical Details
Added version tracking to export files for better compatibility
Implemented fallback mechanisms if primary import methods fail
Added detailed logging for troubleshooting import/export issues
Created helper functions for safer data handling
Maintained backward compatibility with older export formats

Feature Settings:
Feature flags and viewed features
Developer mode settings
Energy saver mode configurations
User Preferences:
User profile information
Theme settings
Tab configurations
Connection Settings:
Netlify connections
Git authentication credentials
Any other service connections
Debug and System Settings:
Debug flags and acknowledged issues
Error logs and event logs
Update settings and preferences

* Update DataTab.tsx

* Update GithubConnection.tsx

revert the code back as asked

* feat: enhance style to match the project

* feat:small improvements

* feat: add major improvements

* Update Dialog.tsx

* Delete DataTab.tsx.bak

* feat: small updates

* Update DataVisualization.tsx

* feat: dark mode fix
2025-03-29 20:43:07 +01:00
Stijnus
47444970e8 feat: bugfix for : Problem Temporarily Solved, Not Fix: Error building my application #1414 (#1567)
* V1

## [Unreleased] - 2025-03-28

###  Fixed
- Fixed deployment errors on Cloudflare Pages caused by:
  - Missing or outdated `compatibility_date` and `compatibility_flags` in `wrangler.toml`
  - Use of Node.js built-ins (`crypto`, `stream`) in functions without proper polyfilling
  - Invalid Wrangler CLI options (`--log-level`) used during deployment
  - Type error when importing the Remix server build

### 🛠 Changed
- `wrangler.toml` updated:
  ```toml
  name = "bolt"
  compatibility_date = "2025-03-28"
  compatibility_flags = ["nodejs_compat"]
  pages_build_output_dir = "./build/client"
  send_metrics = false
  ```
- `functions/[[path]].ts` updated:
  ```ts
  import type { ServerBuild } from '@remix-run/cloudflare';
  import { createPagesFunctionHandler } from '@remix-run/cloudflare-pages';
  import * as serverBuild from '../build/server';

  export const onRequest = createPagesFunctionHandler({
    build: serverBuild as unknown as ServerBuild,
  });
  ```

### 🚀 Deployment
- Successful deployment to:
  - Preview: https://979e2ca9.bolt-55b.pages.dev
  - Production: https://main.bolt-55b.pages.dev

* V1

## [Unreleased] - 2025-03-28

###  Fixed
- Fixed deployment errors on Cloudflare Pages caused by:
  - Missing or outdated `compatibility_date` and `compatibility_flags` in `wrangler.toml`
  - Use of Node.js built-ins (`crypto`, `stream`) in functions without proper polyfilling
  - Invalid Wrangler CLI options (`--log-level`) used during deployment
  - Type error when importing the Remix server build

### 🛠 Changed
- `wrangler.toml` updated:
  ```toml
  name = "bolt"
  compatibility_date = "2025-03-28"
  compatibility_flags = ["nodejs_compat"]
  pages_build_output_dir = "./build/client"
  send_metrics = false
  ```
- `functions/[[path]].ts` updated:
  ```ts
  import type { ServerBuild } from '@remix-run/cloudflare';
  import { createPagesFunctionHandler } from '@remix-run/cloudflare-pages';
  import * as serverBuild from '../build/server';

  export const onRequest = createPagesFunctionHandler({
    build: serverBuild as unknown as ServerBuild,
  });
  ```

### 🚀 Deployment
- Successful deployment to:
  - Preview: https://979e2ca9.bolt-55b.pages.dev
  - Production: https://main.bolt-55b.pages.dev

* feat: small bugfix
2025-03-29 10:26:42 +01:00
KevIsDev
4b0eaf25ce add: add env masking extension for .env files
Introduce a new extension for CodeMirror that masks sensitive values in .env files. This ensures that sensitive information like API keys or passwords is not displayed in plain text within the editor. The extension dynamically applies masking to values in lines matching the KEY=VALUE format, improving security during development.
2025-03-27 18:52:13 +00:00
KevIsDev
95dcd0261a refactor: consolidate imports in supabase API routes
change over to cloudflare.
2025-03-27 16:24:12 +00:00
KevIsDev
687b03ba74 feat: add Vercel integration for project deployment
This commit introduces Vercel integration, enabling users to deploy projects directly to Vercel. It includes:
- New Vercel types and store for managing connections and stats.
- A VercelConnection component for managing Vercel account connections.
- A VercelDeploymentLink component for displaying deployment links.
- API routes for handling Vercel deployments.
- Updates to the HeaderActionButtons component to support Vercel deployment.

The integration allows users to connect their Vercel accounts, view project stats, and deploy projects with ease.
2025-03-27 00:06:10 +00:00
Leex
1364d4a503 feat: supabase integration #1542 from xKevIsDev/supabase
Merge pull request #1542 from xKevIsDev/supabase
2025-03-26 19:58:55 +01:00
KevIsDev
418fbf13e0 refactor: remove debug log and improve button layout in SupabaseConnection
Remove console.log statement for debugging purposes in the API route and enhance the layout of buttons in the SupabaseConnection component by grouping them and adding a refresh button
2025-03-25 13:54:15 +00:00
KevIsDev
fb55a24341 Merge pull request #1549 from Derek-X-Wang/ci/electron-action-permissions
ci: give electron action permission
2025-03-24 10:24:08 +00:00
Derek Wang
1660971cc3 ci: give electron action permission 2025-03-23 15:31:16 -07:00
KevIsDev
bc9948062e fix: add instruction to avoid generating types for supabase 2025-03-21 13:20:14 +00:00
KevIsDev
d53acdadda fix: ensure supabase credentials are populating the env file by default 2025-03-20 14:25:31 +00:00
KevIsDev
a109fc127f fix: ensure supabase credentials are persistent on reloads 2025-03-20 14:22:35 +00:00
KevIsDev
6a79bc6e5b fix: supabase button color to default 2025-03-20 12:32:10 +00:00
KevIsDev
c9c6f4e265 fix: add Supabase database instructions to optimized prompts
Include detailed guidelines for handling database operations using Supabase, covering setup, migrations, security, and best practices. This ensures consistent and secure database interactions in projects.
2025-03-20 11:21:18 +00:00
KevIsDev
bc7e2c5821 feat(supabase): add credentials handling for Supabase API keys and URL
This commit introduces the ability to fetch and store Supabase API keys and URL credentials when a project is selected. This enables the application to dynamically configure the Supabase connection environment variables, improving the integration with Supabase services. The changes include updates to the Supabase connection logic, new API endpoints, and modifications to the chat and prompt components to utilize the new credentials.
2025-03-20 11:17:27 +00:00
KevIsDev
02974089de feat: integrate Supabase for database operations and migrations
Add support for Supabase database operations, including migrations and queries. Implement new Supabase-related types, actions, and components to handle database interactions. Enhance the prompt system to include Supabase-specific instructions and constraints. Ensure data integrity and security by enforcing row-level security and proper migration practices.
2025-03-19 23:11:31 +00:00
KevIsDev
9fd5f149c9 Merge branch 'stackblitz-labs:main' into supabase 2025-03-19 22:20:00 +00:00
Derek Wang
1ce6ad6b59 feat: electron desktop app without express server (#1136)
* feat: add electron app

* refactor: using different approach

* chore: update commit hash to 02621e3545

* fix: working dev but prod showing not found and lint fix

* fix: add icon

* fix: resolve server file load issue

* fix: eslint and prettier wip

* fix: only load server build once

* fix: forward request for other ports

* fix: use cloudflare {} to avoid crash

* fix: no need for appLogger

* fix: forward cookie

* fix: update script and update preload loading path

* chore: minor update for appId

* fix: store and load all cookies

* refactor: split main/index.ts

* refactor: group electron main files into two folders

* fix: update electron build configs

* fix: update auto update feat

* fix: vite-plugin-node-polyfills need to be in dependencies for dmg version to work

* ci: trigger build for electron branch

* ci: mark draft if it's from branch commit

* ci: add icons for windows and linux

* fix: update icons for windows

* fix: add author in package.json

* ci: use softprops/action-gh-release@v2

* fix: use path to join

* refactor: refactor path logic for working in both mac and windows

* fix: still need vite-plugin-node-polyfills dependencies

* fix: update vite-electron.config.ts

* ci: sign mac app

* refactor: assets folder

* ci: notarization

* ci: add NODE_OPTIONS

* ci: window only nsis dist

---------

Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2025-03-20 00:22:06 +05:30
Leex
88901f3a37 docs: docs README.md changes (Webcontainer liicensing for commercial, other small things)
docs: docs README.md
2025-03-19 19:45:06 +01:00
Leex
64afda1078 Update README.md
Co-authored-by: patak <583075+patak-dev@users.noreply.github.com>
2025-03-18 11:40:49 +01:00
Leex
7107163f31 Update README.md 2025-03-18 10:54:39 +01:00
Stijnus
332edd3d98 fix: settings bugfix error building my application issue #1414 (#1436)
* Fix: error building my application #1414

* fix for vite

* Update vite.config.ts

* Update root.tsx

* fix the root.tsx and the debugtab

* lm studio fix and fix for the api key

* Update api.enhancer for prompt enhancement

* bugfixes

* Revert api.enhancer.ts back to original code

* Update api.enhancer.ts

* Update api.git-proxy.$.ts

* Update api.git-proxy.$.ts

* Update api.enhancer.ts
2025-03-11 02:19:39 +05:30
KevIsDev
4665fa67fa fix: remove excessive commenting 2025-03-10 11:20:01 +00:00
KevIsDev
f02e10c9ac fix: remove rename, creations and deletions now persist across reloads
removed rename files until a better solution is found and made file/folder create/delete be persistent across reloads
2025-03-10 11:12:25 +00:00
Leex
27fbfb76c4 Update README.md 2025-03-10 00:05:36 +01:00
Leex
a696d5f254 Update README.md 2025-03-09 23:44:23 +01:00
Leex
fc779b5b1f update: docs README.md
- changed git clone for pulling stable branch, not main anymore
- Removed some not needed stuff
2025-03-08 23:08:40 +01:00
Stijnus
50dd74de07 fix: settings bugfix error building my application issue #1414 (#1436)
* Fix: error building my application #1414

* fix for vite

* Update vite.config.ts

* Update root.tsx

* fix the root.tsx and the debugtab

* lm studio fix and fix for the api key

* Update api.enhancer for prompt enhancement

* bugfixes

* Revert api.enhancer.ts back to original code

* Update api.enhancer.ts

* Update api.git-proxy.$.ts

* Update api.git-proxy.$.ts

* Update api.enhancer.ts
2025-03-09 01:07:56 +05:30
Anirban Kar
7ff48e1d45 fix: attachment not getting sent on first message if starter template is turned on (#1472) 2025-03-08 12:44:46 +05:30
Anirban Kar
cd4a5e8380 fix: fix git proxy to work with other git provider (#1466) 2025-03-07 14:10:37 +05:30
Anirban Kar
9780393b17 fix: git cookies are auto set anytime connects changed or loaded (#1461) 2025-03-07 00:29:44 +05:30
Burhanuddin Khatri
20722a108c feat: add Claude 3.7 Sonnet model as static list and update API key reference (#1449) 2025-03-05 19:12:52 +05:30
Anirban Kar
1f940391b1 feat: restoring project from snapshot on reload (#444)
* feat:(project-snapshot) restoring project from snapshot on reload

* minor bugfix

* updated message

* added snapshot reload with auto run dev commands

* added message context

* snapshot updated
2025-03-05 10:59:48 +05:30
Anirban Kar
73a0f3ae24 fix: git clone modal to work with non main as default branch (#1428) 2025-03-05 04:23:01 +05:30
Anirban Kar
f9436d4929 ci: updated target for docker build (#1451) 2025-03-05 03:58:01 +05:30
Anirban Kar
55283065f5 Merge branch 'docker-fix' 2025-03-04 20:40:11 +05:30
Anirban Kar
2452f9413d ci: updated to have concise and parallel builds 2025-03-04 20:37:33 +05:30
Anirban Kar
9b2a204ddc ci: added arm64 build and tags build 2025-03-04 20:28:51 +05:30
KevIsDev
b079a56788 add: add file renaming and delete functionality 2025-03-03 16:14:31 +00:00
Anirban Kar
8d1f138224 Revert "Delete wrangler.toml"
This reverts commit 60b6f476d7.
2025-03-03 21:21:04 +05:30
Leex
2780b2ebe1 Delete .tool-versions 2025-03-03 15:57:41 +01:00
Leex
60b6f476d7 Delete wrangler.toml 2025-03-03 15:57:25 +01:00
KevIsDev
8c83c3c9aa feat: add creation of files and folders in the FileTree
- Drag and drop images directly in the file tree. Image will convert to base64 format
2025-03-03 12:16:13 +00:00
KevIsDev
964e1973fb fix: added a bunch more common languages to diff view
including: java, c, cpp, csharp, go ruby, rust
2025-03-03 09:39:16 +00:00
KevIsDev
b01874205e fix: support php language in diff view 2025-03-03 09:24:39 +00:00
Anirban Kar
4404f4a5c0 fix: git connection fix for starter template (#1411) 2025-03-02 12:58:13 +05:30
Anirban Kar
3368b7903e fix: OpenAILike api key not showing up (#1403) 2025-03-02 03:41:58 +05:30
bizrockman
8deee04a63 fix: handle empty content correctly in FilesStore saveFile() (#1381)
* Fix FilesStore: Handle empty content correctly in saveFile(). Happens when user creates files in the web terminal

* updated logic

---------

Co-authored-by: Anirban Kar <thecodacus@gmail.com>
2025-03-01 02:34:39 +05:30
github-actions[bot]
7045646b1a chore: release version 0.0.7 2025-02-28 20:13:16 +00:00
github-actions[bot]
b7c8677cb8 chore: release version 0.0.7 2025-02-28 20:13:14 +00:00
Anirban Kar
6c5d094ed7 ci: fixed bug with release notes on github release action (#1401) #release 2025-03-01 01:42:41 +05:30
Anirban Kar
3c28e8ad88 fix: fix enhance prompt to stop implementing full project instead of enhancing (#1383) #release
* fix: enhance prompt fix

* fix: added error capture on api error

* fix: replaced error with log for wrong files selected by bolt
2025-03-01 01:34:35 +05:30
Anirban Kar
b98485d99f feat: make user made changes persistent after reload (#1387)
* feat: save user made changes persistent

* fix: remove artifact from user message on the UI

* fix: message Id generation fix
2025-02-27 13:34:57 +05:30
Phr33d0m
a33a1268c3 Fix broken astro project git clone (#1352) 2025-02-26 22:24:40 +05:30
Anirban Kar
dc20bbc81f feat: added anthropic dynamic models (#1374) 2025-02-26 22:04:46 +05:30
KevIsDev
5d1816be9d Merge pull request #1367 from Toddyclipsgg/diff-view-v2
feat: diff view v3
2025-02-26 10:37:21 +00:00
Toddyclipsgg
a8d8b7b8c7 Merge branch 'main' into diff-view-v2 2025-02-25 19:29:59 -03:00
KevIsDev
5d9bb00ee2 Merge pull request #1376 from xKevIsDev/main
feat: netlify one click deployment
2025-02-25 22:12:10 +00:00
KevIsDev
23c22c5c12 fix: show netlify deployed link
netlify deploy button to be disabled on streaming and show link icon when deployed
2025-02-25 19:02:03 +00:00
KevIsDev
002f1bc5dc Merge branch 'stackblitz-labs:main' into main 2025-02-25 15:07:08 +00:00
KevIsDev
19137c934b add: various improvements to connections
- improved organisation of connections (collapsibles)
- improved deploy button
- improved unique chat deployments
2025-02-25 00:41:44 +00:00
KevIsDev
96a0b2a066 add: connection improvements
Improve connections visually and functionality
2025-02-25 00:39:39 +00:00
Toddyclipsgg
1098188427 feat: Improve DiffView theme and color consistency
- Added dark/light theme support for syntax highlighting
- Enhanced color styles for added/removed lines and characters
- Integrated theme store to dynamically adjust syntax highlighter theme
- Refined color contrast for better readability across themes
2025-02-24 20:06:15 -03:00
Leex
67c4051f82 Update docker.yaml 2025-02-24 23:27:42 +01:00
Leex
eb4aa68581 Update docker.yaml 2025-02-24 23:27:33 +01:00
KevIsDev
4da13d1edc feat: add netlify one-click deployment 2025-02-24 17:24:32 +00:00
KevIsDev
2a8472ed17 feat: add one-click netlify deployment 2025-02-24 17:24:00 +00:00
Toddyclipsgg
afb82e2cf9 chore: Remove unnecessary history directory creation in GitHub Actions 2025-02-23 20:46:18 -03:00
Toddyclipsgg
056a446f0f chore: Remove unused dependencies and clean up imports
- Removed lucide-react and next-themes from package dependencies
- Simplified import in workbench store for path and file-saver
- Removed unnecessary module definition in Vite config
2025-02-23 20:00:17 -03:00
Toddyclipsgg
36872ee6a0 refactor: Enhance Diff View with advanced line and character-level change detection
- Improved diff algorithm to detect more granular line and character-level changes
- Added support for character-level highlighting in diff view
- Simplified diff view mode by removing side-by-side option
- Updated component rendering to support more detailed change visualization
- Optimized line change detection with improved matching strategy
2025-02-23 19:34:27 -03:00
Leex
7dda7938d4 Update docker.yaml 2025-02-23 22:52:23 +01:00
Leex
73710da501 Update docker.yaml 2025-02-23 22:52:09 +01:00
Leex
a87eae2119 Update Dockerfile (fix docker deployment) 2025-02-23 22:37:38 +01:00
Leex
52970812cb Update Dockerfile 2025-02-23 22:28:24 +01:00
Leex
8e790d08e2 Update Dockerfile - Test Bugfix Dockerpipeline
the npm install -g corepack@latest is supposed to make problems with the main docker build
2025-02-23 22:21:55 +01:00
Leex
f0ea22ec63 Update docker.yaml (stable/main deployment)
Exteneded the workflow/action to also deploy a stable release container
2025-02-23 18:45:56 +01:00
Toddyclipsgg
b3ec53fa42 Merge branch 'stackblitz-labs:main' into diff-view-v2 2025-02-23 07:56:06 -03:00
Toddyclipsgg
ab6f5328b4 feat: Add Diff View and File History Tracking
- Implemented a new Diff View in the Workbench to visualize file changes
- Added file history tracking with detailed change information
- Enhanced FileTree and FileModifiedDropdown to show line additions and deletions
- Integrated file history saving and retrieval in ActionRunner
- Updated Workbench view types to include 'diff' option
- Added support for inline and side-by-side diff view modes
2025-02-23 07:55:38 -03:00
KevIsDev
bffb8a2a90 Revert "Merge pull request #1335 from Toddyclipsgg/diff-view-v2"
This reverts commit 871aefbe83, reversing
changes made to 8c72ed76b3.
2025-02-21 15:01:09 +00:00
KevIsDev
871aefbe83 Merge pull request #1335 from Toddyclipsgg/diff-view-v2
feat: diff-view-v2-no-conflict
2025-02-21 14:39:55 +00:00
Stijnus
8c72ed76b3 Merge pull request #1356 from Stijnus/ACT_BoltDYI_UI_BUGFIX
fix: for remove settings icon _index.tsx
2025-02-21 10:34:25 +01:00
Toddyclipsgg
c24e69718e Merge branch 'main' into diff-view-v2 2025-02-21 00:37:50 -03:00
Stijnus
aa02448516 Update _index.tsx
Removed the settings button in the landingpage.
2025-02-20 13:03:59 +01:00
KevIsDev
220e2da7ec fix: preserve complete provider settings in cookies
Previously only the enabled state was being saved to cookies, causing loss of provider configuration like baseURL.
2025-02-20 03:27:15 +00:00
Stijnus
097dffdd78 Merge pull request #1342 from Stijnus/ACT_FEAT_BoltDYI_UI_BUGFIX
fix: bolt dyi UI bugfix
2025-02-18 21:55:50 +01:00
Stijnus
ca7f5ad26b update local models 2025-02-18 21:51:02 +01:00
Stijnus
10af7c9835 Default settings feature tab 2025-02-18 17:50:01 +01:00
Stijnus
7f3b5f6628 Merge branch 'main' into ACT_FEAT_BoltDYI_UI_BUGFIX 2025-02-18 16:30:36 +01:00
Stijnus
0e60d9cca8 UI bug fixes 2025-02-18 14:13:13 +01:00
KevIsDev
0e2e1834e7 Merge pull request #1322 from kamilfurtak/model-search
feat: implement llm model search
2025-02-18 03:47:47 +00:00
Leex
0fd039bdb3 update: new anthropogenic model for amazon bedrock
feat: New Claude 3.5 Sonnet v2 Anthropogenic Model for amazon bedrock
2025-02-17 23:23:23 +01:00
Toddyclipsgg
382bf2c9a3 feat: Add Diff View and File History Tracking
- Implemented a new Diff view in the Workbench to track file changes
- Added file history tracking with version control and change tracking
- Created a FileModifiedDropdown to browse and manage modified files
- Enhanced ActionRunner to support file history persistence
- Updated Workbench and BaseChat components to support new diff view functionality
- Added support for inline and side-by-side diff view modes
2025-02-16 23:10:15 -03:00
KevIsDev
70b723d514 fix: debounce profile update notifications to prevent toast spam
a new toast was being triggered for every character input.
2025-02-17 01:49:33 +00:00
Toddyclipsgg
744b6c2433 Merge branch 'stackblitz-labs:main' into main 2025-02-16 21:28:20 -03:00
Stijnus
6e89710ec7 Several UI fixes 2025-02-15 17:28:17 +01:00
Kamil Furtak
e717d25191 Add click outside handler to close ModelSelector dropdown 2025-02-15 16:59:58 +01:00
Kamil Furtak
2056625cbd Enhance accessibility for ModelSelector dropdown
Added keyboard support for toggling the dropdown using Enter or Space keys, improving accessibility. Also set appropriate focus properties by adding tabindex to the combobox element.
2025-02-15 16:55:55 +01:00
Kamil Furtak
f94be5b383 remove transparency 2025-02-15 16:50:15 +01:00
Kamil Furtak
a3a06d03ba fix truncation 2025-02-15 16:42:40 +01:00
Kamil Furtak
95de84c41a add whitespace-nowrap 2025-02-15 16:15:36 +01:00
Kamil Furtak
0f6bfca9bc remove truncate 2025-02-15 16:07:33 +01:00
Kamil Furtak
24bf34c683 fix: Size of dropdowns should be always the same and not break into 2 lines 2025-02-15 15:59:37 +01:00
Stijnus
db5f30e1ee Update settings.ts 2025-02-15 15:12:08 +01:00
Kamil Furtak
cb58db3bf0 fix ui add keyboard events 2025-02-15 13:51:11 +01:00
Kamil Furtak
d56708966a fix srollbar 2025-02-15 13:45:26 +01:00
Kamil Furtak
b25db9b27e add model search 2025-02-15 13:37:35 +01:00
Leex
294adfdd1b fix: bug fix New UI / Feature tab - Default values hard-coded
It was not possible to change "Context Optimization" and "Prompt Library".
2025-02-15 09:57:22 +01:00
Stijnus
823c66e05c Update pnpm-lock.yaml 2025-02-15 00:26:00 +01:00
Stijnus
79ea72ad74 Update FeaturesTab.tsx
Bug fix : Preserve Settings FeatureTab
2025-02-15 00:24:25 +01:00
Filipe Giácomo
4b817ebdce Update amazon-bedrock.ts
New Claude 3.5 Sonnet v2 Anthropogenic Model
2025-02-12 11:39:37 -03:00
Anirban Kar
a0ea69fd74 fix: auto scroll fix, scroll allow user to scroll up during ai response (#1299) 2025-02-12 01:11:14 +05:30
Anirban Kar
2fe1f1d443 fix: starter template icons fix and auto resize of custon icons are reverted (#1298)
* fix: starter template icons fix and auto resize of custon icons are reverted

* fix: slidev icon revert
2025-02-12 01:08:28 +05:30
BaptisteCDC
c88938cffc ci: updated Dockerfile to install latest version of corepack to ensure to have the right version to pnpm 2025-02-11 19:45:41 +05:30
Cole Medin
fbf1d46106 Merge pull request #1245 from Stijnus/FEAT_BoltDYI_NEW_SETTINGS_UI_V3
feat: bolt dyi new settings UI V3
2025-02-10 15:44:25 -06:00
Toddyclipsgg
6412e58b35 Delete .tool-versions 2025-02-09 18:28:14 -03:00
Toddyclipsgg
5ef7bdc42e Delete wrangler.toml 2025-02-09 18:27:29 -03:00
Leex
6a8449e6aa fix: removed chrome canary note
canary is not needed anymore.
2025-02-09 19:19:06 +01:00
Stijnus
ba582536e4 Merge branch 'stackblitz-labs:main' into FEAT_BoltDYI_NEW_SETTINGS_UI_V3 2025-02-07 17:29:05 +01:00
Stijnus
b5096735ef Update fix
more enhanced  UI and more details what is fixed,  ect
2025-02-03 01:40:54 +01:00
Stijnus
f091409f7e Avatar Fix , control pannel UI fix 2025-02-03 01:04:23 +01:00
Stijnus
f3468d495d Update AvatarDropdown.tsx 2025-02-02 23:50:15 +01:00
Stijnus
23d253e7f8 fixes as fequestd 2025-02-02 18:52:17 +01:00
Stijnus
07435fc255 update fixes BETA 2025-02-02 17:06:37 +01:00
Stijnus
d479550c49 Update api.update.ts 2025-02-02 16:58:41 +01:00
Stijnus
ee67bf1e29 Update UpdateTab.tsx 2025-02-02 16:55:12 +01:00
Stijnus
c200e2f74d update fixes 2025-02-02 16:50:43 +01:00
Stijnus
f50ebc6ea7 Update api.update.ts 2025-02-02 16:42:36 +01:00
Stijnus
3dd3fafb77 Update api.update.ts 2025-02-02 16:25:22 +01:00
Stijnus
9171cf48aa bug fix and some icons changes 2025-02-02 16:17:33 +01:00
Stijnus
8035a76429 Bug fix for the Keyboard Shortcuts
MAC OS SHORTCUTS:
- Toggle Terminal: ⌘ + `
- Toggle Theme: ⌘ + ⌥ + ⇧ + D
- Toggle Chat: ⌘ + ⌥ + J
- Toggle Settings: ⌘ + ⌥ + S

WINDOWS/LINUX SHORTCUTS:
- Toggle Terminal: Ctrl + `
- Toggle Theme: Win + Alt + Shift + D
- Toggle Chat: Ctrl + Alt + J
- Toggle Settings: Ctrl + Alt + S
2025-02-02 15:51:56 +01:00
Stijnus
84f45dd041 Add support for export JSON, CSV, PDF, Text
## Changes to DebugTab.tsx & EventLogsTab.tsx

### Debug Tab Enhancements
- Added multi-page support for PDF exports
- Implemented proper page breaks and content flow
- Added styled headers, key-value pairs, and horizontal lines
- Added title and timestamp at the top of the PDF
- Improved PDF layout with sections for system info, web app info, and performance metrics
- Added footer with page numbers
- Fixed memory usage calculations with proper null checks
- Added error handling for undefined values

### Event Logs Tab Enhancements
- Added comprehensive PDF export functionality with:
  - Professional header with bolt.diy branding
  - Report summary section
  - Log statistics with color-coded categories
  - Detailed log entries with proper formatting
  - Multi-page support with proper page breaks
  - Footer with page numbers and timestamp
- Added multiple export formats (JSON, CSV, PDF, Text)
- Fixed linter errors and improved type safety
- Enhanced dark mode compatibility
2025-02-02 13:25:04 +01:00
Stijnus
fc3dd8c84c Final UI V3
# UI V3 Changelog

Major updates and improvements in this release:

## Core Changes
- Complete NEW REWRITTEN UI system overhaul (V3) with semantic design tokens
- New settings management system with drag-and-drop capabilities
- Enhanced provider system supporting multiple AI services
- Improved theme system with better dark mode support
- New component library with consistent design patterns

## Technical Updates
- Reorganized project architecture for better maintainability
- Performance optimizations and bundle size improvements
- Enhanced security features and access controls
- Improved developer experience with better tooling
- Comprehensive testing infrastructure

## New Features
- Background rays effect for improved visual feedback
- Advanced tab management system
- Automatic and manual update support
- Enhanced error handling and visualization
- Improved accessibility across all components

For detailed information about all changes and improvements, please see the full changelog.
2025-02-02 01:42:30 +01:00
Stijnus
999d87b1e8 beta New control panel
# Tab Management System Implementation

## What's Been Implemented
1. Complete Tab Management System with:
   - Drag and drop functionality for reordering tabs
   - Visual feedback during drag operations
   - Smooth animations and transitions
   - Dark mode support
   - Search functionality for tabs
   - Reset to defaults option

2. Developer Mode Features:
   - Shows ALL available tabs in developer mode
   - Maintains tab order across modes
   - Proper visibility toggles
   - Automatic inclusion of developer-specific tabs

3. User Mode Features:
   - Shows only user-configured tabs
   - Maintains separate tab configurations
   - Proper visibility management

## Key Components
- `TabManagement.tsx`: Main management interface
- `ControlPanel.tsx`: Main panel with tab display
- Integration with tab configuration store
- Proper type definitions and interfaces

## Technical Features
- React DnD for drag and drop
- Framer Motion for animations
- TypeScript for type safety
- UnoCSS for styling
- Toast notifications for user feedback

## Next Steps
1. Testing:
   - Test tab visibility in both modes
   - Verify drag and drop persistence
   - Check dark mode compatibility
   - Verify search functionality
   - Test reset functionality

2. Potential Improvements:
   - Add tab grouping functionality
   - Implement tab pinning
   - Add keyboard shortcuts
   - Improve accessibility
   - Add tab descriptions
   - Add tab icons customization

3. Documentation:
   - Add inline code comments
   - Create user documentation
   - Document API interfaces
   - Add setup instructions

4. Future Features:
   - Tab export/import
   - Custom tab creation
   - Tab templates
   - User preferences sync
   - Tab statistics

## Known Issues to Address
1. Ensure all tabs are visible in developer mode
2. Improve drag and drop performance
3. Better state persistence
4. Enhanced error handling
5. Improved type safety

## Usage Instructions
1. Switch to developer mode to see all available tabs
2. Use drag and drop to reorder tabs
3. Toggle visibility using switches
4. Use search to filter tabs
5. Reset to defaults if needed

## Technical Debt
1. Refactor tab configuration store
2. Improve type definitions
3. Add proper error boundaries
4. Implement proper loading states
5. Add comprehensive testing

## Security Considerations
1. Validate tab configurations
2. Sanitize user input
3. Implement proper access control
4. Add audit logging
5. Secure state management
2025-02-01 18:01:34 +01:00
Anirban Kar
3be18e3f9d feat: added dynamic model support for openAI provider (#1241) 2025-02-01 15:29:54 +05:30
Stijnus
af620d0197 Bug Fixes part1 2025-01-31 12:55:52 +01:00
Stijnus
5791dafcd1 Update uno.config.ts 2025-01-30 23:57:57 +01:00
Stijnus
ec1bcb8aaa Merge branch 'stackblitz-labs:main' into FEAT_BoltDYI_NEW_SETTINGS_UI_V2 2025-01-30 23:43:27 +01:00
Stijnus
73bc81c830 Update constants.ts 2025-01-30 23:40:53 +01:00
Stijnus
cf909431f2 test 2025-01-30 23:28:21 +01:00
Stijnus
2c991e42da revert 2025-01-30 23:05:04 +01:00
Stijnus
1eae44dd14 fix landingpage icons 2025-01-30 22:50:42 +01:00
Stijnus
fab0cdd04e fix icons landingpage 2025-01-30 22:11:07 +01:00
Stijnus
0c6f36302e Taskmanager update
Enhanced System Metrics:
Detailed CPU metrics including temperature and frequency
Comprehensive memory breakdown with heap usage
Advanced performance metrics (FPS, page load times, web vitals)
Detailed network statistics
Storage monitoring with visual indicators
Battery health and detailed status
Power Management:
Multiple power profiles (Performance, Balanced, Power Saver)
Enhanced energy saver mode
Automatic power management based on system state
Detailed energy savings statistics
System Health:
Overall system health score
Real-time issue detection and alerts
Performance optimization suggestions
Historical metrics tracking
UI Improvements:
Interactive graphs for all metrics
Color-coded status indicators
Detailed tooltips and explanations
Collapsible sections for better organization
Alert system for critical events
Performance Monitoring:
Frame rate monitoring
Resource usage tracking
Network performance analysis
Web vitals monitoring
Detailed timing metrics
To use the enhanced task manager:
Monitor system health in the new health score section
Choose a power profile based on your needs
Enable auto energy saver for automatic power management
Monitor real-time alerts for system issues
5. View detailed metrics in each category
Check optimization suggestions when performance issues arise
2025-01-30 21:08:23 +01:00
Stijnus
d1d23d80e7 big fixes
fixes feedback from thecodacus
2025-01-30 17:17:36 +01:00
Stijnus
d9a380f28a Service console check providers 2025-01-30 01:58:47 +01:00
Anirban Kar
137e268943 fix: tune the system prompt to avoid diff writing (#1218) 2025-01-30 01:22:29 +05:30
Anirban Kar
f5fbf421e9 fix: issue with alternate message when importing from folder and git (#1216) 2025-01-29 22:16:58 +05:30
Stijnus
9e8d05cb54 Merge branch 'FEAT_BoltDYI_CHAT_FIX' into FEAT_BoltDYI_NEW_SETTINGS_UI_V2 2025-01-29 17:29:18 +01:00
Stijnus
547cde78c0 Merge branch 'stackblitz-labs:main' into FEAT_BoltDYI_NEW_SETTINGS_UI_V2 2025-01-29 14:37:07 +01:00
Stijnus
d966656070 Merge branch 'stackblitz-labs:main' into FEAT_BoltDYI_CHAT_FIX 2025-01-29 13:37:56 +01:00
Anirban Kar
7016111906 feat: enhanced Code Context and Project Summary Features (#1191)
* fix: docker prod env variable fix

* lint and typecheck

* removed hardcoded tag

* better summary generation

* improved  summary generation for context optimization

* remove think tags from the generation
2025-01-29 15:37:20 +05:30
Stijnus
89a38603d5 Update Messages.client.tsx
Fix for chat response auto scroll :

### Benefits
- More reliable auto-scrolling during streaming
- Better handling of user scroll interactions
- Improved mobile device support
- Smoother initial load with instant scroll
- Cleaner code organization and maintainability

### Testing
The changes can be verified by:
1. Loading chat - should instantly scroll to bottom
2. Streaming messages - should smoothly auto-scroll
3. Manual scroll up - should stay at user's position
4. Scroll to bottom - should resume auto-scroll
5. Mobile testing - should work with touch interactions
2025-01-29 01:17:54 +01:00
Stijnus
24688c3104 Update TaskManagerTab.tsx 2025-01-29 00:02:46 +01:00
Stijnus
3c8b9d107b Merge branch 'stackblitz-labs:main' into FEAT_BoltDYI_NEW_SETTINGS_UI_V2 2025-01-28 23:00:04 +01:00
Stijnus
0765bc3173 add install ollama models , fixes 2025-01-28 22:57:06 +01:00
Anirban Kar
a199295ad8 feat: support for <think></think> tags to allow reasoning tokens formatted in UI (#1205) 2025-01-29 02:33:53 +05:30
Anirban Kar
32bfdd9c24 feat: added more dynamic models, sorted and remove duplicate models (#1206) 2025-01-29 02:33:23 +05:30
Mohammad Saif Khan
39a0724ef3 feat: add Gemini 2.0 Flash-thinking-exp-01-21 model with 65k token support (#1202)
Added the new gemini-2.0-flash-thinking-exp-01-21 model to the GoogleProvider's static model configuration. This model supports a significantly increased maxTokenAllowed limit of 65,536 tokens, enabling it to handle larger context windows compared to existing Gemini models (previously capped at 8k tokens). The model is labeled as "Gemini 2.0 Flash-thinking-exp-01-21" for clear identification in the UI/dropdowns.
2025-01-28 23:30:50 +05:30
Stijnus
f32016c91d Github enhancement 2025-01-28 13:21:24 +01:00
Stijnus
387516b7fd fix 2025-01-28 11:41:33 +01:00
Stijnus
c4c73622f5 Fix ESLint issues 2025-01-28 11:39:12 +01:00
Stijnus
58d3853cd6 Merge branch 'main' into FEAT_BoltDYI_NEW_SETTINGS_UI_V2 2025-01-28 10:38:06 +01:00
Stijnus
0db9ce2717 Revert "Major UI improvements"
This reverts commit 6e52114172.
2025-01-28 10:28:45 +01:00
Stijnus
6e52114172 Major UI improvements 2025-01-28 01:33:19 +01:00
Mohammad Saif Khan
68bbbd0a67 feat: add deepseek-r1-distill-llama-70b to groq provider (#1187)
This PR introduces a new model, deepseek-r1-distill-llama-70b, to the staticModels array and ensures compatibility with the Groq API. The changes include:

Adding the deepseek-r1-distill-llama-70b model to the staticModels array with its relevant metadata.

Updating the Groq API call to use the new model for chat completions.

These changes enable the application to support the deepseek-r1-distill-llama-70b model, expanding the range of available models for users.
2025-01-27 18:08:46 +05:30
Anirban Kar
bbae032a37 fix: git import issue when importing bolt on bolt (#1020)
* fix: import bolt on bolt fix

* added escape on folder import

* type fix
2025-01-27 18:05:55 +05:30
Anirban Kar
6d4196a2b4 fix: improve push to github option (#1111)
* feat: better push to githubbutton

* added url update on push to github
2025-01-27 17:58:25 +05:30
Anirban Kar
df766c98d4 feat: added support for reasoning content (#1168) 2025-01-25 16:16:19 +05:30
Anirban Kar
660353360f fix: docker prod env variable fix (#1170)
* fix: docker prod env variable fix

* lint and typecheck

* removed hardcoded tag
2025-01-25 03:52:26 +05:30
Stijnus
afb1e44187 Update ConnectionsTab.tsx 2025-01-24 17:05:27 +01:00
Stijnus
b0fe1fc871 update 2025-01-24 16:51:43 +01:00
Stijnus
7378d7598b Update DebugTab.tsx 2025-01-24 16:16:05 +01:00
Stijnus
027f6529f2 UI Enhancements 2025-01-24 16:14:48 +01:00
Stijnus
505f1db071 Connection improvements 2025-01-24 01:23:17 +01:00
Stijnus
56783ae45a Merge branch 'main' into FEAT_BoltDYI_NEW_SETTINGS_UI 2025-01-24 01:17:34 +01:00
Stijnus
2ba230cafa Delete app/components/settings/CHANGELOG.md 2025-01-24 01:15:40 +01:00
Stijnus
c1f4f2feb6 Update ConnectionsTab.tsx 2025-01-24 01:13:05 +01:00
Stijnus
27eab591a9 UI fixes 2025-01-24 01:08:51 +01:00
Stijnus
4e6f18ea1e Update ConnectionsTab.tsx 2025-01-23 17:49:22 +01:00
Stijnus
fd98059cfe connection github enhancements 2025-01-23 16:02:50 +01:00
github-actions[bot]
ecf3cad189 chore: release version 0.0.6 2025-01-22 20:54:03 +00:00
github-actions[bot]
5a0489f3c3 chore: release version 0.0.6 2025-01-22 20:54:02 +00:00
Anirban Kar
3c56346e83 feat: enhance context handling by adding code context selection and implementing summary generation (#1091) #release
* feat: add context annotation types and enhance file handling in LLM processing

* feat: enhance context handling by adding chatId to annotations and implementing summary generation

* removed useless changes

* feat: updated token counts to include optimization requests

* prompt fix

* logging added

* useless logs removed
2025-01-22 22:48:13 +05:30
Stijnus
5a6c0e5f90 Update .gitignore 2025-01-22 15:26:32 +01:00
Stijnus
b99ab7ad27 final UI fixes 2025-01-22 15:25:55 +01:00
Stijnus
308f36316a Update UpdateTab.tsx 2025-01-22 14:54:11 +01:00
Stijnus
a286e3bf34 ui fix 2025-01-22 14:47:58 +01:00
Stijnus
2b585c24fe ui dark mode enhancements 2025-01-22 14:34:30 +01:00
Leex
2ae897aae7 fix: get environment variables for docker #1120
fix: get environment variables for docker
2025-01-22 13:01:10 +01:00
Stijnus
723c6a4f02 fixes 2025-01-22 02:05:18 +01:00
Anirban Kar
46f15bdde6 fix: updated system prompt to have correct indentations (#1139)
* updated system prompt to have correct indentations

* removed a section
2025-01-22 01:59:07 +05:30
Anirban Kar
0ad4aa56d3 feat: added deepseek reasoner model in deepseek provider (#1151) 2025-01-22 01:58:31 +05:30
Anirban Kar
f29380e147 fix: auto select starter template bugfix (#1148) 2025-01-22 00:30:31 +05:30
Stijnus
a94330e4a4 fixes 2025-01-21 16:45:54 +01:00
Stijnus
6d98affc3d Add new features
Bolt DIY UI

## New User Interface Features

### 🎨 Redesigned Control Panel

The Bolt DIY interface has been completely redesigned with a modern, intuitive layout featuring two main components:

1. **Users Window** - Main control panel for regular users
2. **Developer Window** - Advanced settings and debugging tools

### 💡 Core Features

- **Drag & Drop Tab Management**: Customize tab order in both User and Developer windows
- **Dynamic Status Updates**: Real-time status indicators for updates, notifications, and system health
- **Responsive Design**: Beautiful transitions and animations using Framer Motion
- **Dark/Light Mode Support**: Full theme support with consistent styling
- **Improved Accessibility**: Using Radix UI primitives for better accessibility
- **Enhanced Provider Management**: Split view for local and cloud providers
- **Resource Monitoring**: New Task Manager for system performance tracking

### 🎯 Tab Overview

#### User Window Tabs

1. **Profile**

   - Manage user profile and account settings
   - Avatar customization
   - Account preferences

2. **Settings**

   - Configure application preferences
   - Customize UI behavior
   - Manage general settings

3. **Notifications**

   - Real-time notification center
   - Unread notification tracking
   - Notification preferences

4. **Features**

   - Explore new and upcoming features
   - Feature preview toggles
   - Early access options

5. **Data**

   - Data management tools
   - Storage settings
   - Backup and restore options

6. **Cloud Providers**

   - Configure cloud-based AI providers
   - API key management
   - Cloud model selection
   - Provider-specific settings
   - Status monitoring for each provider

7. **Local Providers**

   - Manage local AI models
   - Ollama integration and model updates
   - LM Studio configuration
   - Local inference settings
   - Model download and updates

8. **Task Manager**

   - System resource monitoring
   - Process management
   - Performance metrics
   - Resource usage graphs
   - Alert configurations

9. **Connection**

   - Network status monitoring
   - Connection health metrics
   - Troubleshooting tools
   - Latency tracking
   - Auto-reconnect settings

10. **Debug**

- System diagnostics
- Performance monitoring
- Error tracking
- Provider status checks
- System information

11. **Event Logs**

- Comprehensive system logs
- Filtered log views
- Log management tools
- Error tracking
- Performance metrics

12. **Update**
    - Version management
    - Update notifications
    - Release notes
    - Auto-update configuration

#### Developer Window Enhancements

- **Advanced Tab Management**

  - Fine-grained control over tab visibility
  - Custom tab ordering
  - Tab permission management
  - Category-based organization

- **Developer Tools**
  - Enhanced debugging capabilities
  - System metrics and monitoring
  - Performance optimization tools
  - Advanced logging features

### 🚀 UI Improvements

1. **Enhanced Navigation**

   - Intuitive back navigation
   - Breadcrumb-style header
   - Context-aware menu system
   - Improved tab organization

2. **Status Indicators**

   - Dynamic update badges
   - Real-time connection status
   - System health monitoring
   - Provider status tracking

3. **Profile Integration**

   - Quick access profile menu
   - Avatar support
   - Fast settings access
   - Personalization options

4. **Accessibility Features**
   - Keyboard navigation
   - Screen reader support
   - Focus management
   - ARIA attributes

### 🛠 Technical Enhancements

- **State Management**

  - Nano Stores for efficient state handling
  - Persistent settings storage
  - Real-time state synchronization
  - Provider state management

- **Performance Optimizations**

  - Lazy loading of tab contents
  - Efficient DOM updates
  - Optimized animations
  - Resource monitoring

- **Developer Experience**
  - Improved error handling
  - Better debugging tools
  - Enhanced logging system
  - Performance profiling

### 🎯 Future Roadmap

- [ ] Additional customization options
- [ ] Enhanced theme support
- [ ] More developer tools
- [ ] Extended API integrations
- [ ] Advanced monitoring capabilities
- [ ] Custom provider plugins
- [ ] Enhanced resource management
- [ ] Advanced debugging features

## 🔧 Technical Details

### Dependencies

- Radix UI for accessible components
- Framer Motion for animations
- React DnD for drag and drop
- Nano Stores for state management

### Browser Support

- Modern browsers (Chrome, Firefox, Safari, Edge)
- Progressive enhancement for older browsers

### Performance

- Optimized bundle size
- Efficient state updates
- Minimal re-renders
- Resource-aware operations

## 📝 Contributing

We welcome contributions! Please see our contributing guidelines for more information.

## 📄 License

MIT License - see LICENSE for details
2025-01-21 15:18:17 +01:00
Stijnus
293fdb7377 Create changelogUI.md 2025-01-21 12:22:12 +01:00
Stijnus
afc26dd96a Update changelog.md 2025-01-21 12:20:29 +01:00
Stijnus
8c89aa61c4 Update changelog.md 2025-01-21 12:17:31 +01:00
Stijnus
78d4e1bb54 ui fix 2025-01-21 11:55:26 +01:00
Stijnus
436a8e54bf ui refactor 2025-01-20 09:53:15 +01:00
Leex
d62e211d09 Merge pull request #1122 from Stijnus/FEAT_BoltDYI_PREVIEW_V3
fix: for Open preview in a new tab.
2025-01-19 00:17:13 +01:00
Leex
031e679aff Merge branch 'main' into FEAT_BoltDYI_PREVIEW_V3 2025-01-19 00:14:09 +01:00
Leex
6ae1ac25d2 Merge pull request #1094 from lewis617/patch-1
docs: replace docker-compose with docker compose
2025-01-19 00:11:39 +01:00
Leex
b842e0c920 Merge pull request #1124 from stackblitz-labs/leex279-patch-readme-changes-v1
docs: update README.md
2025-01-18 23:41:05 +01:00
Stijnus
48f4999f32 Update Preview.tsx 2025-01-18 21:45:29 +01:00
Stijnus
b732f20233 bug fix for Open preview in a new tab. 2025-01-18 19:25:01 +01:00
Ken Jenney
7341b1292b Get environment variables from .env.local
Environment variables are not being passed to the container in the development profile. Adding env_file to pass them so they can be used by the application.
2025-01-18 12:38:34 -05:00
Stijnus
9230ef3b55 Merge branch 'stackblitz-labs:main' into FEAT_BoltDYI_NEW_SETTINGS_UI 2025-01-18 13:49:03 +01:00
Stijnus
8f3f37ae7e fix 2025-01-17 19:55:07 +01:00
Stijnus
f33ba635e8 V1 : Release of the new Settings Dashboard
# 🚀 Release v1.0.0

## What's Changed 🌟

### 🎨 UI/UX Improvements
- **Dark Mode Support**
  - Implemented comprehensive dark theme across all components
  - Enhanced contrast and readability in dark mode
  - Added smooth theme transitions
  - Optimized dialog overlays and backdrops

### 🛠️ Settings Panel
- **Data Management**
  - Added chat history export/import functionality
  - Implemented settings backup and restore
  - Added secure data deletion with confirmations
  - Added profile customization options

- **Provider Management**
  - Added comprehensive provider configuration
  - Implemented URL-configurable providers
  - Added local model support (Ollama, LMStudio)
  - Added provider health checks
  - Added provider status indicators

- **Ollama Integration**
  - Added Ollama Model Manager with real-time updates
  - Implemented model version tracking
  - Added bulk update capability
  - Added progress tracking for model updates
  - Displays model details (parameter size, quantization)

- **GitHub Integration**
  - Added GitHub connection management
  - Implemented secure token storage
  - Added connection state persistence
  - Real-time connection status updates
  - Proper error handling and user feedback

### 📊 Event Logging
- **System Monitoring**
  - Added real-time event logging system
  - Implemented log filtering by type (info, warning, error, debug)
  - Added log export functionality
  - Added auto-scroll and search capabilities
  - Enhanced log visualization with color coding

### 💫 Animations & Interactions
- Added smooth page transitions
- Implemented loading states with spinners
- Added micro-interactions for better feedback
- Enhanced button hover and active states
- Added motion effects for UI elements

### 🔐 Security Features
- Secure token storage
- Added confirmation dialogs for destructive actions
- Implemented data validation
- Added file size and type validation
- Secure connection management

### ️ Accessibility
- Improved keyboard navigation
- Enhanced screen reader support
- Added ARIA labels and descriptions
- Implemented focus management
- Added proper dialog accessibility

### 🎯 Developer Experience
- Added comprehensive debug information
- Implemented system status monitoring
- Added version control integration
- Enhanced error handling and reporting
- Added detailed logging system

---

## 🔧 Technical Details
- **Frontend Stack**
  - React 18 with TypeScript
  - Framer Motion for animations
  - TailwindCSS for styling
  - Radix UI for accessible components

- **State Management**
  - Local storage for persistence
  - React hooks for state
  - Custom stores for global state

- **API Integration**
  - GitHub API integration
  - Ollama API integration
  - Provider API management
  - Error boundary implementation

## 📝 Notes
- Initial release focusing on core functionality and user experience
- Enhanced dark mode support across all components
- Improved accessibility and keyboard navigation
- Added comprehensive logging and debugging tools
- Implemented robust error handling and user feedback
2025-01-17 19:33:20 +01:00
lewis liu
9958496468 fix: replace docker-compose with docker compose 2025-01-15 17:47:48 +08:00
github-actions[bot]
be7a754a74 chore: release version 0.0.5 2024-12-31 22:28:12 +00:00
github-actions[bot]
2a585ab5ea chore: release version 0.0.4 2024-12-31 17:17:51 +00:00
github-actions[bot]
eac1933094 chore: release version 0.0.3 2024-12-17 21:00:06 +00:00
github-actions[bot]
c36ab43dcc chore: release version 0.0.2 2024-12-16 21:50:28 +00:00
333 changed files with 51882 additions and 7617 deletions

View File

@@ -97,6 +97,22 @@ AWS_BEDROCK_CONFIG=
# Include this environment variable if you want more logging for debugging locally
VITE_LOG_LEVEL=debug
# Get your GitHub Personal Access Token here -
# https://github.com/settings/tokens
# This token is used for:
# 1. Importing/cloning GitHub repositories without rate limiting
# 2. Accessing private repositories
# 3. Automatic GitHub authentication (no need to manually connect in the UI)
#
# For classic tokens, ensure it has these scopes: repo, read:org, read:user
# For fine-grained tokens, ensure it has Repository and Organization access
VITE_GITHUB_ACCESS_TOKEN=
# Specify the type of GitHub token you're using
# Can be 'classic' or 'fine-grained'
# Classic tokens are recommended for broader access
VITE_GITHUB_TOKEN_TYPE=classic
# Example Context Values for qwen2.5-coder:32b
#
# DEFAULT_NUM_CTX=32768 # Consumes 36GB of VRAM

115
.env.production Normal file
View File

@@ -0,0 +1,115 @@
# Rename this file to .env once you have filled in the below environment variables!
# Get your GROQ API Key here -
# https://console.groq.com/keys
# You only need this environment variable set if you want to use Groq models
GROQ_API_KEY=
# Get your HuggingFace API Key here -
# https://huggingface.co/settings/tokens
# You only need this environment variable set if you want to use HuggingFace models
HuggingFace_API_KEY=
# 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
# You only need this environment variable set if you want to use GPT models
OPENAI_API_KEY=
# Get your Anthropic API Key in your account settings -
# https://console.anthropic.com/settings/keys
# You only need this environment variable set if you want to use Claude models
ANTHROPIC_API_KEY=
# Get your OpenRouter API Key in your account settings -
# https://openrouter.ai/settings/keys
# You only need this environment variable set if you want to use OpenRouter models
OPEN_ROUTER_API_KEY=
# Get your Google Generative AI API Key by following these instructions -
# https://console.cloud.google.com/apis/credentials
# You only need this environment variable set if you want to use Google Generative AI models
GOOGLE_GENERATIVE_AI_API_KEY=
# You only need this environment variable set if you want to use oLLAMA models
# 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
OPENAI_LIKE_API_BASE_URL=
# You only need this environment variable set if you want to use Together AI models
TOGETHER_API_BASE_URL=
# You only need this environment variable set if you want to use DeepSeek models through their API
DEEPSEEK_API_KEY=
# Get your OpenAI Like API Key
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
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
MISTRAL_API_KEY=
# Get the Cohere Api key by following these instructions -
# https://dashboard.cohere.com/api-keys
# You only need this environment variable set if you want to use Cohere models
COHERE_API_KEY=
# Get LMStudio Base URL from LM Studio Developer Console
# Make sure to enable CORS
# 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
# https://x.ai/api
# 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=
# Get your AWS configuration
# https://console.aws.amazon.com/iam/home
AWS_BEDROCK_CONFIG=
# Include this environment variable if you want more logging for debugging locally
VITE_LOG_LEVEL=
# Get your GitHub Personal Access Token here -
# https://github.com/settings/tokens
# This token is used for:
# 1. Importing/cloning GitHub repositories without rate limiting
# 2. Accessing private repositories
# 3. Automatic GitHub authentication (no need to manually connect in the UI)
#
# For classic tokens, ensure it has these scopes: repo, read:org, read:user
# For fine-grained tokens, ensure it has Repository and Organization access
VITE_GITHUB_ACCESS_TOKEN=
# Specify the type of GitHub token you're using
# Can be 'classic' or 'fine-grained'
# Classic tokens are recommended for broader access
VITE_GITHUB_TOKEN_TYPE=
# Netlify Authentication
VITE_NETLIFY_ACCESS_TOKEN=
# Example Context Values for qwen2.5-coder:32b
#
# 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
DEFAULT_NUM_CTX=

15
.eslintrc.json Normal file
View File

@@ -0,0 +1,15 @@
{
"env": {
"browser": true,
"es2021": true
},
"extends": [
"eslint:recommended",
"plugin:prettier/recommended"
],
"rules": {
// example: turn off console warnings
"no-console": "off"
}
}

View File

@@ -1,4 +1,4 @@
name: "Bug report"
name: 'Bug report'
description: Create a report to help us improve
body:
- type: markdown

View File

@@ -1,14 +1,14 @@
---
name: Docker Publish
on:
workflow_dispatch:
push:
branches:
- main
tags:
- v*
- "*"
branches: [main, stable]
tags: ['v*', '*.*.*']
workflow_dispatch:
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true
permissions:
packages: write
@@ -16,66 +16,47 @@ permissions:
env:
REGISTRY: ghcr.io
DOCKER_IMAGE: ghcr.io/${{ github.repository }}
BUILD_TARGET: bolt-ai-production # bolt-ai-development
IMAGE_NAME: ${{ github.repository }}
jobs:
docker-build-publish:
runs-on: ubuntu-latest
# timeout-minutes: 30
steps:
- name: Checkout
- name: Checkout code
uses: actions/checkout@v4
- id: string
uses: ASzc/change-string-case-action@v6
with:
string: ${{ env.DOCKER_IMAGE }}
- name: Docker meta
id: meta
uses: crazy-max/ghaction-docker-meta@v5
with:
images: ${{ steps.string.outputs.lowercase }}
flavor: |
latest=true
prefix=
suffix=
tags: |
type=semver,pattern={{version}}
type=pep440,pattern={{version}}
type=ref,event=tag
type=raw,value={{sha}}
- name: Set up QEMU
uses: docker/setup-qemu-action@v3
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
- name: Login to Container Registry
- name: Log in to GitHub Container Registry
uses: docker/login-action@v3
with:
registry: ${{ env.REGISTRY }}
username: ${{ github.actor }} # ${{ secrets.DOCKER_USERNAME }}
password: ${{ secrets.GITHUB_TOKEN }} # ${{ secrets.DOCKER_PASSWORD }}
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Build and push
- name: Extract metadata for Docker image
id: meta
uses: docker/metadata-action@v4
with:
images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}
tags: |
type=raw,value=latest,enable=${{ github.ref == 'refs/heads/main' }}
type=raw,value=stable,enable=${{ github.ref == 'refs/heads/stable' }}
type=ref,event=tag
type=sha,format=short
type=raw,value=${{ github.ref_name }},enable=${{ startsWith(github.ref, 'refs/tags/') || github.ref == 'refs/heads/main' || github.ref == 'refs/heads/stable' }}
- name: Build and push Docker image
uses: docker/build-push-action@v6
with:
context: .
file: ./Dockerfile
target: ${{ env.BUILD_TARGET }}
platforms: linux/amd64,linux/arm64
target: bolt-ai-production
push: true
tags: ${{ steps.meta.outputs.tags }}
labels: ${{ steps.meta.outputs.labels }}
cache-from: type=registry,ref=${{ steps.string.outputs.lowercase }}:latest
cache-to: type=inline
- name: Check manifest
run: |
docker buildx imagetools inspect ${{ steps.string.outputs.lowercase }}:${{ steps.meta.outputs.version }}
- name: Dump context
if: always()
uses: crazy-max/ghaction-dump-context@v2
run: docker buildx imagetools inspect ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:${{ steps.meta.outputs.version }}

View File

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

98
.github/workflows/electron.yml vendored Normal file
View File

@@ -0,0 +1,98 @@
name: Electron Build and Release
on:
workflow_dispatch:
inputs:
tag:
description: 'Tag for the release (e.g., v1.0.0). Leave empty if not applicable.'
required: false
push:
branches:
- electron
tags:
- 'v*'
permissions:
contents: write
jobs:
build:
runs-on: ${{ matrix.os }}
strategy:
matrix:
os: [ubuntu-latest, windows-latest, macos-latest] # Use unsigned macOS builds for now
node-version: [18.18.0]
fail-fast: false
steps:
- name: Check out Git repository
uses: actions/checkout@v4
- name: Install Node.js
uses: actions/setup-node@v4
with:
node-version: ${{ matrix.node-version }}
- name: Install pnpm
uses: pnpm/action-setup@v2
with:
version: 9.14.4
run_install: false
- name: Get pnpm store directory
shell: bash
run: |
echo "STORE_PATH=$(pnpm store path --silent)" >> $GITHUB_ENV
- name: Setup pnpm cache
uses: actions/cache@v3
with:
path: ${{ env.STORE_PATH }}
key: ${{ runner.os }}-pnpm-store-${{ hashFiles('**/pnpm-lock.yaml') }}
restore-keys: |
${{ runner.os }}-pnpm-store-
- name: Install dependencies
run: pnpm install
# Install Linux dependencies
- name: Install Linux dependencies
if: matrix.os == 'ubuntu-latest'
run: |
sudo apt-get update
sudo apt-get install -y rpm
# Build
- name: Build Electron app
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
NODE_OPTIONS: "--max_old_space_size=4096"
run: |
if [ "$RUNNER_OS" == "Windows" ]; then
pnpm run electron:build:win
elif [ "$RUNNER_OS" == "macOS" ]; then
pnpm run electron:build:mac
else
pnpm run electron:build:linux
fi
shell: bash
# Create Release
- name: Create Release
uses: softprops/action-gh-release@v2
with:
# Use the workflow_dispatch input tag if available, else use the Git ref name.
tag_name: ${{ github.event_name == 'workflow_dispatch' && github.event.inputs.tag || github.ref_name }}
# Only branch pushes remain drafts. For workflow_dispatch and tag pushes the release is published.
draft: ${{ github.event_name != 'workflow_dispatch' && github.ref_type == 'branch' }}
# For tag pushes, name the release as "Release <tagname>", otherwise "Electron Release".
name: ${{ (github.event_name == 'push' && github.ref_type == 'tag') && format('Release {0}', github.ref_name) || 'Electron Release' }}
files: |
dist/*.exe
dist/*.dmg
dist/*.deb
dist/*.AppImage
dist/*.zip
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

View File

@@ -2,8 +2,8 @@ name: Mark Stale Issues and Pull Requests
on:
schedule:
- cron: '0 2 * * *' # Runs daily at 2:00 AM UTC
workflow_dispatch: # Allows manual triggering of the workflow
- cron: '0 2 * * *' # Runs daily at 2:00 AM UTC
workflow_dispatch: # Allows manual triggering of the workflow
jobs:
stale:
@@ -14,12 +14,12 @@ jobs:
uses: actions/stale@v8
with:
repo-token: ${{ secrets.GITHUB_TOKEN }}
stale-issue-message: "This issue has been marked as stale due to inactivity. If no further activity occurs, it will be closed in 7 days."
stale-pr-message: "This pull request has been marked as stale due to inactivity. If no further activity occurs, it will be closed in 7 days."
days-before-stale: 10 # Number of days before marking an issue or PR as stale
days-before-close: 4 # Number of days after being marked stale before closing
stale-issue-label: "stale" # Label to apply to stale issues
stale-pr-label: "stale" # Label to apply to stale pull requests
exempt-issue-labels: "pinned,important" # Issues with these labels won't be marked stale
exempt-pr-labels: "pinned,important" # PRs with these labels won't be marked stale
operations-per-run: 75 # Limits the number of actions per run to avoid API rate limits
stale-issue-message: 'This issue has been marked as stale due to inactivity. If no further activity occurs, it will be closed in 7 days.'
stale-pr-message: 'This pull request has been marked as stale due to inactivity. If no further activity occurs, it will be closed in 7 days.'
days-before-stale: 10 # Number of days before marking an issue or PR as stale
days-before-close: 4 # Number of days after being marked stale before closing
stale-issue-label: 'stale' # Label to apply to stale issues
stale-pr-label: 'stale' # Label to apply to stale pull requests
exempt-issue-labels: 'pinned,important' # Issues with these labels won't be marked stale
exempt-pr-labels: 'pinned,important' # PRs with these labels won't be marked stale
operations-per-run: 75 # Limits the number of actions per run to avoid API rate limits

View File

@@ -80,7 +80,6 @@ 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
@@ -120,7 +119,9 @@ jobs:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
VERSION="v${{ steps.bump_version.outputs.new_version }}"
# Save changelog to a file
echo "${{ steps.changelog.outputs.content }}" > release_notes.md
gh release create "$VERSION" \
--title "Release $VERSION" \
--notes "${{ steps.changelog.outputs.content }}" \
--notes-file release_notes.md \
--target stable

6
.gitignore vendored
View File

@@ -25,6 +25,7 @@ dist-ssr
/.history
/.cache
/build
functions/build/
.env.local
.env
.dev.vars
@@ -40,3 +41,8 @@ site
# commit file ignore
app/commit.json
changelogUI.md
docs/instructions/Roadmap.md
.cursorrules
*.md
.qodo

View File

@@ -1,2 +0,0 @@
nodejs 20.15.1
pnpm 9.4.0

92
CHANGES.md Normal file
View File

@@ -0,0 +1,92 @@
# File and Folder Locking Feature Implementation
## Overview
This implementation adds persistent file and folder locking functionality to the BoltDIY project. When a file or folder is locked, it cannot be modified by either the user or the AI until it is unlocked. All locks are scoped to the current chat/project to prevent locks from one project affecting files with matching names in other projects.
## New Files
### 1. `app/components/chat/LockAlert.tsx`
- A dedicated alert component for displaying lock-related error messages
- Features a distinctive amber/yellow color scheme and lock icon
- Provides clear instructions to the user about locked files
### 2. `app/lib/persistence/lockedFiles.ts`
- Core functionality for persisting file and folder locks in localStorage
- Provides functions for adding, removing, and retrieving locked files and folders
- Defines the lock modes: "full" (no modifications) and "scoped" (only additions allowed)
- Implements chat ID scoping to isolate locks to specific projects
### 3. `app/utils/fileLocks.ts`
- Utility functions for checking if a file or folder is locked
- Helps avoid circular dependencies between components and stores
- Provides a consistent interface for lock checking across the application
- Extracts chat ID from URL for project-specific lock scoping
## Modified Files
### 1. `app/components/chat/ChatAlert.tsx`
- Updated to use the new LockAlert component for locked file errors
- Maintains backward compatibility with other error types
### 2. `app/components/editor/codemirror/CodeMirrorEditor.tsx`
- Added checks to prevent editing of locked files
- Updated to use the new fileLocks utility
- Displays appropriate tooltips when a user attempts to edit a locked file
### 3. `app/components/workbench/EditorPanel.tsx`
- Added safety checks for unsavedFiles to prevent errors
- Improved handling of locked files in the editor panel
### 4. `app/components/workbench/FileTree.tsx`
- Added visual indicators for locked files and folders in the file tree
- Improved handling of locked files and folders in the file tree
- Added context menu options for locking and unlocking folders
### 5. `app/lib/stores/editor.ts`
- Added checks to prevent updating locked files
- Improved error handling for locked files
### 6. `app/lib/stores/files.ts`
- Added core functionality for locking and unlocking files and folders
- Implemented persistence of locked files and folders across page refreshes
- Added methods for checking if a file or folder is locked
- Added chat ID scoping to prevent locks from affecting other projects
### 7. `app/lib/stores/workbench.ts`
- Added methods for locking and unlocking files and folders
- Improved error handling for locked files and folders
- Fixed issues with alert initialization
- Added support for chat ID scoping of locks
### 8. `app/types/actions.ts`
- Added `isLockedFile` property to the ActionAlert interface
- Improved type definitions for locked file alerts
## Key Features
1. **Persistent File and Folder Locking**: Locks are stored in localStorage and persist across page refreshes
2. **Visual Indicators**: Locked files and folders are clearly marked in the UI with lock icons
3. **Improved Error Messages**: Clear, visually distinct error messages when attempting to modify locked items
4. **Lock Modes**: Support for both full locks (no modifications) and scoped locks (only additions allowed)
5. **Prevention of AI Modifications**: The AI is prevented from modifying locked files and folders
6. **Project-Specific Locks**: Locks are scoped to the current chat/project to prevent conflicts
7. **Recursive Folder Locking**: Locking a folder automatically locks all files and subfolders within it
## UI Improvements
1. **Enhanced Alert Design**: Modern, visually appealing alert design with better spacing and typography
2. **Contextual Icons**: Different icons and colors for different types of alerts
3. **Improved Error Details**: Better formatting of error details with monospace font and left border
4. **Responsive Buttons**: Better positioned and styled buttons with appropriate hover effects

View File

@@ -27,17 +27,20 @@ This project is governed by our **Code of Conduct**. By participating, you agree
## 🛠️ How Can I Contribute?
### 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.
### 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).
### 3⃣ Join as a Core Contributor
Interested in maintaining and growing the project? Fill out our [Contributor Application Form](https://forms.gle/TBSteXSDCtBDwr5m7).
---
@@ -45,12 +48,14 @@ Interested in maintaining and growing the project? Fill out our [Contributor App
## ✅ Pull Request Guidelines
### PR Checklist
- Branch from the **main** branch.
- Update documentation, if needed.
- Test all functionality manually.
- Focus on one feature/bug per PR.
### Review Process
1. Manual testing by reviewers.
2. At least one maintainer review required.
3. Address review comments.
@@ -61,6 +66,7 @@ Interested in maintaining and growing the project? Fill out our [Contributor App
## 📏 Coding Standards
### General Guidelines
- Follow existing code style.
- Comment complex logic.
- Keep functions small and focused.
@@ -71,6 +77,7 @@ Interested in maintaining and growing the project? Fill out our [Contributor App
## 🖥️ Development Setup
### 1⃣ Initial Setup
- Clone the repository:
```bash
git clone https://github.com/stackblitz-labs/bolt.diy.git
@@ -95,9 +102,11 @@ Interested in maintaining and growing the project? Fill out our [Contributor App
**Note**: Never commit your `.env.local` file to version control. Its already in `.gitignore`.
### 2⃣ Run Development Server
```bash
pnpm run dev
```
**Tip**: Use **Google Chrome Canary** for local testing.
---
@@ -105,6 +114,7 @@ pnpm run dev
## 🧪 Testing
Run the test suite with:
```bash
pnpm test
```
@@ -114,9 +124,11 @@ pnpm test
## 🚀 Deployment
### Deploy to Cloudflare Pages
```bash
pnpm run deploy
```
Ensure you have required permissions and that Wrangler is configured.
---
@@ -132,22 +144,26 @@ This section outlines the methods for deploying the application using Docker. Th
#### 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
docker compose --profile development up
```
#### Running the Development Container
```bash
docker run -p 5173:5173 --env-file .env.local bolt-ai:development
```
@@ -159,22 +175,26 @@ docker run -p 5173:5173 --env-file .env.local bolt-ai:development
#### Build Options
**Option 1: Helper Scripts**
```bash
# Production build
npm run dockerbuild:prod
```
**Option 2: Direct Docker Build Command**
```bash
docker build . --target bolt-ai-production
```
**Option 3: Docker Compose Profile**
```bash
docker-compose --profile production up
docker compose --profile production up
```
#### Running the Production Container
```bash
docker run -p 5173:5173 --env-file .env.local bolt-ai:production
```
@@ -184,6 +204,7 @@ docker run -p 5173:5173 --env-file .env.local bolt-ai:production
### Coolify Deployment
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).
@@ -210,10 +231,12 @@ The `docker-compose.yaml` configuration is compatible with **VS Code Dev Contain
## 🔑 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
```

View File

@@ -6,7 +6,10 @@ WORKDIR /app
# Install dependencies (this step is cached as long as the dependencies don't change)
COPY package.json pnpm-lock.yaml ./
RUN corepack enable pnpm && pnpm install
#RUN npm install -g corepack@latest
#RUN corepack enable pnpm && pnpm install
RUN npm install -g pnpm && pnpm install --prod=false
# Copy the rest of your app's source code
COPY . .

22
FAQ.md
View File

@@ -12,6 +12,7 @@ For the best experience with bolt.diy, we recommend using the following models:
- **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!
</details>
<details>
@@ -21,20 +22,21 @@ For the best experience with bolt.diy, we recommend using the following models:
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.
- **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.
Before sending your prompt, click the _enhance_ icon to let the AI refine your prompt. You can edit the suggested improvements before submitting.
- **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.
- **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."*
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>
<details>
<summary><strong>How do I contribute to bolt.diy?</strong></summary>
Check out our [Contribution Guide](CONTRIBUTING.md) for more details on how to get involved!
</details>
<details>
@@ -42,6 +44,7 @@ Check out our [Contribution Guide](CONTRIBUTING.md) for more details on how to g
Visit our [Roadmap](https://roadmap.sh/r/ottodev-roadmap-2ovzo) for the latest updates.
New features and improvements are on the way!
</details>
<details>
@@ -50,40 +53,51 @@ New features and improvements are on the way!
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!
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>
<details>
<summary><strong>How do local LLMs compare to larger models like Claude 3.5 Sonnet for bolt.diy?</strong></summary>
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>
<details>
<summary><strong>Common Errors and Troubleshooting</strong></summary>
### **"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).
- The developer console in your browser (press `F12` or right-click > _Inspect_, then go to the _Console_ tab).
### **"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.
### **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.
### **"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.
### **"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)
### **"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>
---

View File

@@ -31,7 +31,7 @@ and this way communicate where the focus currently is.
2. Grouping of features
By linking features with epics, we can keep them together and document *why* we invest work into a particular thing.
By linking features with epics, we can keep them together and document _why_ we invest work into a particular thing.
## Features (mid-term)
@@ -41,13 +41,13 @@ function, you name it).
However, we intentionally describe features in a more vague manner. Why? Everybody loves crisp, well-defined
acceptance-criteria, no? Well, every product owner loves it. because he knows what hell get once its done.
But: **here is no owner of this product**. Therefore, we grant *maximum flexibility to the developer contributing a feature* so that he can bring in his ideas and have most fun implementing it.
But: **here is no owner of this product**. Therefore, we grant _maximum flexibility to the developer contributing a feature_ so that he can bring in his ideas and have most fun implementing it.
The feature therefore tries to describe *what* should be improved but not in detail *how*.
The feature therefore tries to describe _what_ should be improved but not in detail _how_.
## PRs as materialized features (short-term)
Once a developer starts working on a feature, a draft-PR *can* be opened asap to share, describe and discuss, how the feature shall be implemented. But: this is not a must. It just helps to get early feedback and get other developers involved. Sometimes, the developer just wants to get started and then open a PR later.
Once a developer starts working on a feature, a draft-PR _can_ be opened asap to share, describe and discuss, how the feature shall be implemented. But: this is not a must. It just helps to get early feedback and get other developers involved. Sometimes, the developer just wants to get started and then open a PR later.
In a loosely organized project, it may as well happen that multiple PRs are opened for the same feature. This is no real issue: Usually, peoply being passionate about a solution are willing to join forces and get it done together. And if a second developer was just faster getting the same feature realized: Be happy that it's been done, close the PR and look out for the next feature to implement 🤓

View File

@@ -1,7 +1,8 @@
# bolt.diy (Previously oTToDev)
# bolt.diy
[![bolt.diy: AI-Powered Full-Stack Web Development in the Browser](./public/social_preview_index.jpg)](https://bolt.diy)
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, 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 offical installation instructions and more informations.
@@ -67,7 +68,7 @@ project, please check the [project management guide](./PROJECT.md) to get starte
- ✅ Together Integration (@mouimet-infinisoft)
- ✅ Mobile friendly (@qwikode)
- ✅ Better prompt enhancing (@SujalXplores)
- ✅ Attach images to prompts (@atrokhym)
- ✅ Attach images to prompts (@atrokhym)(@stijnus)
- ✅ Added Git Clone button (@thecodacus)
- ✅ Git Import from url (@thecodacus)
- ✅ PromptLibrary to have different variations of prompts for different use cases (@thecodacus)
@@ -78,10 +79,12 @@ project, please check the [project management guide](./PROJECT.md) to get starte
- ✅ Add Starter Template Options (@thecodacus)
- ✅ Perplexity Integration (@meetpateltech)
- ✅ AWS Bedrock Integration (@kunjabijukchhe)
- ✅ Add a "Diff View" to see the changes (@toddyclipsgg)
-**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
- Deploy directly to Netlify (@xKevIsDev)
- ⬜ Supabase Integration
- ⬜ Have LLM plan the project in a MD file for better results/transparency
- ⬜ VSCode Integration with git-like confirmations
- ⬜ Upload documents for knowledge - UI design templates, a code base to reference coding style, etc.
@@ -89,7 +92,8 @@ project, please check the [project management guide](./PROJECT.md) to get starte
- ⬜ Azure Open AI API Integration
- ⬜ Vertex AI Integration
- ⬜ Granite Integration
- Popout Window for Web Container
- Popout Window for Web Container(@stijnus)
- ✅ Ability to change Popout window size (@stijnus)
## Features
@@ -98,8 +102,9 @@ project, please check the [project management guide](./PROJECT.md) to get starte
- **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.
- **Download projects as ZIP** for easy portability Sync to a folder on the host.
- **Integration-ready Docker support** for a hassle-free setup.
- **Deploy** directly to **Netlify**
## Setup
@@ -113,9 +118,6 @@ Let's get you up and running with the stable version of Bolt.DIY!
- Next **click source.zip**
## Prerequisites
Before you begin, you'll need to install two important pieces of software:
@@ -148,32 +150,35 @@ You have two options for running Bolt.DIY: directly on your machine or using Doc
### Option 1: Direct Installation (Recommended for Beginners)
1. **Install Package Manager (pnpm)**:
```bash
npm install -g pnpm
```
2. **Install Project Dependencies**:
```bash
pnpm install
```
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
@@ -184,12 +189,9 @@ This option requires some familiarity with Docker but provides a more isolated e
2. **Run the Container**:
```bash
docker-compose --profile development up
docker compose --profile development up
```
## Configuring API Keys and Providers
### Adding Your API Keys
@@ -218,6 +220,7 @@ For providers that support custom base URLs (such as Ollama or LM Studio), follo
> **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
@@ -225,56 +228,73 @@ For providers that support custom base URLs (such as Ollama or LM Studio), follo
## 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
git clone -b stable 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**:
3. **Install Dependencies**:
```bash
pnpm install
```
5. **Start the Development Server**:
4. **Start the Development Server**:
```bash
pnpm run dev
```
5. **(OPTIONAL)** Switch to the Main Branch if you want to use pre-release/testbranch:
```bash
git checkout main
pnpm install
pnpm run dev
```
Hint: Be aware that this can have beta-features and more likely got bugs than the stable release
>**Open the WebUI to test (Default: http://localhost:5173)**
> - Beginngers:
> - Try to use a sophisticated Provider/Model like Anthropic with Claude Sonnet 3.x Models to get best results
> - Explanation: The System Prompt currently implemented in bolt.diy cant cover the best performance for all providers and models out there. So it works better with some models, then other, even if the models itself are perfect for >programming
> - Future: Planned is a Plugin/Extentions-Library so there can be different System Prompts for different Models, which will help to get better results
#### 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
git pull
```
3. **Update Dependencies**:
```bash
pnpm install
```
@@ -289,6 +309,7 @@ To get the latest changes from the repository:
If you encounter issues:
1. **Clean Installation**:
```bash
# Remove node modules and lock files
rm -rf node_modules pnpm-lock.yaml
@@ -339,3 +360,9 @@ Explore upcoming features and priorities on our [Roadmap](https://roadmap.sh/r/o
## FAQ
For answers to common questions, issues, and to see a list of recommended models, visit our [FAQ Page](FAQ.md).
# Licensing
**Who needs a commercial WebContainer API license?**
bolt.diy source code is distributed as MIT, but it uses WebContainers API that [requires licensing](https://webcontainers.io/enterprise) for production usage in a commercial, for-profit setting. (Prototypes or POCs do not require a commercial license.) If you're using the API to meet the needs of your customers, prospective customers, and/or employees, you need a license to ensure compliance with our Terms of Service. Usage of the API in violation of these terms may result in your access being revoked.

View File

@@ -0,0 +1,158 @@
import * as DropdownMenu from '@radix-ui/react-dropdown-menu';
import { motion } from 'framer-motion';
import { useStore } from '@nanostores/react';
import { classNames } from '~/utils/classNames';
import { profileStore } from '~/lib/stores/profile';
import type { TabType, Profile } from './types';
const BetaLabel = () => (
<span className="px-1.5 py-0.5 rounded-full bg-purple-500/10 dark:bg-purple-500/20 text-[10px] font-medium text-purple-600 dark:text-purple-400 ml-2">
BETA
</span>
);
interface AvatarDropdownProps {
onSelectTab: (tab: TabType) => void;
}
export const AvatarDropdown = ({ onSelectTab }: AvatarDropdownProps) => {
const profile = useStore(profileStore) as Profile;
return (
<DropdownMenu.Root>
<DropdownMenu.Trigger asChild>
<motion.button
className="w-10 h-10 rounded-full bg-transparent flex items-center justify-center focus:outline-none"
whileHover={{ scale: 1.02 }}
whileTap={{ scale: 0.98 }}
>
{profile?.avatar ? (
<img
src={profile.avatar}
alt={profile?.username || 'Profile'}
className="w-full h-full rounded-full object-cover"
loading="eager"
decoding="sync"
/>
) : (
<div className="w-full h-full rounded-full flex items-center justify-center bg-white dark:bg-gray-800 text-gray-400 dark:text-gray-500">
<div className="i-ph:question w-6 h-6" />
</div>
)}
</motion.button>
</DropdownMenu.Trigger>
<DropdownMenu.Portal>
<DropdownMenu.Content
className={classNames(
'min-w-[240px] z-[250]',
'bg-white dark:bg-[#141414]',
'rounded-lg shadow-lg',
'border border-gray-200/50 dark:border-gray-800/50',
'animate-in fade-in-0 zoom-in-95',
'py-1',
)}
sideOffset={5}
align="end"
>
<div
className={classNames(
'px-4 py-3 flex items-center gap-3',
'border-b border-gray-200/50 dark:border-gray-800/50',
)}
>
<div className="w-10 h-10 rounded-full overflow-hidden flex-shrink-0 bg-white dark:bg-gray-800 shadow-sm">
{profile?.avatar ? (
<img
src={profile.avatar}
alt={profile?.username || 'Profile'}
className={classNames('w-full h-full', 'object-cover', 'transform-gpu', 'image-rendering-crisp')}
loading="eager"
decoding="sync"
/>
) : (
<div className="w-full h-full flex items-center justify-center text-gray-400 dark:text-gray-500 font-medium text-lg">
<span className="relative -top-0.5">?</span>
</div>
)}
</div>
<div className="flex-1 min-w-0">
<div className="font-medium text-sm text-gray-900 dark:text-white truncate">
{profile?.username || 'Guest User'}
</div>
{profile?.bio && <div className="text-xs text-gray-500 dark:text-gray-400 truncate">{profile.bio}</div>}
</div>
</div>
<DropdownMenu.Item
className={classNames(
'flex items-center gap-2 px-4 py-2.5',
'text-sm text-gray-700 dark:text-gray-200',
'hover:bg-purple-50 dark:hover:bg-purple-500/10',
'hover:text-purple-500 dark:hover:text-purple-400',
'cursor-pointer transition-all duration-200',
'outline-none',
'group',
)}
onClick={() => onSelectTab('profile')}
>
<div className="i-ph:user-circle w-4 h-4 text-gray-400 group-hover:text-purple-500 dark:group-hover:text-purple-400 transition-colors" />
Edit Profile
</DropdownMenu.Item>
<DropdownMenu.Item
className={classNames(
'flex items-center gap-2 px-4 py-2.5',
'text-sm text-gray-700 dark:text-gray-200',
'hover:bg-purple-50 dark:hover:bg-purple-500/10',
'hover:text-purple-500 dark:hover:text-purple-400',
'cursor-pointer transition-all duration-200',
'outline-none',
'group',
)}
onClick={() => onSelectTab('settings')}
>
<div className="i-ph:gear-six w-4 h-4 text-gray-400 group-hover:text-purple-500 dark:group-hover:text-purple-400 transition-colors" />
Settings
</DropdownMenu.Item>
<div className="my-1 border-t border-gray-200/50 dark:border-gray-800/50" />
<DropdownMenu.Item
className={classNames(
'flex items-center gap-2 px-4 py-2.5',
'text-sm text-gray-700 dark:text-gray-200',
'hover:bg-purple-50 dark:hover:bg-purple-500/10',
'hover:text-purple-500 dark:hover:text-purple-400',
'cursor-pointer transition-all duration-200',
'outline-none',
'group',
)}
onClick={() => onSelectTab('task-manager')}
>
<div className="i-ph:activity w-4 h-4 text-gray-400 group-hover:text-purple-500 dark:group-hover:text-purple-400 transition-colors" />
Task Manager
<BetaLabel />
</DropdownMenu.Item>
<DropdownMenu.Item
className={classNames(
'flex items-center gap-2 px-4 py-2.5',
'text-sm text-gray-700 dark:text-gray-200',
'hover:bg-purple-50 dark:hover:bg-purple-500/10',
'hover:text-purple-500 dark:hover:text-purple-400',
'cursor-pointer transition-all duration-200',
'outline-none',
'group',
)}
onClick={() => onSelectTab('service-status')}
>
<div className="i-ph:heartbeat w-4 h-4 text-gray-400 group-hover:text-purple-500 dark:group-hover:text-purple-400 transition-colors" />
Service Status
<BetaLabel />
</DropdownMenu.Item>
</DropdownMenu.Content>
</DropdownMenu.Portal>
</DropdownMenu.Root>
);
};

View File

@@ -0,0 +1,555 @@
import { useState, useEffect, useMemo } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { useStore } from '@nanostores/react';
import { Switch } from '@radix-ui/react-switch';
import * as RadixDialog from '@radix-ui/react-dialog';
import { classNames } from '~/utils/classNames';
import { TabManagement } from '~/components/@settings/shared/components/TabManagement';
import { TabTile } from '~/components/@settings/shared/components/TabTile';
import { useUpdateCheck } from '~/lib/hooks/useUpdateCheck';
import { useFeatures } from '~/lib/hooks/useFeatures';
import { useNotifications } from '~/lib/hooks/useNotifications';
import { useConnectionStatus } from '~/lib/hooks/useConnectionStatus';
import { useDebugStatus } from '~/lib/hooks/useDebugStatus';
import {
tabConfigurationStore,
developerModeStore,
setDeveloperMode,
resetTabConfiguration,
} from '~/lib/stores/settings';
import { profileStore } from '~/lib/stores/profile';
import type { TabType, TabVisibilityConfig, Profile } from './types';
import { TAB_LABELS, DEFAULT_TAB_CONFIG } from './constants';
import { DialogTitle } from '~/components/ui/Dialog';
import { AvatarDropdown } from './AvatarDropdown';
import BackgroundRays from '~/components/ui/BackgroundRays';
// Import all tab components
import ProfileTab from '~/components/@settings/tabs/profile/ProfileTab';
import SettingsTab from '~/components/@settings/tabs/settings/SettingsTab';
import NotificationsTab from '~/components/@settings/tabs/notifications/NotificationsTab';
import FeaturesTab from '~/components/@settings/tabs/features/FeaturesTab';
import { DataTab } from '~/components/@settings/tabs/data/DataTab';
import DebugTab from '~/components/@settings/tabs/debug/DebugTab';
import { EventLogsTab } from '~/components/@settings/tabs/event-logs/EventLogsTab';
import UpdateTab from '~/components/@settings/tabs/update/UpdateTab';
import ConnectionsTab from '~/components/@settings/tabs/connections/ConnectionsTab';
import CloudProvidersTab from '~/components/@settings/tabs/providers/cloud/CloudProvidersTab';
import ServiceStatusTab from '~/components/@settings/tabs/providers/status/ServiceStatusTab';
import LocalProvidersTab from '~/components/@settings/tabs/providers/local/LocalProvidersTab';
import TaskManagerTab from '~/components/@settings/tabs/task-manager/TaskManagerTab';
interface ControlPanelProps {
open: boolean;
onClose: () => void;
}
interface TabWithDevType extends TabVisibilityConfig {
isExtraDevTab?: boolean;
}
interface ExtendedTabConfig extends TabVisibilityConfig {
isExtraDevTab?: boolean;
}
interface BaseTabConfig {
id: TabType;
visible: boolean;
window: 'user' | 'developer';
order: number;
}
interface AnimatedSwitchProps {
checked: boolean;
onCheckedChange: (checked: boolean) => void;
id: string;
label: string;
}
const TAB_DESCRIPTIONS: Record<TabType, string> = {
profile: 'Manage your profile and account settings',
settings: 'Configure application preferences',
notifications: 'View and manage your notifications',
features: 'Explore new and upcoming features',
data: 'Manage your data and storage',
'cloud-providers': 'Configure cloud AI providers and models',
'local-providers': 'Configure local AI providers and models',
'service-status': 'Monitor cloud LLM service status',
connection: 'Check connection status and settings',
debug: 'Debug tools and system information',
'event-logs': 'View system events and logs',
update: 'Check for updates and release notes',
'task-manager': 'Monitor system resources and processes',
'tab-management': 'Configure visible tabs and their order',
};
// Beta status for experimental features
const BETA_TABS = new Set<TabType>(['task-manager', 'service-status', 'update', 'local-providers']);
const BetaLabel = () => (
<div className="absolute top-2 right-2 px-1.5 py-0.5 rounded-full bg-purple-500/10 dark:bg-purple-500/20">
<span className="text-[10px] font-medium text-purple-600 dark:text-purple-400">BETA</span>
</div>
);
const AnimatedSwitch = ({ checked, onCheckedChange, id, label }: AnimatedSwitchProps) => {
return (
<div className="flex items-center gap-2">
<Switch
id={id}
checked={checked}
onCheckedChange={onCheckedChange}
className={classNames(
'relative inline-flex h-6 w-11 items-center rounded-full',
'transition-all duration-300 ease-[cubic-bezier(0.87,_0,_0.13,_1)]',
'bg-gray-200 dark:bg-gray-700',
'data-[state=checked]:bg-purple-500',
'focus:outline-none focus:ring-2 focus:ring-purple-500/20',
'cursor-pointer',
'group',
)}
>
<motion.span
className={classNames(
'absolute left-[2px] top-[2px]',
'inline-block h-5 w-5 rounded-full',
'bg-white shadow-lg',
'transition-shadow duration-300',
'group-hover:shadow-md group-active:shadow-sm',
'group-hover:scale-95 group-active:scale-90',
)}
initial={false}
transition={{
type: 'spring',
stiffness: 500,
damping: 30,
duration: 0.2,
}}
animate={{
x: checked ? '1.25rem' : '0rem',
}}
>
<motion.div
className="absolute inset-0 rounded-full bg-white"
initial={false}
animate={{
scale: checked ? 1 : 0.8,
}}
transition={{ duration: 0.2 }}
/>
</motion.span>
<span className="sr-only">Toggle {label}</span>
</Switch>
<div className="flex items-center gap-2">
<label
htmlFor={id}
className="text-sm text-gray-500 dark:text-gray-400 select-none cursor-pointer whitespace-nowrap w-[88px]"
>
{label}
</label>
</div>
</div>
);
};
export const ControlPanel = ({ open, onClose }: ControlPanelProps) => {
// State
const [activeTab, setActiveTab] = useState<TabType | null>(null);
const [loadingTab, setLoadingTab] = useState<TabType | null>(null);
const [showTabManagement, setShowTabManagement] = useState(false);
// Store values
const tabConfiguration = useStore(tabConfigurationStore);
const developerMode = useStore(developerModeStore);
const profile = useStore(profileStore) as Profile;
// Status hooks
const { hasUpdate, currentVersion, acknowledgeUpdate } = useUpdateCheck();
const { hasNewFeatures, unviewedFeatures, acknowledgeAllFeatures } = useFeatures();
const { hasUnreadNotifications, unreadNotifications, markAllAsRead } = useNotifications();
const { hasConnectionIssues, currentIssue, acknowledgeIssue } = useConnectionStatus();
const { hasActiveWarnings, activeIssues, acknowledgeAllIssues } = useDebugStatus();
// Memoize the base tab configurations to avoid recalculation
const baseTabConfig = useMemo(() => {
return new Map(DEFAULT_TAB_CONFIG.map((tab) => [tab.id, tab]));
}, []);
// Add visibleTabs logic using useMemo with optimized calculations
const visibleTabs = useMemo(() => {
if (!tabConfiguration?.userTabs || !Array.isArray(tabConfiguration.userTabs)) {
console.warn('Invalid tab configuration, resetting to defaults');
resetTabConfiguration();
return [];
}
const notificationsDisabled = profile?.preferences?.notifications === false;
// In developer mode, show ALL tabs without restrictions
if (developerMode) {
const seenTabs = new Set<TabType>();
const devTabs: ExtendedTabConfig[] = [];
// Process tabs in order of priority: developer, user, default
const processTab = (tab: BaseTabConfig) => {
if (!seenTabs.has(tab.id)) {
seenTabs.add(tab.id);
devTabs.push({
id: tab.id,
visible: true,
window: 'developer',
order: tab.order || devTabs.length,
});
}
};
// Process tabs in priority order
tabConfiguration.developerTabs?.forEach((tab) => processTab(tab as BaseTabConfig));
tabConfiguration.userTabs.forEach((tab) => processTab(tab as BaseTabConfig));
DEFAULT_TAB_CONFIG.forEach((tab) => processTab(tab as BaseTabConfig));
// Add Tab Management tile
devTabs.push({
id: 'tab-management' as TabType,
visible: true,
window: 'developer',
order: devTabs.length,
isExtraDevTab: true,
});
return devTabs.sort((a, b) => a.order - b.order);
}
// Optimize user mode tab filtering
return tabConfiguration.userTabs
.filter((tab) => {
if (!tab?.id) {
return false;
}
if (tab.id === 'notifications' && notificationsDisabled) {
return false;
}
return tab.visible && tab.window === 'user';
})
.sort((a, b) => a.order - b.order);
}, [tabConfiguration, developerMode, profile?.preferences?.notifications, baseTabConfig]);
// Optimize animation performance with layout animations
const gridLayoutVariants = {
hidden: { opacity: 0 },
visible: {
opacity: 1,
transition: {
staggerChildren: 0.05,
delayChildren: 0.1,
},
},
};
const itemVariants = {
hidden: { opacity: 0, scale: 0.8 },
visible: {
opacity: 1,
scale: 1,
transition: {
type: 'spring',
stiffness: 200,
damping: 20,
mass: 0.6,
},
},
};
// Reset to default view when modal opens/closes
useEffect(() => {
if (!open) {
// Reset when closing
setActiveTab(null);
setLoadingTab(null);
setShowTabManagement(false);
} else {
// When opening, set to null to show the main view
setActiveTab(null);
}
}, [open]);
// Handle closing
const handleClose = () => {
setActiveTab(null);
setLoadingTab(null);
setShowTabManagement(false);
onClose();
};
// Handlers
const handleBack = () => {
if (showTabManagement) {
setShowTabManagement(false);
} else if (activeTab) {
setActiveTab(null);
}
};
const handleDeveloperModeChange = (checked: boolean) => {
console.log('Developer mode changed:', checked);
setDeveloperMode(checked);
};
// Add effect to log developer mode changes
useEffect(() => {
console.log('Current developer mode:', developerMode);
}, [developerMode]);
const getTabComponent = (tabId: TabType | 'tab-management') => {
if (tabId === 'tab-management') {
return <TabManagement />;
}
switch (tabId) {
case 'profile':
return <ProfileTab />;
case 'settings':
return <SettingsTab />;
case 'notifications':
return <NotificationsTab />;
case 'features':
return <FeaturesTab />;
case 'data':
return <DataTab />;
case 'cloud-providers':
return <CloudProvidersTab />;
case 'local-providers':
return <LocalProvidersTab />;
case 'connection':
return <ConnectionsTab />;
case 'debug':
return <DebugTab />;
case 'event-logs':
return <EventLogsTab />;
case 'update':
return <UpdateTab />;
case 'task-manager':
return <TaskManagerTab />;
case 'service-status':
return <ServiceStatusTab />;
default:
return null;
}
};
const getTabUpdateStatus = (tabId: TabType): boolean => {
switch (tabId) {
case 'update':
return hasUpdate;
case 'features':
return hasNewFeatures;
case 'notifications':
return hasUnreadNotifications;
case 'connection':
return hasConnectionIssues;
case 'debug':
return hasActiveWarnings;
default:
return false;
}
};
const getStatusMessage = (tabId: TabType): string => {
switch (tabId) {
case 'update':
return `New update available (v${currentVersion})`;
case 'features':
return `${unviewedFeatures.length} new feature${unviewedFeatures.length === 1 ? '' : 's'} to explore`;
case 'notifications':
return `${unreadNotifications.length} unread notification${unreadNotifications.length === 1 ? '' : 's'}`;
case 'connection':
return currentIssue === 'disconnected'
? 'Connection lost'
: currentIssue === 'high-latency'
? 'High latency detected'
: 'Connection issues detected';
case 'debug': {
const warnings = activeIssues.filter((i) => i.type === 'warning').length;
const errors = activeIssues.filter((i) => i.type === 'error').length;
return `${warnings} warning${warnings === 1 ? '' : 's'}, ${errors} error${errors === 1 ? '' : 's'}`;
}
default:
return '';
}
};
const handleTabClick = (tabId: TabType) => {
setLoadingTab(tabId);
setActiveTab(tabId);
setShowTabManagement(false);
// Acknowledge notifications based on tab
switch (tabId) {
case 'update':
acknowledgeUpdate();
break;
case 'features':
acknowledgeAllFeatures();
break;
case 'notifications':
markAllAsRead();
break;
case 'connection':
acknowledgeIssue();
break;
case 'debug':
acknowledgeAllIssues();
break;
}
// Clear loading state after a delay
setTimeout(() => setLoadingTab(null), 500);
};
return (
<RadixDialog.Root open={open}>
<RadixDialog.Portal>
<div className="fixed inset-0 flex items-center justify-center z-[100] modern-scrollbar">
<RadixDialog.Overlay asChild>
<motion.div
className="absolute inset-0 bg-black/70 dark:bg-black/80 backdrop-blur-sm"
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0 }}
transition={{ duration: 0.2 }}
/>
</RadixDialog.Overlay>
<RadixDialog.Content
aria-describedby={undefined}
onEscapeKeyDown={handleClose}
onPointerDownOutside={handleClose}
className="relative z-[101]"
>
<motion.div
className={classNames(
'w-[1200px] h-[90vh]',
'bg-[#FAFAFA] dark:bg-[#0A0A0A]',
'rounded-2xl shadow-2xl',
'border border-[#E5E5E5] dark:border-[#1A1A1A]',
'flex flex-col overflow-hidden',
'relative',
)}
initial={{ opacity: 0, scale: 0.95, y: 20 }}
animate={{ opacity: 1, scale: 1, y: 0 }}
exit={{ opacity: 0, scale: 0.95, y: 20 }}
transition={{ duration: 0.2 }}
>
<div className="absolute inset-0 overflow-hidden rounded-2xl">
<BackgroundRays />
</div>
<div className="relative z-10 flex flex-col h-full">
{/* Header */}
<div className="flex items-center justify-between px-6 py-4 border-b border-gray-200 dark:border-gray-700">
<div className="flex items-center space-x-4">
{(activeTab || showTabManagement) && (
<button
onClick={handleBack}
className="flex items-center justify-center w-8 h-8 rounded-full bg-transparent hover:bg-purple-500/10 dark:hover:bg-purple-500/20 group transition-all duration-200"
>
<div className="i-ph:arrow-left w-4 h-4 text-gray-500 dark:text-gray-400 group-hover:text-purple-500 transition-colors" />
</button>
)}
<DialogTitle className="text-xl font-semibold text-gray-900 dark:text-white">
{showTabManagement ? 'Tab Management' : activeTab ? TAB_LABELS[activeTab] : 'Control Panel'}
</DialogTitle>
</div>
<div className="flex items-center gap-6">
{/* Mode Toggle */}
<div className="flex items-center gap-2 min-w-[140px] border-r border-gray-200 dark:border-gray-800 pr-6">
<AnimatedSwitch
id="developer-mode"
checked={developerMode}
onCheckedChange={handleDeveloperModeChange}
label={developerMode ? 'Developer Mode' : 'User Mode'}
/>
</div>
{/* Avatar and Dropdown */}
<div className="border-l border-gray-200 dark:border-gray-800 pl-6">
<AvatarDropdown onSelectTab={handleTabClick} />
</div>
{/* Close Button */}
<button
onClick={handleClose}
className="flex items-center justify-center w-8 h-8 rounded-full bg-transparent hover:bg-purple-500/10 dark:hover:bg-purple-500/20 group transition-all duration-200"
>
<div className="i-ph:x w-4 h-4 text-gray-500 dark:text-gray-400 group-hover:text-purple-500 transition-colors" />
</button>
</div>
</div>
{/* Content */}
<div
className={classNames(
'flex-1',
'overflow-y-auto',
'hover:overflow-y-auto',
'scrollbar scrollbar-w-2',
'scrollbar-track-transparent',
'scrollbar-thumb-[#E5E5E5] hover:scrollbar-thumb-[#CCCCCC]',
'dark:scrollbar-thumb-[#333333] dark:hover:scrollbar-thumb-[#444444]',
'will-change-scroll',
'touch-auto',
)}
>
<motion.div
key={activeTab || 'home'}
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0 }}
transition={{ duration: 0.2 }}
className="p-6"
>
{showTabManagement ? (
<TabManagement />
) : activeTab ? (
getTabComponent(activeTab)
) : (
<motion.div
className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4 relative"
variants={gridLayoutVariants}
initial="hidden"
animate="visible"
>
<AnimatePresence mode="popLayout">
{(visibleTabs as TabWithDevType[]).map((tab: TabWithDevType) => (
<motion.div key={tab.id} layout variants={itemVariants} className="aspect-[1.5/1]">
<TabTile
tab={tab}
onClick={() => handleTabClick(tab.id as TabType)}
isActive={activeTab === tab.id}
hasUpdate={getTabUpdateStatus(tab.id)}
statusMessage={getStatusMessage(tab.id)}
description={TAB_DESCRIPTIONS[tab.id]}
isLoading={loadingTab === tab.id}
className="h-full relative"
>
{BETA_TABS.has(tab.id) && <BetaLabel />}
</TabTile>
</motion.div>
))}
</AnimatePresence>
</motion.div>
)}
</motion.div>
</div>
</div>
</motion.div>
</RadixDialog.Content>
</div>
</RadixDialog.Portal>
</RadixDialog.Root>
);
};

View File

@@ -0,0 +1,88 @@
import type { TabType } from './types';
export const TAB_ICONS: Record<TabType, string> = {
profile: 'i-ph:user-circle-fill',
settings: 'i-ph:gear-six-fill',
notifications: 'i-ph:bell-fill',
features: 'i-ph:star-fill',
data: 'i-ph:database-fill',
'cloud-providers': 'i-ph:cloud-fill',
'local-providers': 'i-ph:desktop-fill',
'service-status': 'i-ph:activity-bold',
connection: 'i-ph:wifi-high-fill',
debug: 'i-ph:bug-fill',
'event-logs': 'i-ph:list-bullets-fill',
update: 'i-ph:arrow-clockwise-fill',
'task-manager': 'i-ph:chart-line-fill',
'tab-management': 'i-ph:squares-four-fill',
};
export const TAB_LABELS: Record<TabType, string> = {
profile: 'Profile',
settings: 'Settings',
notifications: 'Notifications',
features: 'Features',
data: 'Data Management',
'cloud-providers': 'Cloud Providers',
'local-providers': 'Local Providers',
'service-status': 'Service Status',
connection: 'Connection',
debug: 'Debug',
'event-logs': 'Event Logs',
update: 'Updates',
'task-manager': 'Task Manager',
'tab-management': 'Tab Management',
};
export const TAB_DESCRIPTIONS: Record<TabType, string> = {
profile: 'Manage your profile and account settings',
settings: 'Configure application preferences',
notifications: 'View and manage your notifications',
features: 'Explore new and upcoming features',
data: 'Manage your data and storage',
'cloud-providers': 'Configure cloud AI providers and models',
'local-providers': 'Configure local AI providers and models',
'service-status': 'Monitor cloud LLM service status',
connection: 'Check connection status and settings',
debug: 'Debug tools and system information',
'event-logs': 'View system events and logs',
update: 'Check for updates and release notes',
'task-manager': 'Monitor system resources and processes',
'tab-management': 'Configure visible tabs and their order',
};
export const DEFAULT_TAB_CONFIG = [
// User Window Tabs (Always visible by default)
{ id: 'features', visible: true, window: 'user' as const, order: 0 },
{ id: 'data', visible: true, window: 'user' as const, order: 1 },
{ id: 'cloud-providers', visible: true, window: 'user' as const, order: 2 },
{ id: 'local-providers', visible: true, window: 'user' as const, order: 3 },
{ id: 'connection', visible: true, window: 'user' as const, order: 4 },
{ id: 'notifications', visible: true, window: 'user' as const, order: 5 },
{ id: 'event-logs', visible: true, window: 'user' as const, order: 6 },
// User Window Tabs (In dropdown, initially hidden)
{ id: 'profile', visible: false, window: 'user' as const, order: 7 },
{ id: 'settings', visible: false, window: 'user' as const, order: 8 },
{ id: 'task-manager', visible: false, window: 'user' as const, order: 9 },
{ id: 'service-status', visible: false, window: 'user' as const, order: 10 },
// User Window Tabs (Hidden, controlled by TaskManagerTab)
{ id: 'debug', visible: false, window: 'user' as const, order: 11 },
{ id: 'update', visible: false, window: 'user' as const, order: 12 },
// Developer Window Tabs (All visible by default)
{ id: 'features', visible: true, window: 'developer' as const, order: 0 },
{ id: 'data', visible: true, window: 'developer' as const, order: 1 },
{ id: 'cloud-providers', visible: true, window: 'developer' as const, order: 2 },
{ id: 'local-providers', visible: true, window: 'developer' as const, order: 3 },
{ id: 'connection', visible: true, window: 'developer' as const, order: 4 },
{ id: 'notifications', visible: true, window: 'developer' as const, order: 5 },
{ id: 'event-logs', visible: true, window: 'developer' as const, order: 6 },
{ id: 'profile', visible: true, window: 'developer' as const, order: 7 },
{ id: 'settings', visible: true, window: 'developer' as const, order: 8 },
{ id: 'task-manager', visible: true, window: 'developer' as const, order: 9 },
{ id: 'service-status', visible: true, window: 'developer' as const, order: 10 },
{ id: 'debug', visible: true, window: 'developer' as const, order: 11 },
{ id: 'update', visible: true, window: 'developer' as const, order: 12 },
];

View File

@@ -0,0 +1,114 @@
import type { ReactNode } from 'react';
export type SettingCategory = 'profile' | 'file_sharing' | 'connectivity' | 'system' | 'services' | 'preferences';
export type TabType =
| 'profile'
| 'settings'
| 'notifications'
| 'features'
| 'data'
| 'cloud-providers'
| 'local-providers'
| 'service-status'
| 'connection'
| 'debug'
| 'event-logs'
| 'update'
| 'task-manager'
| 'tab-management';
export type WindowType = 'user' | 'developer';
export interface UserProfile {
nickname: any;
name: string;
email: string;
avatar?: string;
theme: 'light' | 'dark' | 'system';
notifications: boolean;
password?: string;
bio?: string;
language: string;
timezone: string;
}
export interface SettingItem {
id: TabType;
label: string;
icon: string;
category: SettingCategory;
description?: string;
component: () => ReactNode;
badge?: string;
keywords?: string[];
}
export interface TabVisibilityConfig {
id: TabType;
visible: boolean;
window: WindowType;
order: number;
isExtraDevTab?: boolean;
locked?: boolean;
}
export interface DevTabConfig extends TabVisibilityConfig {
window: 'developer';
}
export interface UserTabConfig extends TabVisibilityConfig {
window: 'user';
}
export interface TabWindowConfig {
userTabs: UserTabConfig[];
developerTabs: DevTabConfig[];
}
export const TAB_LABELS: Record<TabType, string> = {
profile: 'Profile',
settings: 'Settings',
notifications: 'Notifications',
features: 'Features',
data: 'Data Management',
'cloud-providers': 'Cloud Providers',
'local-providers': 'Local Providers',
'service-status': 'Service Status',
connection: 'Connections',
debug: 'Debug',
'event-logs': 'Event Logs',
update: 'Updates',
'task-manager': 'Task Manager',
'tab-management': 'Tab Management',
};
export const categoryLabels: Record<SettingCategory, string> = {
profile: 'Profile & Account',
file_sharing: 'File Sharing',
connectivity: 'Connectivity',
system: 'System',
services: 'Services',
preferences: 'Preferences',
};
export const categoryIcons: Record<SettingCategory, string> = {
profile: 'i-ph:user-circle',
file_sharing: 'i-ph:folder-simple',
connectivity: 'i-ph:wifi-high',
system: 'i-ph:gear',
services: 'i-ph:cube',
preferences: 'i-ph:sliders',
};
export interface Profile {
username?: string;
bio?: string;
avatar?: string;
preferences?: {
notifications?: boolean;
theme?: 'light' | 'dark' | 'system';
language?: string;
timezone?: string;
};
}

View File

@@ -0,0 +1,14 @@
// Core exports
export { ControlPanel } from './core/ControlPanel';
export type { TabType, TabVisibilityConfig } from './core/types';
// Constants
export { TAB_LABELS, TAB_DESCRIPTIONS, DEFAULT_TAB_CONFIG } from './core/constants';
// Shared components
export { TabTile } from './shared/components/TabTile';
export { TabManagement } from './shared/components/TabManagement';
// Utils
export { getVisibleTabs, reorderTabs, resetToDefaultConfig } from './utils/tab-helpers';
export * from './utils/animations';

View File

@@ -0,0 +1,163 @@
import { useDrag, useDrop } from 'react-dnd';
import { motion } from 'framer-motion';
import { classNames } from '~/utils/classNames';
import type { TabVisibilityConfig } from '~/components/@settings/core/types';
import { TAB_LABELS } from '~/components/@settings/core/types';
import { Switch } from '~/components/ui/Switch';
interface DraggableTabListProps {
tabs: TabVisibilityConfig[];
onReorder: (tabs: TabVisibilityConfig[]) => void;
onWindowChange?: (tab: TabVisibilityConfig, window: 'user' | 'developer') => void;
onVisibilityChange?: (tab: TabVisibilityConfig, visible: boolean) => void;
showControls?: boolean;
}
interface DraggableTabItemProps {
tab: TabVisibilityConfig;
index: number;
moveTab: (dragIndex: number, hoverIndex: number) => void;
showControls?: boolean;
onWindowChange?: (tab: TabVisibilityConfig, window: 'user' | 'developer') => void;
onVisibilityChange?: (tab: TabVisibilityConfig, visible: boolean) => void;
}
interface DragItem {
type: string;
index: number;
id: string;
}
const DraggableTabItem = ({
tab,
index,
moveTab,
showControls,
onWindowChange,
onVisibilityChange,
}: DraggableTabItemProps) => {
const [{ isDragging }, dragRef] = useDrag({
type: 'tab',
item: { type: 'tab', index, id: tab.id },
collect: (monitor) => ({
isDragging: monitor.isDragging(),
}),
});
const [, dropRef] = useDrop({
accept: 'tab',
hover: (item: DragItem, monitor) => {
if (!monitor.isOver({ shallow: true })) {
return;
}
if (item.index === index) {
return;
}
if (item.id === tab.id) {
return;
}
moveTab(item.index, index);
item.index = index;
},
});
const ref = (node: HTMLDivElement | null) => {
dragRef(node);
dropRef(node);
};
return (
<motion.div
ref={ref}
initial={false}
animate={{
scale: isDragging ? 1.02 : 1,
boxShadow: isDragging ? '0 8px 16px rgba(0,0,0,0.1)' : 'none',
}}
className={classNames(
'flex items-center justify-between p-4 rounded-lg',
'bg-[#F5F5F5] dark:bg-[#1A1A1A]',
'border border-[#E5E5E5] dark:border-[#333333]',
isDragging ? 'z-50' : '',
)}
>
<div className="flex items-center gap-4">
<div className="cursor-grab">
<div className="i-ph:dots-six-vertical w-4 h-4 text-bolt-elements-textSecondary" />
</div>
<div>
<div className="font-medium text-bolt-elements-textPrimary">{TAB_LABELS[tab.id]}</div>
{showControls && (
<div className="text-xs text-bolt-elements-textSecondary">
Order: {tab.order}, Window: {tab.window}
</div>
)}
</div>
</div>
{showControls && !tab.locked && (
<div className="flex items-center gap-4">
<div className="flex items-center gap-2">
<Switch
checked={tab.visible}
onCheckedChange={(checked: boolean) => onVisibilityChange?.(tab, checked)}
className="data-[state=checked]:bg-purple-500"
aria-label={`Toggle ${TAB_LABELS[tab.id]} visibility`}
/>
<label className="text-sm text-bolt-elements-textSecondary">Visible</label>
</div>
<div className="flex items-center gap-2">
<label className="text-sm text-bolt-elements-textSecondary">User</label>
<Switch
checked={tab.window === 'developer'}
onCheckedChange={(checked: boolean) => onWindowChange?.(tab, checked ? 'developer' : 'user')}
className="data-[state=checked]:bg-purple-500"
aria-label={`Toggle ${TAB_LABELS[tab.id]} window assignment`}
/>
<label className="text-sm text-bolt-elements-textSecondary">Dev</label>
</div>
</div>
)}
</motion.div>
);
};
export const DraggableTabList = ({
tabs,
onReorder,
onWindowChange,
onVisibilityChange,
showControls = false,
}: DraggableTabListProps) => {
const moveTab = (dragIndex: number, hoverIndex: number) => {
const items = Array.from(tabs);
const [reorderedItem] = items.splice(dragIndex, 1);
items.splice(hoverIndex, 0, reorderedItem);
// Update order numbers based on position
const reorderedTabs = items.map((tab, index) => ({
...tab,
order: index + 1,
}));
onReorder(reorderedTabs);
};
return (
<div className="space-y-2">
{tabs.map((tab, index) => (
<DraggableTabItem
key={tab.id}
tab={tab}
index={index}
moveTab={moveTab}
showControls={showControls}
onWindowChange={onWindowChange}
onVisibilityChange={onVisibilityChange}
/>
))}
</div>
);
};

View File

@@ -0,0 +1,380 @@
import { useState, useEffect } from 'react';
import { motion } from 'framer-motion';
import { useStore } from '@nanostores/react';
import { Switch } from '~/components/ui/Switch';
import { classNames } from '~/utils/classNames';
import { tabConfigurationStore } from '~/lib/stores/settings';
import { TAB_LABELS } from '~/components/@settings/core/constants';
import type { TabType } from '~/components/@settings/core/types';
import { toast } from 'react-toastify';
import { TbLayoutGrid } from 'react-icons/tb';
import { useSettingsStore } from '~/lib/stores/settings';
// Define tab icons mapping
const TAB_ICONS: Record<TabType, string> = {
profile: 'i-ph:user-circle-fill',
settings: 'i-ph:gear-six-fill',
notifications: 'i-ph:bell-fill',
features: 'i-ph:star-fill',
data: 'i-ph:database-fill',
'cloud-providers': 'i-ph:cloud-fill',
'local-providers': 'i-ph:desktop-fill',
'service-status': 'i-ph:activity-fill',
connection: 'i-ph:wifi-high-fill',
debug: 'i-ph:bug-fill',
'event-logs': 'i-ph:list-bullets-fill',
update: 'i-ph:arrow-clockwise-fill',
'task-manager': 'i-ph:chart-line-fill',
'tab-management': 'i-ph:squares-four-fill',
};
// Define which tabs are default in user mode
const DEFAULT_USER_TABS: TabType[] = [
'features',
'data',
'cloud-providers',
'local-providers',
'connection',
'notifications',
'event-logs',
];
// Define which tabs can be added to user mode
const OPTIONAL_USER_TABS: TabType[] = ['profile', 'settings', 'task-manager', 'service-status', 'debug', 'update'];
// All available tabs for user mode
const ALL_USER_TABS = [...DEFAULT_USER_TABS, ...OPTIONAL_USER_TABS];
// Define which tabs are beta
const BETA_TABS = new Set<TabType>(['task-manager', 'service-status', 'update', 'local-providers']);
// Beta label component
const BetaLabel = () => (
<span className="px-1.5 py-0.5 text-[10px] rounded-full bg-purple-500/10 text-purple-500 font-medium">BETA</span>
);
export const TabManagement = () => {
const [searchQuery, setSearchQuery] = useState('');
const tabConfiguration = useStore(tabConfigurationStore);
const { setSelectedTab } = useSettingsStore();
const handleTabVisibilityChange = (tabId: TabType, checked: boolean) => {
// Get current tab configuration
const currentTab = tabConfiguration.userTabs.find((tab) => tab.id === tabId);
// If tab doesn't exist in configuration, create it
if (!currentTab) {
const newTab = {
id: tabId,
visible: checked,
window: 'user' as const,
order: tabConfiguration.userTabs.length,
};
const updatedTabs = [...tabConfiguration.userTabs, newTab];
tabConfigurationStore.set({
...tabConfiguration,
userTabs: updatedTabs,
});
toast.success(`Tab ${checked ? 'enabled' : 'disabled'} successfully`);
return;
}
// Check if tab can be enabled in user mode
const canBeEnabled = DEFAULT_USER_TABS.includes(tabId) || OPTIONAL_USER_TABS.includes(tabId);
if (!canBeEnabled && checked) {
toast.error('This tab cannot be enabled in user mode');
return;
}
// Update tab visibility
const updatedTabs = tabConfiguration.userTabs.map((tab) => {
if (tab.id === tabId) {
return { ...tab, visible: checked };
}
return tab;
});
// Update store
tabConfigurationStore.set({
...tabConfiguration,
userTabs: updatedTabs,
});
// Show success message
toast.success(`Tab ${checked ? 'enabled' : 'disabled'} successfully`);
};
// Create a map of existing tab configurations
const tabConfigMap = new Map(tabConfiguration.userTabs.map((tab) => [tab.id, tab]));
// Generate the complete list of tabs, including those not in the configuration
const allTabs = ALL_USER_TABS.map((tabId) => {
return (
tabConfigMap.get(tabId) || {
id: tabId,
visible: false,
window: 'user' as const,
order: -1,
}
);
});
// Filter tabs based on search query
const filteredTabs = allTabs.filter((tab) => TAB_LABELS[tab.id].toLowerCase().includes(searchQuery.toLowerCase()));
useEffect(() => {
// Reset to first tab when component unmounts
return () => {
setSelectedTab('user'); // Reset to user tab when unmounting
};
}, [setSelectedTab]);
return (
<div className="space-y-6">
<motion.div
className="space-y-4"
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ duration: 0.3 }}
>
{/* Header */}
<div className="flex items-center justify-between gap-4 mt-8 mb-4">
<div className="flex items-center gap-2">
<div
className={classNames(
'w-8 h-8 flex items-center justify-center rounded-lg',
'bg-bolt-elements-background-depth-3',
'text-purple-500',
)}
>
<TbLayoutGrid className="w-5 h-5" />
</div>
<div>
<h4 className="text-md font-medium text-bolt-elements-textPrimary">Tab Management</h4>
<p className="text-sm text-bolt-elements-textSecondary">Configure visible tabs and their order</p>
</div>
</div>
{/* Search */}
<div className="relative w-64">
<div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
<div className="i-ph:magnifying-glass w-4 h-4 text-gray-400" />
</div>
<input
type="text"
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
placeholder="Search tabs..."
className={classNames(
'w-full pl-10 pr-4 py-2 rounded-lg',
'bg-bolt-elements-background-depth-2',
'border border-bolt-elements-borderColor',
'text-bolt-elements-textPrimary',
'placeholder-bolt-elements-textTertiary',
'focus:outline-none focus:ring-2 focus:ring-purple-500/30',
'transition-all duration-200',
)}
/>
</div>
</div>
{/* Tab Grid */}
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
{/* Default Section Header */}
{filteredTabs.some((tab) => DEFAULT_USER_TABS.includes(tab.id)) && (
<div className="col-span-full flex items-center gap-2 mt-4 mb-2">
<div className="i-ph:star-fill w-4 h-4 text-purple-500" />
<span className="text-sm font-medium text-bolt-elements-textPrimary">Default Tabs</span>
</div>
)}
{/* Default Tabs */}
{filteredTabs
.filter((tab) => DEFAULT_USER_TABS.includes(tab.id))
.map((tab, index) => (
<motion.div
key={tab.id}
className={classNames(
'rounded-lg border bg-bolt-elements-background text-bolt-elements-textPrimary',
'bg-bolt-elements-background-depth-2',
'hover:bg-bolt-elements-background-depth-3',
'transition-all duration-200',
'relative overflow-hidden group',
)}
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ delay: index * 0.1 }}
whileHover={{ scale: 1.02 }}
>
{/* Status Badges */}
<div className="absolute top-1 right-1.5 flex gap-1">
<span className="px-1.5 py-0.25 text-xs rounded-full bg-purple-500/10 text-purple-500 font-medium mr-2">
Default
</span>
</div>
<div className="flex items-start gap-4 p-4">
<motion.div
className={classNames(
'w-10 h-10 flex items-center justify-center rounded-xl',
'bg-bolt-elements-background-depth-3 group-hover:bg-bolt-elements-background-depth-4',
'transition-all duration-200',
tab.visible ? 'text-purple-500' : 'text-bolt-elements-textSecondary',
)}
whileHover={{ scale: 1.1 }}
whileTap={{ scale: 0.9 }}
>
<div
className={classNames('w-6 h-6', 'transition-transform duration-200', 'group-hover:rotate-12')}
>
<div className={classNames(TAB_ICONS[tab.id], 'w-full h-full')} />
</div>
</motion.div>
<div className="flex-1 min-w-0">
<div className="flex items-center justify-between gap-4">
<div>
<div className="flex items-center gap-2">
<h4 className="text-sm font-medium text-bolt-elements-textPrimary group-hover:text-purple-500 transition-colors">
{TAB_LABELS[tab.id]}
</h4>
{BETA_TABS.has(tab.id) && <BetaLabel />}
</div>
<p className="text-xs text-bolt-elements-textSecondary mt-0.5">
{tab.visible ? 'Visible in user mode' : 'Hidden in user mode'}
</p>
</div>
<Switch
checked={tab.visible}
onCheckedChange={(checked) => {
const isDisabled =
!DEFAULT_USER_TABS.includes(tab.id) && !OPTIONAL_USER_TABS.includes(tab.id);
if (!isDisabled) {
handleTabVisibilityChange(tab.id, checked);
}
}}
className={classNames('data-[state=checked]:bg-purple-500 ml-4', {
'opacity-50 pointer-events-none':
!DEFAULT_USER_TABS.includes(tab.id) && !OPTIONAL_USER_TABS.includes(tab.id),
})}
/>
</div>
</div>
</div>
<motion.div
className="absolute inset-0 border-2 border-purple-500/0 rounded-lg pointer-events-none"
animate={{
borderColor: tab.visible ? 'rgba(168, 85, 247, 0.2)' : 'rgba(168, 85, 247, 0)',
scale: tab.visible ? 1 : 0.98,
}}
transition={{ duration: 0.2 }}
/>
</motion.div>
))}
{/* Optional Section Header */}
{filteredTabs.some((tab) => OPTIONAL_USER_TABS.includes(tab.id)) && (
<div className="col-span-full flex items-center gap-2 mt-8 mb-2">
<div className="i-ph:plus-circle-fill w-4 h-4 text-blue-500" />
<span className="text-sm font-medium text-bolt-elements-textPrimary">Optional Tabs</span>
</div>
)}
{/* Optional Tabs */}
{filteredTabs
.filter((tab) => OPTIONAL_USER_TABS.includes(tab.id))
.map((tab, index) => (
<motion.div
key={tab.id}
className={classNames(
'rounded-lg border bg-bolt-elements-background text-bolt-elements-textPrimary',
'bg-bolt-elements-background-depth-2',
'hover:bg-bolt-elements-background-depth-3',
'transition-all duration-200',
'relative overflow-hidden group',
)}
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ delay: index * 0.1 }}
whileHover={{ scale: 1.02 }}
>
{/* Status Badges */}
<div className="absolute top-1 right-1.5 flex gap-1">
<span className="px-1.5 py-0.25 text-xs rounded-full bg-blue-500/10 text-blue-500 font-medium mr-2">
Optional
</span>
</div>
<div className="flex items-start gap-4 p-4">
<motion.div
className={classNames(
'w-10 h-10 flex items-center justify-center rounded-xl',
'bg-bolt-elements-background-depth-3 group-hover:bg-bolt-elements-background-depth-4',
'transition-all duration-200',
tab.visible ? 'text-purple-500' : 'text-bolt-elements-textSecondary',
)}
whileHover={{ scale: 1.1 }}
whileTap={{ scale: 0.9 }}
>
<div
className={classNames('w-6 h-6', 'transition-transform duration-200', 'group-hover:rotate-12')}
>
<div className={classNames(TAB_ICONS[tab.id], 'w-full h-full')} />
</div>
</motion.div>
<div className="flex-1 min-w-0">
<div className="flex items-center justify-between gap-4">
<div>
<div className="flex items-center gap-2">
<h4 className="text-sm font-medium text-bolt-elements-textPrimary group-hover:text-purple-500 transition-colors">
{TAB_LABELS[tab.id]}
</h4>
{BETA_TABS.has(tab.id) && <BetaLabel />}
</div>
<p className="text-xs text-bolt-elements-textSecondary mt-0.5">
{tab.visible ? 'Visible in user mode' : 'Hidden in user mode'}
</p>
</div>
<Switch
checked={tab.visible}
onCheckedChange={(checked) => {
const isDisabled =
!DEFAULT_USER_TABS.includes(tab.id) && !OPTIONAL_USER_TABS.includes(tab.id);
if (!isDisabled) {
handleTabVisibilityChange(tab.id, checked);
}
}}
className={classNames('data-[state=checked]:bg-purple-500 ml-4', {
'opacity-50 pointer-events-none':
!DEFAULT_USER_TABS.includes(tab.id) && !OPTIONAL_USER_TABS.includes(tab.id),
})}
/>
</div>
</div>
</div>
<motion.div
className="absolute inset-0 border-2 border-purple-500/0 rounded-lg pointer-events-none"
animate={{
borderColor: tab.visible ? 'rgba(168, 85, 247, 0.2)' : 'rgba(168, 85, 247, 0)',
scale: tab.visible ? 1 : 0.98,
}}
transition={{ duration: 0.2 }}
/>
</motion.div>
))}
</div>
</motion.div>
</div>
);
};

View File

@@ -0,0 +1,135 @@
import { motion } from 'framer-motion';
import * as Tooltip from '@radix-ui/react-tooltip';
import { classNames } from '~/utils/classNames';
import type { TabVisibilityConfig } from '~/components/@settings/core/types';
import { TAB_LABELS, TAB_ICONS } from '~/components/@settings/core/constants';
interface TabTileProps {
tab: TabVisibilityConfig;
onClick?: () => void;
isActive?: boolean;
hasUpdate?: boolean;
statusMessage?: string;
description?: string;
isLoading?: boolean;
className?: string;
children?: React.ReactNode;
}
export const TabTile: React.FC<TabTileProps> = ({
tab,
onClick,
isActive,
hasUpdate,
statusMessage,
description,
isLoading,
className,
children,
}: TabTileProps) => {
return (
<Tooltip.Provider delayDuration={200}>
<Tooltip.Root>
<Tooltip.Trigger asChild>
<motion.div
onClick={onClick}
className={classNames(
'relative flex flex-col items-center p-6 rounded-xl',
'w-full h-full min-h-[160px]',
'bg-white dark:bg-[#141414]',
'border border-[#E5E5E5] dark:border-[#333333]',
'group',
'hover:bg-purple-50 dark:hover:bg-[#1a1a1a]',
'hover:border-purple-200 dark:hover:border-purple-900/30',
isActive ? 'border-purple-500 dark:border-purple-500/50 bg-purple-500/5 dark:bg-purple-500/10' : '',
isLoading ? 'cursor-wait opacity-70' : '',
className || '',
)}
>
{/* Main Content */}
<div className="flex flex-col items-center justify-center flex-1 w-full">
{/* Icon */}
<motion.div
className={classNames(
'relative',
'w-14 h-14',
'flex items-center justify-center',
'rounded-xl',
'bg-gray-100 dark:bg-gray-800',
'ring-1 ring-gray-200 dark:ring-gray-700',
'group-hover:bg-purple-100 dark:group-hover:bg-gray-700/80',
'group-hover:ring-purple-200 dark:group-hover:ring-purple-800/30',
isActive ? 'bg-purple-500/10 dark:bg-purple-500/10 ring-purple-500/30 dark:ring-purple-500/20' : '',
)}
>
<motion.div
className={classNames(
TAB_ICONS[tab.id],
'w-8 h-8',
'text-gray-600 dark:text-gray-300',
'group-hover:text-purple-500 dark:group-hover:text-purple-400/80',
isActive ? 'text-purple-500 dark:text-purple-400/90' : '',
)}
/>
</motion.div>
{/* Label and Description */}
<div className="flex flex-col items-center mt-5 w-full">
<h3
className={classNames(
'text-[15px] font-medium leading-snug mb-2',
'text-gray-700 dark:text-gray-200',
'group-hover:text-purple-600 dark:group-hover:text-purple-300/90',
isActive ? 'text-purple-500 dark:text-purple-400/90' : '',
)}
>
{TAB_LABELS[tab.id]}
</h3>
{description && (
<p
className={classNames(
'text-[13px] leading-relaxed',
'text-gray-500 dark:text-gray-400',
'max-w-[85%]',
'text-center',
'group-hover:text-purple-500 dark:group-hover:text-purple-400/70',
isActive ? 'text-purple-400 dark:text-purple-400/80' : '',
)}
>
{description}
</p>
)}
</div>
</div>
{/* Update Indicator with Tooltip */}
{hasUpdate && (
<>
<div className="absolute top-4 right-4 w-2 h-2 rounded-full bg-purple-500 dark:bg-purple-400 animate-pulse" />
<Tooltip.Portal>
<Tooltip.Content
className={classNames(
'px-3 py-1.5 rounded-lg',
'bg-[#18181B] text-white',
'text-sm font-medium',
'select-none',
'z-[100]',
)}
side="top"
sideOffset={5}
>
{statusMessage}
<Tooltip.Arrow className="fill-[#18181B]" />
</Tooltip.Content>
</Tooltip.Portal>
</>
)}
{/* Children (e.g. Beta Label) */}
{children}
</motion.div>
</Tooltip.Trigger>
</Tooltip.Root>
</Tooltip.Provider>
);
};

View File

@@ -0,0 +1,595 @@
import React, { useState } from 'react';
import { toast } from 'react-toastify';
import { Button } from '~/components/ui/Button';
import { Badge } from '~/components/ui/Badge';
import { classNames } from '~/utils/classNames';
import { Collapsible, CollapsibleTrigger, CollapsibleContent } from '~/components/ui/Collapsible';
import { CodeBracketIcon, ChevronDownIcon } from '@heroicons/react/24/outline';
// Helper function to safely parse JSON
const safeJsonParse = (item: string | null) => {
if (!item) {
return null;
}
try {
return JSON.parse(item);
} catch (e) {
console.error('Failed to parse JSON from localStorage:', e);
return null;
}
};
/**
* A diagnostics component to help troubleshoot connection issues
*/
export default function ConnectionDiagnostics() {
const [diagnosticResults, setDiagnosticResults] = useState<any>(null);
const [isRunning, setIsRunning] = useState(false);
const [showDetails, setShowDetails] = useState(false);
// Run diagnostics when requested
const runDiagnostics = async () => {
try {
setIsRunning(true);
setDiagnosticResults(null);
// Check browser-side storage
const localStorageChecks = {
githubConnection: localStorage.getItem('github_connection'),
netlifyConnection: localStorage.getItem('netlify_connection'),
vercelConnection: localStorage.getItem('vercel_connection'),
supabaseConnection: localStorage.getItem('supabase_connection'),
};
// Get diagnostic data from server
const response = await fetch('/api/system/diagnostics');
if (!response.ok) {
throw new Error(`Diagnostics API error: ${response.status}`);
}
const serverDiagnostics = await response.json();
// === GitHub Checks ===
const githubConnectionParsed = safeJsonParse(localStorageChecks.githubConnection);
const githubToken = githubConnectionParsed?.token;
const githubAuthHeaders = {
...(githubToken ? { Authorization: `Bearer ${githubToken}` } : {}),
'Content-Type': 'application/json',
};
console.log('Testing GitHub endpoints with token:', githubToken ? 'present' : 'missing');
const githubEndpoints = [
{ name: 'User', url: '/api/system/git-info?action=getUser' },
{ name: 'Repos', url: '/api/system/git-info?action=getRepos' },
{ name: 'Default', url: '/api/system/git-info' },
];
const githubResults = await Promise.all(
githubEndpoints.map(async (endpoint) => {
try {
const resp = await fetch(endpoint.url, { headers: githubAuthHeaders });
return { endpoint: endpoint.name, status: resp.status, ok: resp.ok };
} catch (error) {
return {
endpoint: endpoint.name,
error: error instanceof Error ? error.message : String(error),
ok: false,
};
}
}),
);
// === Netlify Checks ===
const netlifyConnectionParsed = safeJsonParse(localStorageChecks.netlifyConnection);
const netlifyToken = netlifyConnectionParsed?.token;
let netlifyUserCheck = null;
if (netlifyToken) {
try {
const netlifyResp = await fetch('https://api.netlify.com/api/v1/user', {
headers: { Authorization: `Bearer ${netlifyToken}` },
});
netlifyUserCheck = { status: netlifyResp.status, ok: netlifyResp.ok };
} catch (error) {
netlifyUserCheck = {
error: error instanceof Error ? error.message : String(error),
ok: false,
};
}
}
// === Vercel Checks ===
const vercelConnectionParsed = safeJsonParse(localStorageChecks.vercelConnection);
const vercelToken = vercelConnectionParsed?.token;
let vercelUserCheck = null;
if (vercelToken) {
try {
const vercelResp = await fetch('https://api.vercel.com/v2/user', {
headers: { Authorization: `Bearer ${vercelToken}` },
});
vercelUserCheck = { status: vercelResp.status, ok: vercelResp.ok };
} catch (error) {
vercelUserCheck = {
error: error instanceof Error ? error.message : String(error),
ok: false,
};
}
}
// === Supabase Checks ===
const supabaseConnectionParsed = safeJsonParse(localStorageChecks.supabaseConnection);
const supabaseUrl = supabaseConnectionParsed?.projectUrl;
const supabaseAnonKey = supabaseConnectionParsed?.anonKey;
let supabaseCheck = null;
if (supabaseUrl && supabaseAnonKey) {
supabaseCheck = { ok: true, status: 200, message: 'URL and Key present in localStorage' };
} else {
supabaseCheck = { ok: false, message: 'URL or Key missing in localStorage' };
}
// Compile results
const results = {
timestamp: new Date().toISOString(),
localStorage: {
hasGithubConnection: Boolean(localStorageChecks.githubConnection),
hasNetlifyConnection: Boolean(localStorageChecks.netlifyConnection),
hasVercelConnection: Boolean(localStorageChecks.vercelConnection),
hasSupabaseConnection: Boolean(localStorageChecks.supabaseConnection),
githubConnectionParsed,
netlifyConnectionParsed,
vercelConnectionParsed,
supabaseConnectionParsed,
},
apiEndpoints: {
github: githubResults,
netlify: netlifyUserCheck,
vercel: vercelUserCheck,
supabase: supabaseCheck,
},
serverDiagnostics,
};
setDiagnosticResults(results);
// Display simple results
if (results.localStorage.hasGithubConnection && results.apiEndpoints.github.some((r: { ok: boolean }) => !r.ok)) {
toast.error('GitHub API connections are failing. Try reconnecting.');
}
if (results.localStorage.hasNetlifyConnection && netlifyUserCheck && !netlifyUserCheck.ok) {
toast.error('Netlify API connection is failing. Try reconnecting.');
}
if (results.localStorage.hasVercelConnection && vercelUserCheck && !vercelUserCheck.ok) {
toast.error('Vercel API connection is failing. Try reconnecting.');
}
if (results.localStorage.hasSupabaseConnection && supabaseCheck && !supabaseCheck.ok) {
toast.warning('Supabase connection check failed or missing details. Verify settings.');
}
if (
!results.localStorage.hasGithubConnection &&
!results.localStorage.hasNetlifyConnection &&
!results.localStorage.hasVercelConnection &&
!results.localStorage.hasSupabaseConnection
) {
toast.info('No connection data found in browser storage.');
}
} catch (error) {
console.error('Diagnostics error:', error);
toast.error('Error running diagnostics');
setDiagnosticResults({ error: error instanceof Error ? error.message : String(error) });
} finally {
setIsRunning(false);
}
};
// Helper to reset GitHub connection
const resetGitHubConnection = () => {
try {
localStorage.removeItem('github_connection');
document.cookie = 'githubToken=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;';
document.cookie = 'githubUsername=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;';
document.cookie = 'git:github.com=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;';
toast.success('GitHub connection data cleared. Please refresh the page and reconnect.');
setDiagnosticResults(null);
} catch (error) {
console.error('Error clearing GitHub data:', error);
toast.error('Failed to clear GitHub connection data');
}
};
// Helper to reset Netlify connection
const resetNetlifyConnection = () => {
try {
localStorage.removeItem('netlify_connection');
document.cookie = 'netlifyToken=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;';
toast.success('Netlify connection data cleared. Please refresh the page and reconnect.');
setDiagnosticResults(null);
} catch (error) {
console.error('Error clearing Netlify data:', error);
toast.error('Failed to clear Netlify connection data');
}
};
// Helper to reset Vercel connection
const resetVercelConnection = () => {
try {
localStorage.removeItem('vercel_connection');
toast.success('Vercel connection data cleared. Please refresh the page and reconnect.');
setDiagnosticResults(null);
} catch (error) {
console.error('Error clearing Vercel data:', error);
toast.error('Failed to clear Vercel connection data');
}
};
// Helper to reset Supabase connection
const resetSupabaseConnection = () => {
try {
localStorage.removeItem('supabase_connection');
toast.success('Supabase connection data cleared. Please refresh the page and reconnect.');
setDiagnosticResults(null);
} catch (error) {
console.error('Error clearing Supabase data:', error);
toast.error('Failed to clear Supabase connection data');
}
};
return (
<div className="flex flex-col gap-6">
{/* Connection Status Cards */}
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
{/* GitHub Connection Card */}
<div className="p-4 rounded-lg bg-bolt-elements-background dark:bg-bolt-elements-background-depth-2 border border-bolt-elements-borderColor dark:border-bolt-elements-borderColor hover:border-bolt-elements-borderColorActive/70 dark:hover:border-bolt-elements-borderColorActive/70 transition-all duration-200 h-[180px] flex flex-col">
<div className="flex items-center gap-2">
<div className="i-ph:github-logo text-bolt-elements-item-contentAccent dark:text-bolt-elements-item-contentAccent w-4 h-4" />
<div className="text-sm font-medium text-bolt-elements-textPrimary dark:text-bolt-elements-textPrimary">
GitHub Connection
</div>
</div>
{diagnosticResults ? (
<>
<div className="flex items-center gap-2 mt-2">
<span
className={classNames(
'text-xl font-semibold',
diagnosticResults.localStorage.hasGithubConnection
? 'text-green-500 dark:text-green-400'
: 'text-red-500 dark:text-red-400',
)}
>
{diagnosticResults.localStorage.hasGithubConnection ? 'Connected' : 'Not Connected'}
</span>
</div>
{diagnosticResults.localStorage.hasGithubConnection && (
<>
<div className="text-xs text-bolt-elements-textSecondary dark:text-bolt-elements-textSecondary mt-2 flex items-center gap-1.5">
<div className="i-ph:user w-3.5 h-3.5 text-bolt-elements-item-contentAccent dark:text-bolt-elements-item-contentAccent" />
User: {diagnosticResults.localStorage.githubConnectionParsed?.user?.login || 'N/A'}
</div>
<div className="text-xs text-bolt-elements-textSecondary dark:text-bolt-elements-textSecondary mt-2 flex items-center gap-1.5">
<div className="i-ph:check-circle w-3.5 h-3.5 text-bolt-elements-item-contentAccent dark:text-bolt-elements-item-contentAccent" />
API Status:{' '}
<Badge
variant={
diagnosticResults.apiEndpoints.github.every((r: { ok: boolean }) => r.ok)
? 'default'
: 'destructive'
}
className="ml-1"
>
{diagnosticResults.apiEndpoints.github.every((r: { ok: boolean }) => r.ok) ? 'OK' : 'Failed'}
</Badge>
</div>
</>
)}
{!diagnosticResults.localStorage.hasGithubConnection && (
<Button
onClick={() => window.location.reload()}
variant="outline"
size="sm"
className="mt-auto self-start hover:bg-bolt-elements-item-backgroundActive/10 hover:text-bolt-elements-textPrimary dark:hover:bg-bolt-elements-item-backgroundActive/10 dark:hover:text-bolt-elements-textPrimary transition-colors"
>
<div className="i-ph:plug w-3.5 h-3.5 mr-1" />
Connect Now
</Button>
)}
</>
) : (
<div className="flex items-center justify-center h-full">
<div className="text-sm text-bolt-elements-textSecondary dark:text-bolt-elements-textSecondary flex items-center gap-2">
<div className="i-ph:info w-4 h-4" />
Run diagnostics to check connection status
</div>
</div>
)}
</div>
{/* Netlify Connection Card */}
<div className="p-4 rounded-lg bg-bolt-elements-background dark:bg-bolt-elements-background-depth-2 border border-bolt-elements-borderColor dark:border-bolt-elements-borderColor hover:border-bolt-elements-borderColorActive/70 dark:hover:border-bolt-elements-borderColorActive/70 transition-all duration-200 h-[180px] flex flex-col">
<div className="flex items-center gap-2">
<div className="i-bolt:netlify text-bolt-elements-item-contentAccent dark:text-bolt-elements-item-contentAccent w-4 h-4" />
<div className="text-sm font-medium text-bolt-elements-textPrimary dark:text-bolt-elements-textPrimary">
Netlify Connection
</div>
</div>
{diagnosticResults ? (
<>
<div className="flex items-center gap-2 mt-2">
<span
className={classNames(
'text-xl font-semibold',
diagnosticResults.localStorage.hasNetlifyConnection
? 'text-green-500 dark:text-green-400'
: 'text-red-500 dark:text-red-400',
)}
>
{diagnosticResults.localStorage.hasNetlifyConnection ? 'Connected' : 'Not Connected'}
</span>
</div>
{diagnosticResults.localStorage.hasNetlifyConnection && (
<>
<div className="text-xs text-bolt-elements-textSecondary dark:text-bolt-elements-textSecondary mt-2 flex items-center gap-1.5">
<div className="i-ph:user w-3.5 h-3.5 text-bolt-elements-item-contentAccent dark:text-bolt-elements-item-contentAccent" />
User:{' '}
{diagnosticResults.localStorage.netlifyConnectionParsed?.user?.full_name ||
diagnosticResults.localStorage.netlifyConnectionParsed?.user?.email ||
'N/A'}
</div>
<div className="text-xs text-bolt-elements-textSecondary dark:text-bolt-elements-textSecondary mt-2 flex items-center gap-1.5">
<div className="i-ph:check-circle w-3.5 h-3.5 text-bolt-elements-item-contentAccent dark:text-bolt-elements-item-contentAccent" />
API Status:{' '}
<Badge
variant={diagnosticResults.apiEndpoints.netlify?.ok ? 'default' : 'destructive'}
className="ml-1"
>
{diagnosticResults.apiEndpoints.netlify?.ok ? 'OK' : 'Failed'}
</Badge>
</div>
</>
)}
{!diagnosticResults.localStorage.hasNetlifyConnection && (
<Button
onClick={() => window.location.reload()}
variant="outline"
size="sm"
className="mt-auto self-start hover:bg-bolt-elements-item-backgroundActive/10 hover:text-bolt-elements-textPrimary dark:hover:bg-bolt-elements-item-backgroundActive/10 dark:hover:text-bolt-elements-textPrimary transition-colors"
>
<div className="i-ph:plug w-3.5 h-3.5 mr-1" />
Connect Now
</Button>
)}
</>
) : (
<div className="flex items-center justify-center h-full">
<div className="text-sm text-bolt-elements-textSecondary dark:text-bolt-elements-textSecondary flex items-center gap-2">
<div className="i-ph:info w-4 h-4" />
Run diagnostics to check connection status
</div>
</div>
)}
</div>
{/* Vercel Connection Card */}
<div className="p-4 rounded-lg bg-bolt-elements-background dark:bg-bolt-elements-background-depth-2 border border-bolt-elements-borderColor dark:border-bolt-elements-borderColor hover:border-bolt-elements-borderColorActive/70 dark:hover:border-bolt-elements-borderColorActive/70 transition-all duration-200 h-[180px] flex flex-col">
<div className="flex items-center gap-2">
<div className="i-si:vercel text-bolt-elements-item-contentAccent dark:text-bolt-elements-item-contentAccent w-4 h-4" />
<div className="text-sm font-medium text-bolt-elements-textPrimary dark:text-bolt-elements-textPrimary">
Vercel Connection
</div>
</div>
{diagnosticResults ? (
<>
<div className="flex items-center gap-2 mt-2">
<span
className={classNames(
'text-xl font-semibold',
diagnosticResults.localStorage.hasVercelConnection
? 'text-green-500 dark:text-green-400'
: 'text-red-500 dark:text-red-400',
)}
>
{diagnosticResults.localStorage.hasVercelConnection ? 'Connected' : 'Not Connected'}
</span>
</div>
{diagnosticResults.localStorage.hasVercelConnection && (
<>
<div className="text-xs text-bolt-elements-textSecondary dark:text-bolt-elements-textSecondary mt-2 flex items-center gap-1.5">
<div className="i-ph:user w-3.5 h-3.5 text-bolt-elements-item-contentAccent dark:text-bolt-elements-item-contentAccent" />
User:{' '}
{diagnosticResults.localStorage.vercelConnectionParsed?.user?.username ||
diagnosticResults.localStorage.vercelConnectionParsed?.user?.user?.username ||
'N/A'}
</div>
<div className="text-xs text-bolt-elements-textSecondary dark:text-bolt-elements-textSecondary mt-2 flex items-center gap-1.5">
<div className="i-ph:check-circle w-3.5 h-3.5 text-bolt-elements-item-contentAccent dark:text-bolt-elements-item-contentAccent" />
API Status:{' '}
<Badge
variant={diagnosticResults.apiEndpoints.vercel?.ok ? 'default' : 'destructive'}
className="ml-1"
>
{diagnosticResults.apiEndpoints.vercel?.ok ? 'OK' : 'Failed'}
</Badge>
</div>
</>
)}
{!diagnosticResults.localStorage.hasVercelConnection && (
<Button
onClick={() => window.location.reload()}
variant="outline"
size="sm"
className="mt-auto self-start hover:bg-bolt-elements-item-backgroundActive/10 hover:text-bolt-elements-textPrimary dark:hover:bg-bolt-elements-item-backgroundActive/10 dark:hover:text-bolt-elements-textPrimary transition-colors"
>
<div className="i-ph:plug w-3.5 h-3.5 mr-1" />
Connect Now
</Button>
)}
</>
) : (
<div className="flex items-center justify-center h-full">
<div className="text-sm text-bolt-elements-textSecondary dark:text-bolt-elements-textSecondary flex items-center gap-2">
<div className="i-ph:info w-4 h-4" />
Run diagnostics to check connection status
</div>
</div>
)}
</div>
{/* Supabase Connection Card */}
<div className="p-4 rounded-lg bg-bolt-elements-background dark:bg-bolt-elements-background-depth-2 border border-bolt-elements-borderColor dark:border-bolt-elements-borderColor hover:border-bolt-elements-borderColorActive/70 dark:hover:border-bolt-elements-borderColorActive/70 transition-all duration-200 h-[180px] flex flex-col">
<div className="flex items-center gap-2">
<div className="i-si:supabase text-bolt-elements-item-contentAccent dark:text-bolt-elements-item-contentAccent w-4 h-4" />
<div className="text-sm font-medium text-bolt-elements-textPrimary dark:text-bolt-elements-textPrimary">
Supabase Connection
</div>
</div>
{diagnosticResults ? (
<>
<div className="flex items-center gap-2 mt-2">
<span
className={classNames(
'text-xl font-semibold',
diagnosticResults.localStorage.hasSupabaseConnection
? 'text-green-500 dark:text-green-400'
: 'text-red-500 dark:text-red-400',
)}
>
{diagnosticResults.localStorage.hasSupabaseConnection ? 'Configured' : 'Not Configured'}
</span>
</div>
{diagnosticResults.localStorage.hasSupabaseConnection && (
<>
<div className="text-xs text-bolt-elements-textSecondary dark:text-bolt-elements-textSecondary mt-2 flex items-center gap-1.5 truncate">
<div className="i-ph:link w-3.5 h-3.5 text-bolt-elements-item-contentAccent dark:text-bolt-elements-item-contentAccent flex-shrink-0" />
Project URL: {diagnosticResults.localStorage.supabaseConnectionParsed?.projectUrl || 'N/A'}
</div>
<div className="text-xs text-bolt-elements-textSecondary dark:text-bolt-elements-textSecondary mt-2 flex items-center gap-1.5">
<div className="i-ph:check-circle w-3.5 h-3.5 text-bolt-elements-item-contentAccent dark:text-bolt-elements-item-contentAccent" />
Config Status:{' '}
<Badge
variant={diagnosticResults.apiEndpoints.supabase?.ok ? 'default' : 'destructive'}
className="ml-1"
>
{diagnosticResults.apiEndpoints.supabase?.ok ? 'OK' : 'Check Failed'}
</Badge>
</div>
</>
)}
{!diagnosticResults.localStorage.hasSupabaseConnection && (
<Button
onClick={() => window.location.reload()}
variant="outline"
size="sm"
className="mt-auto self-start hover:bg-bolt-elements-item-backgroundActive/10 hover:text-bolt-elements-textPrimary dark:hover:bg-bolt-elements-item-backgroundActive/10 dark:hover:text-bolt-elements-textPrimary transition-colors"
>
<div className="i-ph:plug w-3.5 h-3.5 mr-1" />
Configure Now
</Button>
)}
</>
) : (
<div className="flex items-center justify-center h-full">
<div className="text-sm text-bolt-elements-textSecondary dark:text-bolt-elements-textSecondary flex items-center gap-2">
<div className="i-ph:info w-4 h-4" />
Run diagnostics to check connection status
</div>
</div>
)}
</div>
</div>
{/* Action Buttons */}
<div className="flex flex-wrap gap-4">
<Button
onClick={runDiagnostics}
disabled={isRunning}
variant="outline"
className="flex items-center gap-2 hover:bg-bolt-elements-item-backgroundActive/10 hover:text-bolt-elements-textPrimary dark:hover:bg-bolt-elements-item-backgroundActive/10 dark:hover:text-bolt-elements-textPrimary transition-colors"
>
{isRunning ? (
<div className="i-ph:spinner-gap w-4 h-4 animate-spin" />
) : (
<div className="i-ph:activity w-4 h-4" />
)}
{isRunning ? 'Running Diagnostics...' : 'Run Diagnostics'}
</Button>
<Button
onClick={resetGitHubConnection}
disabled={isRunning || !diagnosticResults?.localStorage.hasGithubConnection}
variant="outline"
className="flex items-center gap-2 hover:bg-bolt-elements-item-backgroundActive/10 hover:text-bolt-elements-textPrimary dark:hover:bg-bolt-elements-item-backgroundActive/10 dark:hover:text-bolt-elements-textPrimary transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
>
<div className="i-ph:github-logo w-4 h-4" />
Reset GitHub
</Button>
<Button
onClick={resetNetlifyConnection}
disabled={isRunning || !diagnosticResults?.localStorage.hasNetlifyConnection}
variant="outline"
className="flex items-center gap-2 hover:bg-bolt-elements-item-backgroundActive/10 hover:text-bolt-elements-textPrimary dark:hover:bg-bolt-elements-item-backgroundActive/10 dark:hover:text-bolt-elements-textPrimary transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
>
<div className="i-si:netlify w-4 h-4" />
Reset Netlify
</Button>
<Button
onClick={resetVercelConnection}
disabled={isRunning || !diagnosticResults?.localStorage.hasVercelConnection}
variant="outline"
className="flex items-center gap-2 hover:bg-bolt-elements-item-backgroundActive/10 hover:text-bolt-elements-textPrimary dark:hover:bg-bolt-elements-item-backgroundActive/10 dark:hover:text-bolt-elements-textPrimary transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
>
<div className="i-si:vercel w-4 h-4" />
Reset Vercel
</Button>
<Button
onClick={resetSupabaseConnection}
disabled={isRunning || !diagnosticResults?.localStorage.hasSupabaseConnection}
variant="outline"
className="flex items-center gap-2 hover:bg-bolt-elements-item-backgroundActive/10 hover:text-bolt-elements-textPrimary dark:hover:bg-bolt-elements-item-backgroundActive/10 dark:hover:text-bolt-elements-textPrimary transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
>
<div className="i-si:supabase w-4 h-4" />
Reset Supabase
</Button>
</div>
{/* Details Panel */}
{diagnosticResults && (
<div className="mt-4">
<Collapsible open={showDetails} onOpenChange={setShowDetails} className="w-full">
<CollapsibleTrigger className="w-full">
<div className="flex items-center justify-between p-4 rounded-lg bg-bolt-elements-background dark:bg-bolt-elements-background-depth-2 border border-bolt-elements-borderColor dark:border-bolt-elements-borderColor hover:border-bolt-elements-borderColorActive/70 dark:hover:border-bolt-elements-borderColorActive/70 transition-all duration-200">
<div className="flex items-center gap-2">
<CodeBracketIcon className="w-4 h-4 text-blue-500" />
<span className="text-sm font-medium text-bolt-elements-textPrimary dark:text-bolt-elements-textPrimary">
Diagnostic Details
</span>
</div>
<ChevronDownIcon
className={classNames(
'w-4 h-4 transform transition-transform duration-200 text-bolt-elements-textSecondary dark:text-bolt-elements-textSecondary',
showDetails ? 'rotate-180' : '',
)}
/>
</div>
</CollapsibleTrigger>
<CollapsibleContent className="overflow-hidden">
<div className="p-4 mt-2 rounded-lg bg-bolt-elements-background-depth-2 dark:bg-bolt-elements-background-depth-1 border border-bolt-elements-borderColor dark:border-bolt-elements-borderColor">
<pre className="text-xs overflow-auto max-h-96 text-bolt-elements-textSecondary dark:text-bolt-elements-textSecondary">
{JSON.stringify(diagnosticResults, null, 2)}
</pre>
</div>
</CollapsibleContent>
</Collapsible>
</div>
)}
</div>
);
}

View File

@@ -0,0 +1,184 @@
import { motion } from 'framer-motion';
import React, { Suspense, useState } from 'react';
import { classNames } from '~/utils/classNames';
import ConnectionDiagnostics from './ConnectionDiagnostics';
import { Button } from '~/components/ui/Button';
import VercelConnection from './VercelConnection';
// Use React.lazy for dynamic imports
const GitHubConnection = React.lazy(() => import('./GithubConnection'));
const NetlifyConnection = React.lazy(() => import('./NetlifyConnection'));
// Loading fallback component
const LoadingFallback = () => (
<div className="p-4 bg-bolt-elements-background-depth-1 dark:bg-bolt-elements-background-depth-1 rounded-lg border border-bolt-elements-borderColor dark:border-bolt-elements-borderColor">
<div className="flex items-center justify-center gap-2 text-bolt-elements-textSecondary dark:text-bolt-elements-textSecondary">
<div className="i-ph:spinner-gap w-4 h-4 animate-spin" />
<span>Loading connection...</span>
</div>
</div>
);
export default function ConnectionsTab() {
const [isEnvVarsExpanded, setIsEnvVarsExpanded] = useState(false);
const [showDiagnostics, setShowDiagnostics] = useState(false);
return (
<div className="space-y-6">
{/* Header */}
<motion.div
className="flex items-center justify-between gap-2"
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ delay: 0.1 }}
>
<div className="flex items-center gap-2">
<div className="i-ph:plugs-connected w-5 h-5 text-bolt-elements-item-contentAccent dark:text-bolt-elements-item-contentAccent" />
<h2 className="text-lg font-medium text-bolt-elements-textPrimary dark:text-bolt-elements-textPrimary">
Connection Settings
</h2>
</div>
<Button
onClick={() => setShowDiagnostics(!showDiagnostics)}
variant="outline"
className="flex items-center gap-2 hover:bg-bolt-elements-item-backgroundActive/10 hover:text-bolt-elements-textPrimary dark:hover:bg-bolt-elements-item-backgroundActive/10 dark:hover:text-bolt-elements-textPrimary transition-colors"
>
{showDiagnostics ? (
<>
<div className="i-ph:eye-slash w-4 h-4" />
Hide Diagnostics
</>
) : (
<>
<div className="i-ph:wrench w-4 h-4" />
Troubleshoot Connections
</>
)}
</Button>
</motion.div>
<p className="text-sm text-bolt-elements-textSecondary dark:text-bolt-elements-textSecondary">
Manage your external service connections and integrations
</p>
{/* Diagnostics Tool - Conditionally rendered */}
{showDiagnostics && <ConnectionDiagnostics />}
{/* Environment Variables Info - Collapsible */}
<motion.div
className="bg-bolt-elements-background dark:bg-bolt-elements-background rounded-lg border border-bolt-elements-borderColor dark:border-bolt-elements-borderColor"
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ delay: 0.2 }}
>
<div className="p-6">
<button
onClick={() => setIsEnvVarsExpanded(!isEnvVarsExpanded)}
className={classNames(
'w-full bg-transparent flex items-center justify-between',
'hover:bg-bolt-elements-item-backgroundActive/10 hover:text-bolt-elements-textPrimary',
'dark:hover:bg-bolt-elements-item-backgroundActive/10 dark:hover:text-bolt-elements-textPrimary',
'rounded-md p-2 -m-2 transition-colors',
)}
>
<div className="flex items-center gap-2">
<div className="i-ph:info w-5 h-5 text-bolt-elements-item-contentAccent dark:text-bolt-elements-item-contentAccent" />
<h3 className="text-base font-medium text-bolt-elements-textPrimary dark:text-bolt-elements-textPrimary">
Environment Variables
</h3>
</div>
<div
className={classNames(
'i-ph:caret-down w-4 h-4 text-bolt-elements-textSecondary dark:text-bolt-elements-textSecondary transition-transform',
isEnvVarsExpanded ? 'rotate-180' : '',
)}
/>
</button>
{isEnvVarsExpanded && (
<div className="mt-4">
<p className="text-sm text-bolt-elements-textSecondary dark:text-bolt-elements-textSecondary mb-2">
You can configure connections using environment variables in your{' '}
<code className="px-1 py-0.5 bg-bolt-elements-background-depth-2 dark:bg-bolt-elements-background-depth-2 rounded">
.env.local
</code>{' '}
file:
</p>
<div className="bg-bolt-elements-background-depth-2 dark:bg-bolt-elements-background-depth-2 p-3 rounded-md text-xs font-mono overflow-x-auto">
<div className="text-bolt-elements-textSecondary dark:text-bolt-elements-textSecondary">
# GitHub Authentication
</div>
<div className="text-bolt-elements-textPrimary dark:text-bolt-elements-textPrimary">
VITE_GITHUB_ACCESS_TOKEN=your_token_here
</div>
<div className="text-bolt-elements-textSecondary dark:text-bolt-elements-textSecondary">
# Optional: Specify token type (defaults to 'classic' if not specified)
</div>
<div className="text-bolt-elements-textPrimary dark:text-bolt-elements-textPrimary">
VITE_GITHUB_TOKEN_TYPE=classic|fine-grained
</div>
<div className="text-bolt-elements-textSecondary dark:text-bolt-elements-textSecondary mt-2">
# Netlify Authentication
</div>
<div className="text-bolt-elements-textPrimary dark:text-bolt-elements-textPrimary">
VITE_NETLIFY_ACCESS_TOKEN=your_token_here
</div>
</div>
<div className="mt-3 text-xs text-bolt-elements-textSecondary dark:text-bolt-elements-textSecondary space-y-1">
<p>
<span className="font-medium">Token types:</span>
</p>
<ul className="list-disc list-inside pl-2 space-y-1">
<li>
<span className="font-medium">classic</span> - Personal Access Token with{' '}
<code className="px-1 py-0.5 bg-bolt-elements-background-depth-2 dark:bg-bolt-elements-background-depth-2 rounded">
repo, read:org, read:user
</code>{' '}
scopes
</li>
<li>
<span className="font-medium">fine-grained</span> - Fine-grained token with Repository and
Organization access
</li>
</ul>
<p className="mt-2">
When set, these variables will be used automatically without requiring manual connection.
</p>
</div>
</div>
)}
</div>
</motion.div>
<div className="grid grid-cols-1 gap-6">
<Suspense fallback={<LoadingFallback />}>
<GitHubConnection />
</Suspense>
<Suspense fallback={<LoadingFallback />}>
<NetlifyConnection />
</Suspense>
<Suspense fallback={<LoadingFallback />}>
<VercelConnection />
</Suspense>
</div>
{/* Additional help text */}
<div className="text-sm text-bolt-elements-textSecondary dark:text-bolt-elements-textSecondary bg-bolt-elements-background-depth-2 dark:bg-bolt-elements-background-depth-2 p-4 rounded-lg">
<p className="flex items-center gap-1 mb-2">
<span className="i-ph:lightbulb w-4 h-4 text-bolt-elements-icon-success dark:text-bolt-elements-icon-success" />
<span className="font-medium">Troubleshooting Tip:</span>
</p>
<p className="mb-2">
If you're having trouble with connections, try using the troubleshooting tool at the top of this page. It can
help diagnose and fix common connection issues.
</p>
<p>For persistent issues:</p>
<ol className="list-decimal list-inside pl-4 mt-1">
<li>Check your browser console for errors</li>
<li>Verify that your tokens have the correct permissions</li>
<li>Try clearing your browser cache and cookies</li>
<li>Ensure your browser allows third-party cookies if using integrations</li>
</ol>
</div>
</div>
);
}

View File

@@ -0,0 +1,980 @@
import React, { useState, useEffect } from 'react';
import { motion } from 'framer-motion';
import { toast } from 'react-toastify';
import { logStore } from '~/lib/stores/logs';
import { classNames } from '~/utils/classNames';
import Cookies from 'js-cookie';
import { Collapsible, CollapsibleTrigger, CollapsibleContent } from '~/components/ui/Collapsible';
import { Button } from '~/components/ui/Button';
interface GitHubUserResponse {
login: string;
avatar_url: string;
html_url: string;
name: string;
bio: string;
public_repos: number;
followers: number;
following: number;
created_at: string;
public_gists: number;
}
interface GitHubRepoInfo {
name: string;
full_name: string;
html_url: string;
description: string;
stargazers_count: number;
forks_count: number;
default_branch: string;
updated_at: string;
languages_url: string;
}
interface GitHubOrganization {
login: string;
avatar_url: string;
html_url: string;
}
interface GitHubEvent {
id: string;
type: string;
repo: {
name: string;
};
created_at: string;
}
interface GitHubLanguageStats {
[language: string]: number;
}
interface GitHubStats {
repos: GitHubRepoInfo[];
recentActivity: GitHubEvent[];
languages: GitHubLanguageStats;
totalGists: number;
publicRepos: number;
privateRepos: number;
stars: number;
forks: number;
followers: number;
publicGists: number;
privateGists: number;
lastUpdated: string;
// Keep these for backward compatibility
totalStars?: number;
totalForks?: number;
organizations?: GitHubOrganization[];
}
interface GitHubConnection {
user: GitHubUserResponse | null;
token: string;
tokenType: 'classic' | 'fine-grained';
stats?: GitHubStats;
rateLimit?: {
limit: number;
remaining: number;
reset: number;
};
}
// Add the GitHub logo SVG component
const GithubLogo = () => (
<svg viewBox="0 0 24 24" className="w-5 h-5">
<path
fill="currentColor"
d="M12 0c-6.626 0-12 5.373-12 12 0 5.302 3.438 9.8 8.207 11.387.599.111.793-.261.793-.577v-2.234c-3.338.726-4.033-1.416-4.033-1.416-.546-1.387-1.333-1.756-1.333-1.756-1.089-.745.083-.729.083-.729 1.205.084 1.839 1.237 1.839 1.237 1.07 1.834 2.807 1.304 3.492.997.107-.775.418-1.305.762-1.604-2.665-.305-5.467-1.334-5.467-5.931 0-1.311.469-2.381 1.236-3.221-.124-.303-.535-1.524.117-3.176 0 0 1.008-.322 3.301 1.23.957-.266 1.983-.399 3.003-.404 1.02.005 2.047.138 3.006.404 2.291-1.552 3.297-1.23 3.297-1.23.653 1.653.242 2.874.118 3.176.77.84 1.235 1.911 1.235 3.221 0 4.609-2.807 5.624-5.479 5.921.43.372.823 1.102.823 2.222v3.293c0 .319.192.694.801.576 4.765-1.589 8.199-6.086 8.199-11.386 0-6.627-5.373-12-12-12z"
/>
</svg>
);
export default function GitHubConnection() {
const [connection, setConnection] = useState<GitHubConnection>({
user: null,
token: '',
tokenType: 'classic',
});
const [isLoading, setIsLoading] = useState(true);
const [isConnecting, setIsConnecting] = useState(false);
const [isFetchingStats, setIsFetchingStats] = useState(false);
const [isStatsExpanded, setIsStatsExpanded] = useState(false);
const tokenTypeRef = React.useRef<'classic' | 'fine-grained'>('classic');
const fetchGithubUser = async (token: string) => {
try {
console.log('Fetching GitHub user with token:', token.substring(0, 5) + '...');
// Use server-side API endpoint instead of direct GitHub API call
const response = await fetch(`/api/system/git-info?action=getUser`, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${token}`, // Include token in headers for validation
},
});
if (!response.ok) {
console.error('Error fetching GitHub user. Status:', response.status);
throw new Error(`Error: ${response.status}`);
}
// Get rate limit information from headers
const rateLimit = {
limit: parseInt(response.headers.get('x-ratelimit-limit') || '0'),
remaining: parseInt(response.headers.get('x-ratelimit-remaining') || '0'),
reset: parseInt(response.headers.get('x-ratelimit-reset') || '0'),
};
const data = await response.json();
console.log('GitHub user API response:', data);
const { user } = data as { user: GitHubUserResponse };
// Validate that we received a user object
if (!user || !user.login) {
console.error('Invalid user data received:', user);
throw new Error('Invalid user data received');
}
// Use the response data
setConnection((prev) => ({
...prev,
user,
token,
tokenType: tokenTypeRef.current,
rateLimit,
}));
// Set cookies for client-side access
Cookies.set('githubUsername', user.login);
Cookies.set('githubToken', token);
Cookies.set('git:github.com', JSON.stringify({ username: token, password: 'x-oauth-basic' }));
// Store connection details in localStorage
localStorage.setItem(
'github_connection',
JSON.stringify({
user,
token,
tokenType: tokenTypeRef.current,
}),
);
logStore.logInfo('Connected to GitHub', {
type: 'system',
message: `Connected to GitHub as ${user.login}`,
});
// Fetch additional GitHub stats
fetchGitHubStats(token);
} catch (error) {
console.error('Failed to fetch GitHub user:', error);
logStore.logError(`GitHub authentication failed: ${error instanceof Error ? error.message : 'Unknown error'}`, {
type: 'system',
message: 'GitHub authentication failed',
});
toast.error(`Authentication failed: ${error instanceof Error ? error.message : 'Unknown error'}`);
throw error; // Rethrow to allow handling in the calling function
}
};
const fetchGitHubStats = async (token: string) => {
setIsFetchingStats(true);
try {
// Get the current user first to ensure we have the latest value
const userResponse = await fetch('https://api.github.com/user', {
headers: {
Authorization: `${connection.tokenType === 'classic' ? 'token' : 'Bearer'} ${token}`,
},
});
if (!userResponse.ok) {
if (userResponse.status === 401) {
toast.error('Your GitHub token has expired. Please reconnect your account.');
handleDisconnect();
return;
}
throw new Error(`Failed to fetch user data: ${userResponse.statusText}`);
}
const userData = (await userResponse.json()) as any;
// Fetch repositories with pagination
let allRepos: any[] = [];
let page = 1;
let hasMore = true;
while (hasMore) {
const reposResponse = await fetch(`https://api.github.com/user/repos?per_page=100&page=${page}`, {
headers: {
Authorization: `${connection.tokenType === 'classic' ? 'token' : 'Bearer'} ${token}`,
},
});
if (!reposResponse.ok) {
throw new Error(`Failed to fetch repositories: ${reposResponse.statusText}`);
}
const repos = (await reposResponse.json()) as any[];
allRepos = [...allRepos, ...repos];
// Check if there are more pages
const linkHeader = reposResponse.headers.get('Link');
hasMore = linkHeader?.includes('rel="next"') ?? false;
page++;
}
// Calculate stats
const repoStats = calculateRepoStats(allRepos);
// Fetch recent activity
const eventsResponse = await fetch(`https://api.github.com/users/${userData.login}/events?per_page=10`, {
headers: {
Authorization: `${connection.tokenType === 'classic' ? 'token' : 'Bearer'} ${token}`,
},
});
if (!eventsResponse.ok) {
throw new Error(`Failed to fetch events: ${eventsResponse.statusText}`);
}
const events = (await eventsResponse.json()) as any[];
const recentActivity = events.slice(0, 5).map((event: any) => ({
id: event.id,
type: event.type,
repo: event.repo.name,
created_at: event.created_at,
}));
// Calculate total stars and forks
const totalStars = allRepos.reduce((sum: number, repo: any) => sum + repo.stargazers_count, 0);
const totalForks = allRepos.reduce((sum: number, repo: any) => sum + repo.forks_count, 0);
const privateRepos = allRepos.filter((repo: any) => repo.private).length;
// Update the stats in the store
const stats: GitHubStats = {
repos: repoStats.repos,
recentActivity,
languages: repoStats.languages || {},
totalGists: repoStats.totalGists || 0,
publicRepos: userData.public_repos || 0,
privateRepos: privateRepos || 0,
stars: totalStars || 0,
forks: totalForks || 0,
followers: userData.followers || 0,
publicGists: userData.public_gists || 0,
privateGists: userData.private_gists || 0,
lastUpdated: new Date().toISOString(),
// For backward compatibility
totalStars: totalStars || 0,
totalForks: totalForks || 0,
organizations: [],
};
// Get the current user first to ensure we have the latest value
const currentConnection = JSON.parse(localStorage.getItem('github_connection') || '{}');
const currentUser = currentConnection.user || connection.user;
// Update connection with stats
const updatedConnection: GitHubConnection = {
user: currentUser,
token,
tokenType: connection.tokenType,
stats,
rateLimit: connection.rateLimit,
};
// Update localStorage
localStorage.setItem('github_connection', JSON.stringify(updatedConnection));
// Update state
setConnection(updatedConnection);
toast.success('GitHub stats refreshed');
} catch (error) {
console.error('Error fetching GitHub stats:', error);
toast.error(`Failed to fetch GitHub stats: ${error instanceof Error ? error.message : 'Unknown error'}`);
} finally {
setIsFetchingStats(false);
}
};
const calculateRepoStats = (repos: any[]) => {
const repoStats = {
repos: repos.map((repo: any) => ({
name: repo.name,
full_name: repo.full_name,
html_url: repo.html_url,
description: repo.description,
stargazers_count: repo.stargazers_count,
forks_count: repo.forks_count,
default_branch: repo.default_branch,
updated_at: repo.updated_at,
languages_url: repo.languages_url,
})),
languages: {} as Record<string, number>,
totalGists: 0,
};
repos.forEach((repo: any) => {
fetch(repo.languages_url)
.then((response) => response.json())
.then((languages: any) => {
const typedLanguages = languages as Record<string, number>;
Object.keys(typedLanguages).forEach((language) => {
if (!repoStats.languages[language]) {
repoStats.languages[language] = 0;
}
repoStats.languages[language] += 1;
});
});
});
return repoStats;
};
useEffect(() => {
const loadSavedConnection = async () => {
setIsLoading(true);
const savedConnection = localStorage.getItem('github_connection');
if (savedConnection) {
try {
const parsed = JSON.parse(savedConnection);
if (!parsed.tokenType) {
parsed.tokenType = 'classic';
}
// Update the ref with the parsed token type
tokenTypeRef.current = parsed.tokenType;
// Set the connection
setConnection(parsed);
// If we have a token but no stats or incomplete stats, fetch them
if (
parsed.user &&
parsed.token &&
(!parsed.stats || !parsed.stats.repos || parsed.stats.repos.length === 0)
) {
console.log('Fetching missing GitHub stats for saved connection');
await fetchGitHubStats(parsed.token);
}
} catch (error) {
console.error('Error parsing saved GitHub connection:', error);
localStorage.removeItem('github_connection');
}
} else {
// Check for environment variable token
const envToken = import.meta.env.VITE_GITHUB_ACCESS_TOKEN;
if (envToken) {
// Check if token type is specified in environment variables
const envTokenType = import.meta.env.VITE_GITHUB_TOKEN_TYPE;
console.log('Environment token type:', envTokenType);
const tokenType =
envTokenType === 'classic' || envTokenType === 'fine-grained'
? (envTokenType as 'classic' | 'fine-grained')
: 'classic';
console.log('Using token type:', tokenType);
// Update both the state and the ref
tokenTypeRef.current = tokenType;
setConnection((prev) => ({
...prev,
tokenType,
}));
try {
// Fetch user data with the environment token
await fetchGithubUser(envToken);
} catch (error) {
console.error('Failed to connect with environment token:', error);
}
}
}
setIsLoading(false);
};
loadSavedConnection();
}, []);
// Ensure cookies are updated when connection changes
useEffect(() => {
if (!connection) {
return;
}
const token = connection.token;
const data = connection.user;
if (token) {
Cookies.set('githubToken', token);
Cookies.set('git:github.com', JSON.stringify({ username: token, password: 'x-oauth-basic' }));
}
if (data) {
Cookies.set('githubUsername', data.login);
}
}, [connection]);
// Add function to update rate limits
const updateRateLimits = async (token: string) => {
try {
const response = await fetch('https://api.github.com/rate_limit', {
headers: {
Authorization: `Bearer ${token}`,
Accept: 'application/vnd.github.v3+json',
},
});
if (response.ok) {
const rateLimit = {
limit: parseInt(response.headers.get('x-ratelimit-limit') || '0'),
remaining: parseInt(response.headers.get('x-ratelimit-remaining') || '0'),
reset: parseInt(response.headers.get('x-ratelimit-reset') || '0'),
};
setConnection((prev) => ({
...prev,
rateLimit,
}));
}
} catch (error) {
console.error('Failed to fetch rate limits:', error);
}
};
// Add effect to update rate limits periodically
useEffect(() => {
let interval: NodeJS.Timeout;
if (connection.token && connection.user) {
updateRateLimits(connection.token);
interval = setInterval(() => updateRateLimits(connection.token), 60000); // Update every minute
}
return () => {
if (interval) {
clearInterval(interval);
}
};
}, [connection.token, connection.user]);
if (isLoading || isConnecting || isFetchingStats) {
return <LoadingSpinner />;
}
const handleConnect = async (event: React.FormEvent) => {
event.preventDefault();
setIsConnecting(true);
try {
// Update the ref with the current state value before connecting
tokenTypeRef.current = connection.tokenType;
/*
* Save token type to localStorage even before connecting
* This ensures the token type is persisted even if connection fails
*/
localStorage.setItem(
'github_connection',
JSON.stringify({
user: null,
token: connection.token,
tokenType: connection.tokenType,
}),
);
// Attempt to fetch the user info which validates the token
await fetchGithubUser(connection.token);
toast.success('Connected to GitHub successfully');
} catch (error) {
console.error('Failed to connect to GitHub:', error);
// Reset connection state on failure
setConnection({ user: null, token: connection.token, tokenType: connection.tokenType });
toast.error(`Failed to connect to GitHub: ${error instanceof Error ? error.message : 'Unknown error'}`);
} finally {
setIsConnecting(false);
}
};
const handleDisconnect = () => {
localStorage.removeItem('github_connection');
// Remove all GitHub-related cookies
Cookies.remove('githubToken');
Cookies.remove('githubUsername');
Cookies.remove('git:github.com');
// Reset the token type ref
tokenTypeRef.current = 'classic';
setConnection({ user: null, token: '', tokenType: 'classic' });
toast.success('Disconnected from GitHub');
};
return (
<motion.div
className="bg-bolt-elements-background dark:bg-bolt-elements-background border border-bolt-elements-borderColor dark:border-bolt-elements-borderColor rounded-lg"
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ delay: 0.2 }}
>
<div className="p-6 space-y-6">
<div className="flex items-center justify-between">
<div className="flex items-center gap-2">
<GithubLogo />
<h3 className="text-base font-medium text-bolt-elements-textPrimary dark:text-bolt-elements-textPrimary">
GitHub Connection
</h3>
</div>
</div>
{!connection.user && (
<div className="text-xs text-bolt-elements-textSecondary bg-bolt-elements-background-depth-1 dark:bg-bolt-elements-background-depth-1 p-3 rounded-lg mb-4">
<p className="flex items-center gap-1 mb-1">
<span className="i-ph:lightbulb w-3.5 h-3.5 text-bolt-elements-icon-success dark:text-bolt-elements-icon-success" />
<span className="font-medium">Tip:</span> You can also set the{' '}
<code className="px-1 py-0.5 bg-bolt-elements-background-depth-2 dark:bg-bolt-elements-background-depth-2 rounded">
VITE_GITHUB_ACCESS_TOKEN
</code>{' '}
environment variable to connect automatically.
</p>
<p>
For fine-grained tokens, also set{' '}
<code className="px-1 py-0.5 bg-bolt-elements-background-depth-2 dark:bg-bolt-elements-background-depth-2 rounded">
VITE_GITHUB_TOKEN_TYPE=fine-grained
</code>
</p>
</div>
)}
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<div>
<label className="block text-sm text-bolt-elements-textSecondary dark:text-bolt-elements-textSecondary mb-2">
Token Type
</label>
<select
value={connection.tokenType}
onChange={(e) => {
const newTokenType = e.target.value as 'classic' | 'fine-grained';
tokenTypeRef.current = newTokenType;
setConnection((prev) => ({ ...prev, tokenType: newTokenType }));
}}
disabled={isConnecting || !!connection.user}
className={classNames(
'w-full px-3 py-2 rounded-lg text-sm',
'bg-bolt-elements-background-depth-1 dark:bg-bolt-elements-background-depth-1',
'border border-bolt-elements-borderColor dark:border-bolt-elements-borderColor',
'text-bolt-elements-textPrimary dark:text-bolt-elements-textPrimary',
'focus:outline-none focus:ring-1 focus:ring-bolt-elements-item-contentAccent dark:focus:ring-bolt-elements-item-contentAccent',
'disabled:opacity-50',
)}
>
<option value="classic">Personal Access Token (Classic)</option>
<option value="fine-grained">Fine-grained Token</option>
</select>
</div>
<div>
<label className="block text-sm text-bolt-elements-textSecondary dark:text-bolt-elements-textSecondary mb-2">
{connection.tokenType === 'classic' ? 'Personal Access Token' : 'Fine-grained Token'}
</label>
<input
type="password"
value={connection.token}
onChange={(e) => setConnection((prev) => ({ ...prev, token: e.target.value }))}
disabled={isConnecting || !!connection.user}
placeholder={`Enter your GitHub ${
connection.tokenType === 'classic' ? 'personal access token' : 'fine-grained token'
}`}
className={classNames(
'w-full px-3 py-2 rounded-lg text-sm',
'bg-[#F8F8F8] dark:bg-[#1A1A1A]',
'border border-[#E5E5E5] dark:border-[#333333]',
'text-bolt-elements-textPrimary placeholder-bolt-elements-textTertiary',
'focus:outline-none focus:ring-1 focus:ring-bolt-elements-borderColorActive',
'disabled:opacity-50',
)}
/>
<div className="mt-2 text-sm text-bolt-elements-textSecondary">
<a
href={`https://github.com/settings/tokens${connection.tokenType === 'fine-grained' ? '/beta' : '/new'}`}
target="_blank"
rel="noopener noreferrer"
className="text-bolt-elements-borderColorActive hover:underline inline-flex items-center gap-1"
>
Get your token
<div className="i-ph:arrow-square-out w-4 h-4" />
</a>
<span className="mx-2"></span>
<span>
Required scopes:{' '}
{connection.tokenType === 'classic'
? 'repo, read:org, read:user'
: 'Repository access, Organization access'}
</span>
</div>
</div>
</div>
<div className="flex items-center justify-between">
{!connection.user ? (
<button
onClick={handleConnect}
disabled={isConnecting || !connection.token}
className={classNames(
'px-4 py-2 rounded-lg text-sm flex items-center gap-2',
'bg-[#303030] text-white',
'hover:bg-[#5E41D0] hover:text-white',
'disabled:opacity-50 disabled:cursor-not-allowed transition-all duration-200',
'transform active:scale-95',
)}
>
{isConnecting ? (
<>
<div className="i-ph:spinner-gap animate-spin" />
Connecting...
</>
) : (
<>
<div className="i-ph:plug-charging w-4 h-4" />
Connect
</>
)}
</button>
) : (
<>
<div className="flex items-center justify-between w-full">
<div className="flex items-center gap-4">
<button
onClick={handleDisconnect}
className={classNames(
'px-4 py-2 rounded-lg text-sm flex items-center gap-2',
'bg-red-500 text-white',
'hover:bg-red-600',
)}
>
<div className="i-ph:plug w-4 h-4" />
Disconnect
</button>
<span className="text-sm text-bolt-elements-textSecondary flex items-center gap-1">
<div className="i-ph:check-circle w-4 h-4 text-green-500" />
Connected to GitHub
</span>
</div>
<div className="flex items-center gap-2">
<Button
variant="outline"
onClick={() => window.open('https://github.com/dashboard', '_blank', 'noopener,noreferrer')}
className="flex items-center gap-2 hover:bg-bolt-elements-item-backgroundActive/10 hover:text-bolt-elements-textPrimary dark:hover:text-bolt-elements-textPrimary transition-colors"
>
<div className="i-ph:layout w-4 h-4" />
Dashboard
</Button>
<Button
onClick={() => {
fetchGitHubStats(connection.token);
updateRateLimits(connection.token);
}}
disabled={isFetchingStats}
variant="outline"
className="flex items-center gap-2 hover:bg-bolt-elements-item-backgroundActive/10 hover:text-bolt-elements-textPrimary dark:hover:text-bolt-elements-textPrimary transition-colors"
>
{isFetchingStats ? (
<>
<div className="i-ph:spinner-gap w-4 h-4 animate-spin" />
Refreshing...
</>
) : (
<>
<div className="i-ph:arrows-clockwise w-4 h-4" />
Refresh Stats
</>
)}
</Button>
</div>
</div>
</>
)}
</div>
{connection.user && connection.stats && (
<div className="mt-6 border-t border-bolt-elements-borderColor dark:border-bolt-elements-borderColor pt-6">
<div className="flex items-center gap-4 p-4 bg-bolt-elements-background-depth-1 dark:bg-bolt-elements-background-depth-1 rounded-lg mb-4">
<img
src={connection.user.avatar_url}
alt={connection.user.login}
className="w-12 h-12 rounded-full border-2 border-bolt-elements-item-contentAccent dark:border-bolt-elements-item-contentAccent"
/>
<div>
<h4 className="text-sm font-medium text-bolt-elements-textPrimary dark:text-bolt-elements-textPrimary">
{connection.user.name || connection.user.login}
</h4>
<p className="text-sm text-bolt-elements-textSecondary dark:text-bolt-elements-textSecondary">
{connection.user.login}
</p>
</div>
</div>
<Collapsible open={isStatsExpanded} onOpenChange={setIsStatsExpanded}>
<CollapsibleTrigger asChild>
<div className="flex items-center justify-between p-4 rounded-lg bg-bolt-elements-background dark:bg-bolt-elements-background-depth-2 border border-bolt-elements-borderColor dark:border-bolt-elements-borderColor hover:border-bolt-elements-borderColorActive/70 dark:hover:border-bolt-elements-borderColorActive/70 transition-all duration-200">
<div className="flex items-center gap-2">
<div className="i-ph:chart-bar w-4 h-4 text-bolt-elements-item-contentAccent" />
<span className="text-sm font-medium text-bolt-elements-textPrimary">GitHub Stats</span>
</div>
<div
className={classNames(
'i-ph:caret-down w-4 h-4 transform transition-transform duration-200 text-bolt-elements-textSecondary',
isStatsExpanded ? 'rotate-180' : '',
)}
/>
</div>
</CollapsibleTrigger>
<CollapsibleContent className="overflow-hidden">
<div className="space-y-4 mt-4">
{/* Languages Section */}
<div className="mb-6">
<h4 className="text-sm font-medium text-bolt-elements-textPrimary mb-3">Top Languages</h4>
<div className="flex flex-wrap gap-2">
{Object.entries(connection.stats.languages)
.sort(([, a], [, b]) => b - a)
.slice(0, 5)
.map(([language]) => (
<span
key={language}
className="px-3 py-1 text-xs rounded-full bg-bolt-elements-sidebar-buttonBackgroundDefault text-bolt-elements-sidebar-buttonText"
>
{language}
</span>
))}
</div>
</div>
{/* Additional Stats */}
<div className="grid grid-cols-4 gap-4 mb-6">
{[
{
label: 'Member Since',
value: new Date(connection.user.created_at).toLocaleDateString(),
},
{
label: 'Public Gists',
value: connection.stats.publicGists,
},
{
label: 'Organizations',
value: connection.stats.organizations ? connection.stats.organizations.length : 0,
},
{
label: 'Languages',
value: Object.keys(connection.stats.languages).length,
},
].map((stat, index) => (
<div
key={index}
className="flex flex-col p-3 rounded-lg bg-bolt-elements-background-depth-2 dark:bg-bolt-elements-background-depth-2 border border-bolt-elements-borderColor dark:border-bolt-elements-borderColor"
>
<span className="text-xs text-bolt-elements-textSecondary">{stat.label}</span>
<span className="text-lg font-medium text-bolt-elements-textPrimary">{stat.value}</span>
</div>
))}
</div>
{/* Repository Stats */}
<div className="mt-4">
<div className="space-y-4">
<div>
<h5 className="text-sm font-medium text-bolt-elements-textPrimary mb-2">Repository Stats</h5>
<div className="grid grid-cols-2 gap-4">
{[
{
label: 'Public Repos',
value: connection.stats.publicRepos,
},
{
label: 'Private Repos',
value: connection.stats.privateRepos,
},
].map((stat, index) => (
<div
key={index}
className="flex flex-col p-3 rounded-lg bg-bolt-elements-background-depth-2 dark:bg-bolt-elements-background-depth-2 border border-bolt-elements-borderColor dark:border-bolt-elements-borderColor"
>
<span className="text-xs text-bolt-elements-textSecondary">{stat.label}</span>
<span className="text-lg font-medium text-bolt-elements-textPrimary">{stat.value}</span>
</div>
))}
</div>
</div>
<div>
<h5 className="text-sm font-medium text-bolt-elements-textPrimary mb-2">Contribution Stats</h5>
<div className="grid grid-cols-3 gap-4">
{[
{
label: 'Stars',
value: connection.stats.stars || 0,
icon: 'i-ph:star',
iconColor: 'text-bolt-elements-icon-warning',
},
{
label: 'Forks',
value: connection.stats.forks || 0,
icon: 'i-ph:git-fork',
iconColor: 'text-bolt-elements-icon-info',
},
{
label: 'Followers',
value: connection.stats.followers || 0,
icon: 'i-ph:users',
iconColor: 'text-bolt-elements-icon-success',
},
].map((stat, index) => (
<div
key={index}
className="flex flex-col p-3 rounded-lg bg-bolt-elements-background-depth-2 dark:bg-bolt-elements-background-depth-2 border border-bolt-elements-borderColor dark:border-bolt-elements-borderColor"
>
<span className="text-xs text-bolt-elements-textSecondary">{stat.label}</span>
<span className="text-lg font-medium text-bolt-elements-textPrimary flex items-center gap-1">
<div className={`${stat.icon} w-4 h-4 ${stat.iconColor}`} />
{stat.value}
</span>
</div>
))}
</div>
</div>
<div>
<h5 className="text-sm font-medium text-bolt-elements-textPrimary mb-2">Gists</h5>
<div className="grid grid-cols-2 gap-4">
{[
{
label: 'Public',
value: connection.stats.publicGists,
},
{
label: 'Private',
value: connection.stats.privateGists || 0,
},
].map((stat, index) => (
<div
key={index}
className="flex flex-col p-3 rounded-lg bg-bolt-elements-background-depth-2 dark:bg-bolt-elements-background-depth-2 border border-bolt-elements-borderColor dark:border-bolt-elements-borderColor"
>
<span className="text-xs text-bolt-elements-textSecondary">{stat.label}</span>
<span className="text-lg font-medium text-bolt-elements-textPrimary">{stat.value}</span>
</div>
))}
</div>
</div>
<div className="pt-2 border-t border-bolt-elements-borderColor">
<span className="text-xs text-bolt-elements-textSecondary">
Last updated: {new Date(connection.stats.lastUpdated).toLocaleString()}
</span>
</div>
</div>
</div>
{/* Repositories Section */}
<div className="space-y-4">
<h4 className="text-sm font-medium text-bolt-elements-textPrimary">Recent Repositories</h4>
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
{connection.stats.repos.map((repo) => (
<a
key={repo.full_name}
href={repo.html_url}
target="_blank"
rel="noopener noreferrer"
className="group block p-4 rounded-lg bg-bolt-elements-background-depth-1 dark:bg-bolt-elements-background-depth-1 border border-bolt-elements-borderColor dark:border-bolt-elements-borderColor hover:border-bolt-elements-borderColorActive dark:hover:border-bolt-elements-borderColorActive transition-all duration-200"
>
<div className="space-y-3">
<div className="flex items-start justify-between">
<div className="flex items-center gap-2">
<div className="i-ph:git-branch w-4 h-4 text-bolt-elements-icon-tertiary" />
<h5 className="text-sm font-medium text-bolt-elements-textPrimary group-hover:text-bolt-elements-item-contentAccent transition-colors">
{repo.name}
</h5>
</div>
<div className="flex items-center gap-3 text-xs text-bolt-elements-textSecondary">
<span className="flex items-center gap-1" title="Stars">
<div className="i-ph:star w-3.5 h-3.5 text-bolt-elements-icon-warning" />
{repo.stargazers_count.toLocaleString()}
</span>
<span className="flex items-center gap-1" title="Forks">
<div className="i-ph:git-fork w-3.5 h-3.5 text-bolt-elements-icon-info" />
{repo.forks_count.toLocaleString()}
</span>
</div>
</div>
{repo.description && (
<p className="text-xs text-bolt-elements-textSecondary line-clamp-2">
{repo.description}
</p>
)}
<div className="flex items-center gap-3 text-xs text-bolt-elements-textSecondary">
<span className="flex items-center gap-1" title="Default Branch">
<div className="i-ph:git-branch w-3.5 h-3.5" />
{repo.default_branch}
</span>
<span className="flex items-center gap-1" title="Last Updated">
<div className="i-ph:clock w-3.5 h-3.5" />
{new Date(repo.updated_at).toLocaleDateString(undefined, {
year: 'numeric',
month: 'short',
day: 'numeric',
})}
</span>
<span className="flex items-center gap-1 ml-auto group-hover:text-bolt-elements-item-contentAccent transition-colors">
<div className="i-ph:arrow-square-out w-3.5 h-3.5" />
View
</span>
</div>
</div>
</a>
))}
</div>
</div>
</div>
</CollapsibleContent>
</Collapsible>
</div>
)}
</div>
</motion.div>
);
}
function LoadingSpinner() {
return (
<div className="flex items-center justify-center p-4">
<div className="flex items-center gap-2">
<div className="i-ph:spinner-gap-bold animate-spin w-4 h-4" />
<span className="text-bolt-elements-textSecondary">Loading...</span>
</div>
</div>
);
}

View File

@@ -0,0 +1,731 @@
import React, { useState, useEffect } from 'react';
import { toast } from 'react-toastify';
import { classNames } from '~/utils/classNames';
import { useStore } from '@nanostores/react';
import { netlifyConnection, updateNetlifyConnection, initializeNetlifyConnection } from '~/lib/stores/netlify';
import type { NetlifySite, NetlifyDeploy, NetlifyBuild, NetlifyUser } from '~/types/netlify';
import {
CloudIcon,
BuildingLibraryIcon,
ClockIcon,
CodeBracketIcon,
CheckCircleIcon,
XCircleIcon,
TrashIcon,
ArrowPathIcon,
LockClosedIcon,
LockOpenIcon,
RocketLaunchIcon,
} from '@heroicons/react/24/outline';
import { Button } from '~/components/ui/Button';
import { Collapsible, CollapsibleTrigger, CollapsibleContent } from '~/components/ui/Collapsible';
import { formatDistanceToNow } from 'date-fns';
import { Badge } from '~/components/ui/Badge';
// Add the Netlify logo SVG component at the top of the file
const NetlifyLogo = () => (
<svg viewBox="0 0 40 40" className="w-5 h-5">
<path
fill="currentColor"
d="M28.589 14.135l-.014-.006c-.008-.003-.016-.006-.023-.013a.11.11 0 0 1-.028-.093l.773-4.726 3.625 3.626-3.77 1.604a.083.083 0 0 1-.033.006h-.015c-.005-.003-.01-.007-.02-.017a1.716 1.716 0 0 0-.495-.381zm5.258-.288l3.876 3.876c.805.806 1.208 1.208 1.674 1.355a2 2 0 0 1 1.206 0c.466-.148.869-.55 1.674-1.356L8.73 28.73l2.349-3.643c.011-.018.022-.034.04-.047.025-.018.061-.01.091 0a2.434 2.434 0 0 0 1.638-.083c.027-.01.054-.017.075.002a.19.19 0 0 1 .028.032L21.95 38.05zM7.863 27.863L5.8 25.8l4.074-1.738a.084.084 0 0 1 .033-.007c.034 0 .054.034.072.065a2.91 2.91 0 0 0 .13.184l.013.016c.012.017.004.034-.008.05l-2.25 3.493zm-2.976-2.976l-2.61-2.61c-.444-.444-.766-.766-.99-1.043l7.936 1.646a.84.84 0 0 0 .03.005c.049.008.103.017.103.063 0 .05-.059.073-.109.092l-.023.01-4.337 1.837zM.831 19.892a2 2 0 0 1 .09-.495c.148-.466.55-.868 1.356-1.674l3.34-3.34a2175.525 2175.525 0 0 0 4.626 6.687c.027.036.057.076.026.106-.146.161-.292.337-.395.528a.16.16 0 0 1-.05.062c-.013.008-.027.005-.042.002H9.78L.831 19.892zm5.68-6.403l4.491-4.491c.422.185 1.958.834 3.332 1.414 1.04.44 1.988.84 2.286.97.03.012.057.024.07.054.008.018.004.041 0 .06a2.003 2.003 0 0 0 .523 1.828c.03.03 0 .073-.026.11l-.014.021-4.56 7.063c-.012.02-.023.037-.043.05-.024.015-.058.008-.086.001a2.274 2.274 0 0 0-.543-.074c-.164 0-.342.03-.522.063h-.001c-.02.003-.038.007-.054-.005a.21.21 0 0 1-.045-.051l-4.808-7.013zm5.398-5.398l5.814-5.814c.805-.805 1.208-1.208 1.674-1.355a2 2 0 0 1 1.206 0c.466.147.869.55 1.674 1.355l1.26 1.26-4.135 6.404a.155.155 0 0 1-.041.048c-.025.017-.06.01-.09 0a2.097 2.097 0 0 0-1.92.37c-.027.028-.067.012-.101-.003-.54-.235-4.74-2.01-5.341-2.265zm12.506-3.676l3.818 3.818-.92 5.698v.015a.135.135 0 0 1-.008.038c-.01.02-.03.024-.05.03a1.83 1.83 0 0 0-.548.273.154.154 0 0 0-.02.017c-.011.012-.022.023-.04.025a.114.114 0 0 1-.043-.007l-5.818-2.472-.011-.005c-.037-.015-.081-.033-.081-.071a2.198 2.198 0 0 0-.31-.915c-.028-.046-.059-.094-.035-.141l4.066-6.303zm-3.932 8.606l5.454 2.31c.03.014.063.027.076.058a.106.106 0 0 1 0 .057c-.016.08-.03.171-.03.263v.153c0 .038-.039.054-.075.069l-.011.004c-.864.369-12.13 5.173-12.147 5.173-.017 0-.035 0-.052-.017-.03-.03 0-.072.027-.11a.76.76 0 0 0 .014-.02l4.482-6.94.008-.012c.026-.042.056-.089.104-.089l.045.007c.102.014.192.027.283.027.68 0 1.31-.331 1.69-.897a.16.16 0 0 1 .034-.04c.027-.02.067-.01.098.004zm-6.246 9.185l12.28-5.237s.018 0 .035.017c.067.067.124.112.179.154l.027.017c.025.014.05.03.052.056 0 .01 0 .016-.002.025L25.756 23.7l-.004.026c-.007.05-.014.107-.061.107a1.729 1.729 0 0 0-1.373.847l-.005.008c-.014.023-.027.045-.05.057-.021.01-.048.006-.07.001l-9.793-2.02c-.01-.002-.152-.519-.163-.52z"
/>
</svg>
);
// Add new interface for site actions
interface SiteAction {
name: string;
icon: React.ComponentType<any>;
action: (siteId: string) => Promise<void>;
requiresConfirmation?: boolean;
variant?: 'default' | 'destructive' | 'outline';
}
export default function NetlifyConnection() {
const connection = useStore(netlifyConnection);
const [tokenInput, setTokenInput] = useState('');
const [fetchingStats, setFetchingStats] = useState(false);
const [sites, setSites] = useState<NetlifySite[]>([]);
const [deploys, setDeploys] = useState<NetlifyDeploy[]>([]);
const [builds, setBuilds] = useState<NetlifyBuild[]>([]);
const [deploymentCount, setDeploymentCount] = useState(0);
const [lastUpdated, setLastUpdated] = useState('');
const [isStatsOpen, setIsStatsOpen] = useState(false);
const [activeSiteIndex, setActiveSiteIndex] = useState(0);
const [isActionLoading, setIsActionLoading] = useState(false);
const [isConnecting, setIsConnecting] = useState(false);
// Add site actions
const siteActions: SiteAction[] = [
{
name: 'Clear Cache',
icon: ArrowPathIcon,
action: async (siteId: string) => {
try {
const response = await fetch(`https://api.netlify.com/api/v1/sites/${siteId}/cache`, {
method: 'POST',
headers: {
Authorization: `Bearer ${connection.token}`,
},
});
if (!response.ok) {
throw new Error('Failed to clear cache');
}
toast.success('Site cache cleared successfully');
} catch (err: unknown) {
const error = err instanceof Error ? err.message : 'Unknown error';
toast.error(`Failed to clear site cache: ${error}`);
}
},
},
{
name: 'Delete Site',
icon: TrashIcon,
action: async (siteId: string) => {
try {
const response = await fetch(`https://api.netlify.com/api/v1/sites/${siteId}`, {
method: 'DELETE',
headers: {
Authorization: `Bearer ${connection.token}`,
},
});
if (!response.ok) {
throw new Error('Failed to delete site');
}
toast.success('Site deleted successfully');
fetchNetlifyStats(connection.token);
} catch (err: unknown) {
const error = err instanceof Error ? err.message : 'Unknown error';
toast.error(`Failed to delete site: ${error}`);
}
},
requiresConfirmation: true,
variant: 'destructive',
},
];
// Add deploy management functions
const handleDeploy = async (siteId: string, deployId: string, action: 'lock' | 'unlock' | 'publish') => {
try {
setIsActionLoading(true);
const endpoint =
action === 'publish'
? `https://api.netlify.com/api/v1/sites/${siteId}/deploys/${deployId}/restore`
: `https://api.netlify.com/api/v1/deploys/${deployId}/${action}`;
const response = await fetch(endpoint, {
method: 'POST',
headers: {
Authorization: `Bearer ${connection.token}`,
},
});
if (!response.ok) {
throw new Error(`Failed to ${action} deploy`);
}
toast.success(`Deploy ${action}ed successfully`);
fetchNetlifyStats(connection.token);
} catch (err: unknown) {
const error = err instanceof Error ? err.message : 'Unknown error';
toast.error(`Failed to ${action} deploy: ${error}`);
} finally {
setIsActionLoading(false);
}
};
useEffect(() => {
// Initialize connection with environment token if available
initializeNetlifyConnection();
}, []);
useEffect(() => {
// Check if we have a connection with a token but no stats
if (connection.user && connection.token && (!connection.stats || !connection.stats.sites)) {
fetchNetlifyStats(connection.token);
}
// Update local state from connection
if (connection.stats) {
setSites(connection.stats.sites || []);
setDeploys(connection.stats.deploys || []);
setBuilds(connection.stats.builds || []);
setDeploymentCount(connection.stats.deploys?.length || 0);
setLastUpdated(connection.stats.lastDeployTime || '');
}
}, [connection]);
const handleConnect = async () => {
if (!tokenInput) {
toast.error('Please enter a Netlify API token');
return;
}
setIsConnecting(true);
try {
const response = await fetch('https://api.netlify.com/api/v1/user', {
headers: {
Authorization: `Bearer ${tokenInput}`,
},
});
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
const userData = (await response.json()) as NetlifyUser;
// Update the connection store
updateNetlifyConnection({
user: userData,
token: tokenInput,
});
toast.success('Connected to Netlify successfully');
// Fetch stats after successful connection
fetchNetlifyStats(tokenInput);
} catch (error) {
console.error('Error connecting to Netlify:', error);
toast.error(`Failed to connect to Netlify: ${error instanceof Error ? error.message : 'Unknown error'}`);
} finally {
setIsConnecting(false);
setTokenInput('');
}
};
const handleDisconnect = () => {
// Clear from localStorage
localStorage.removeItem('netlify_connection');
// Remove cookies
document.cookie = 'netlifyToken=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;';
// Update the store
updateNetlifyConnection({ user: null, token: '' });
toast.success('Disconnected from Netlify');
};
const fetchNetlifyStats = async (token: string) => {
setFetchingStats(true);
try {
// Fetch sites
const sitesResponse = await fetch('https://api.netlify.com/api/v1/sites', {
headers: {
Authorization: `Bearer ${token}`,
},
});
if (!sitesResponse.ok) {
throw new Error(`Failed to fetch sites: ${sitesResponse.statusText}`);
}
const sitesData = (await sitesResponse.json()) as NetlifySite[];
setSites(sitesData);
// Fetch recent deploys for the first site (if any)
let deploysData: NetlifyDeploy[] = [];
let buildsData: NetlifyBuild[] = [];
let lastDeployTime = '';
if (sitesData && sitesData.length > 0) {
const firstSite = sitesData[0];
// Fetch deploys
const deploysResponse = await fetch(`https://api.netlify.com/api/v1/sites/${firstSite.id}/deploys`, {
headers: {
Authorization: `Bearer ${token}`,
},
});
if (deploysResponse.ok) {
deploysData = (await deploysResponse.json()) as NetlifyDeploy[];
setDeploys(deploysData);
setDeploymentCount(deploysData.length);
// Get the latest deploy time
if (deploysData.length > 0) {
lastDeployTime = deploysData[0].created_at;
setLastUpdated(lastDeployTime);
// Fetch builds for the site
const buildsResponse = await fetch(`https://api.netlify.com/api/v1/sites/${firstSite.id}/builds`, {
headers: {
Authorization: `Bearer ${token}`,
},
});
if (buildsResponse.ok) {
buildsData = (await buildsResponse.json()) as NetlifyBuild[];
setBuilds(buildsData);
}
}
}
}
// Update the stats in the store
updateNetlifyConnection({
stats: {
sites: sitesData,
deploys: deploysData,
builds: buildsData,
lastDeployTime,
totalSites: sitesData.length,
},
});
toast.success('Netlify stats updated');
} catch (error) {
console.error('Error fetching Netlify stats:', error);
toast.error(`Failed to fetch Netlify stats: ${error instanceof Error ? error.message : 'Unknown error'}`);
} finally {
setFetchingStats(false);
}
};
const renderStats = () => {
if (!connection.user || !connection.stats) {
return null;
}
return (
<div className="mt-6">
<Collapsible open={isStatsOpen} onOpenChange={setIsStatsOpen}>
<CollapsibleTrigger asChild>
<div className="flex items-center justify-between p-4 rounded-lg bg-bolt-elements-background dark:bg-bolt-elements-background-depth-2 border border-bolt-elements-borderColor dark:border-bolt-elements-borderColor hover:border-bolt-elements-borderColorActive/70 dark:hover:border-bolt-elements-borderColorActive/70 transition-all duration-200">
<div className="flex items-center gap-2">
<div className="i-ph:chart-bar w-4 h-4 text-bolt-elements-item-contentAccent dark:text-bolt-elements-item-contentAccent" />
<span className="text-sm font-medium text-bolt-elements-textPrimary dark:text-bolt-elements-textPrimary">
Netlify Stats
</span>
</div>
<div
className={classNames(
'i-ph:caret-down w-4 h-4 transform transition-transform duration-200 text-bolt-elements-textSecondary',
isStatsOpen ? 'rotate-180' : '',
)}
/>
</div>
</CollapsibleTrigger>
<CollapsibleContent className="overflow-hidden">
<div className="space-y-4 mt-4">
<div className="flex flex-wrap items-center gap-4">
<Badge
variant="outline"
className="flex items-center gap-1 text-bolt-elements-textPrimary dark:text-bolt-elements-textPrimary"
>
<BuildingLibraryIcon className="h-4 w-4 text-bolt-elements-item-contentAccent" />
<span>{connection.stats.totalSites} Sites</span>
</Badge>
<Badge
variant="outline"
className="flex items-center gap-1 text-bolt-elements-textPrimary dark:text-bolt-elements-textPrimary"
>
<RocketLaunchIcon className="h-4 w-4 text-bolt-elements-item-contentAccent" />
<span>{deploymentCount} Deployments</span>
</Badge>
{lastUpdated && (
<Badge
variant="outline"
className="flex items-center gap-1 text-bolt-elements-textPrimary dark:text-bolt-elements-textPrimary"
>
<ClockIcon className="h-4 w-4 text-bolt-elements-item-contentAccent" />
<span>Updated {formatDistanceToNow(new Date(lastUpdated))} ago</span>
</Badge>
)}
</div>
{sites.length > 0 && (
<div className="mt-4 space-y-4">
<div className="bg-bolt-elements-background dark:bg-bolt-elements-background-depth-1 border border-bolt-elements-borderColor dark:border-bolt-elements-borderColor rounded-lg p-4">
<div className="flex items-center justify-between mb-4">
<h4 className="text-sm font-medium flex items-center gap-2 text-bolt-elements-textPrimary dark:text-bolt-elements-textPrimary">
<BuildingLibraryIcon className="h-4 w-4 text-bolt-elements-item-contentAccent dark:text-bolt-elements-item-contentAccent" />
Your Sites
</h4>
<Button
variant="outline"
size="sm"
onClick={() => fetchNetlifyStats(connection.token)}
disabled={fetchingStats}
className="flex items-center gap-2 text-bolt-elements-textPrimary dark:text-bolt-elements-textPrimary hover:bg-bolt-elements-item-backgroundActive/10"
>
<ArrowPathIcon
className={classNames(
'h-4 w-4 text-bolt-elements-item-contentAccent dark:text-bolt-elements-item-contentAccent',
{ 'animate-spin': fetchingStats },
)}
/>
{fetchingStats ? 'Refreshing...' : 'Refresh'}
</Button>
</div>
<div className="space-y-3">
{sites.map((site, index) => (
<div
key={site.id}
className={classNames(
'bg-bolt-elements-background dark:bg-bolt-elements-background-depth-1 border rounded-lg p-4 transition-all',
activeSiteIndex === index
? 'border-bolt-elements-item-contentAccent bg-bolt-elements-item-backgroundActive/10'
: 'border-bolt-elements-borderColor hover:border-bolt-elements-borderColorActive/70',
)}
onClick={() => {
setActiveSiteIndex(index);
}}
>
<div className="flex items-center justify-between">
<div className="flex items-center gap-2">
<CloudIcon className="h-5 w-5 text-bolt-elements-item-contentAccent dark:text-bolt-elements-item-contentAccent" />
<span className="font-medium text-bolt-elements-textPrimary dark:text-bolt-elements-textPrimary">
{site.name}
</span>
</div>
<div className="flex items-center gap-2">
<Badge
variant={site.published_deploy?.state === 'ready' ? 'default' : 'destructive'}
className="flex items-center gap-1 text-bolt-elements-textPrimary dark:text-bolt-elements-textPrimary"
>
{site.published_deploy?.state === 'ready' ? (
<CheckCircleIcon className="h-4 w-4 text-green-500" />
) : (
<XCircleIcon className="h-4 w-4 text-red-500" />
)}
<span className="text-bolt-elements-textPrimary dark:text-bolt-elements-textPrimary">
{site.published_deploy?.state || 'Unknown'}
</span>
</Badge>
</div>
</div>
<div className="mt-3 flex items-center gap-2">
<a
href={site.ssl_url || site.url}
target="_blank"
rel="noopener noreferrer"
className="text-sm flex items-center gap-1 transition-colors text-bolt-elements-link-text hover:text-bolt-elements-link-textHover dark:text-white dark:hover:text-bolt-elements-link-textHover"
onClick={(e) => e.stopPropagation()}
>
<CloudIcon className="h-3 w-3 text-bolt-elements-item-contentAccent dark:text-bolt-elements-item-contentAccent" />
<span className="underline decoration-1 underline-offset-2">
{site.ssl_url || site.url}
</span>
</a>
</div>
{activeSiteIndex === index && (
<>
<div className="mt-4 pt-3 border-t border-bolt-elements-borderColor">
<div className="flex items-center gap-2">
{siteActions.map((action) => (
<Button
key={action.name}
variant={action.variant || 'outline'}
size="sm"
onClick={async (e) => {
e.stopPropagation();
if (action.requiresConfirmation) {
if (!confirm(`Are you sure you want to ${action.name.toLowerCase()}?`)) {
return;
}
}
setIsActionLoading(true);
await action.action(site.id);
setIsActionLoading(false);
}}
disabled={isActionLoading}
className="flex items-center gap-1 text-bolt-elements-textPrimary dark:text-bolt-elements-textPrimary"
>
<action.icon className="h-4 w-4 text-bolt-elements-item-contentAccent dark:text-bolt-elements-item-contentAccent" />
{action.name}
</Button>
))}
</div>
</div>
{site.published_deploy && (
<div className="mt-3 text-sm">
<div className="flex items-center gap-1">
<ClockIcon className="h-4 w-4 text-bolt-elements-item-contentAccent dark:text-bolt-elements-item-contentAccent" />
<span className="text-bolt-elements-textSecondary dark:text-bolt-elements-textSecondary">
Published {formatDistanceToNow(new Date(site.published_deploy.published_at))} ago
</span>
</div>
{site.published_deploy.branch && (
<div className="flex items-center gap-1 mt-1">
<CodeBracketIcon className="h-4 w-4 text-bolt-elements-item-contentAccent dark:text-bolt-elements-item-contentAccent" />
<span className="text-bolt-elements-textSecondary dark:text-bolt-elements-textSecondary">
Branch: {site.published_deploy.branch}
</span>
</div>
)}
</div>
)}
</>
)}
</div>
))}
</div>
</div>
{activeSiteIndex !== -1 && deploys.length > 0 && (
<div className="bg-bolt-elements-background dark:bg-bolt-elements-background-depth-1 border border-bolt-elements-borderColor dark:border-bolt-elements-borderColor rounded-lg p-4">
<div className="flex items-center justify-between mb-3">
<h4 className="text-sm font-medium flex items-center gap-2 text-bolt-elements-textPrimary dark:text-bolt-elements-textPrimary">
<BuildingLibraryIcon className="h-4 w-4 text-bolt-elements-item-contentAccent dark:text-bolt-elements-item-contentAccent" />
Recent Deployments
</h4>
</div>
<div className="space-y-2">
{deploys.map((deploy) => (
<div
key={deploy.id}
className="bg-bolt-elements-background dark:bg-bolt-elements-background-depth-1 border border-bolt-elements-borderColor dark:border-bolt-elements-borderColor rounded-lg p-3"
>
<div className="flex items-center justify-between">
<div className="flex items-center gap-2">
<Badge
variant={
deploy.state === 'ready'
? 'default'
: deploy.state === 'error'
? 'destructive'
: 'outline'
}
className="flex items-center gap-1"
>
{deploy.state === 'ready' ? (
<CheckCircleIcon className="h-4 w-4 text-green-500" />
) : deploy.state === 'error' ? (
<XCircleIcon className="h-4 w-4 text-red-500" />
) : (
<BuildingLibraryIcon className="h-4 w-4 text-bolt-elements-item-contentAccent" />
)}
<span className="text-bolt-elements-textPrimary dark:text-bolt-elements-textPrimary">
{deploy.state}
</span>
</Badge>
</div>
<span className="text-xs text-bolt-elements-textSecondary dark:text-bolt-elements-textSecondary">
{formatDistanceToNow(new Date(deploy.created_at))} ago
</span>
</div>
{deploy.branch && (
<div className="mt-2 text-xs text-bolt-elements-textSecondary dark:text-bolt-elements-textSecondary flex items-center gap-1">
<CodeBracketIcon className="h-3 w-3 text-bolt-elements-item-contentAccent dark:text-bolt-elements-item-contentAccent" />
<span className="text-bolt-elements-textSecondary dark:text-bolt-elements-textSecondary">
Branch: {deploy.branch}
</span>
</div>
)}
{deploy.deploy_url && (
<div className="mt-2 text-xs">
<a
href={deploy.deploy_url}
target="_blank"
rel="noopener noreferrer"
className="flex items-center gap-1 transition-colors text-bolt-elements-link-text hover:text-bolt-elements-link-textHover dark:text-white dark:hover:text-bolt-elements-link-textHover"
onClick={(e) => e.stopPropagation()}
>
<CloudIcon className="h-3 w-3 text-bolt-elements-item-contentAccent dark:text-bolt-elements-item-contentAccent" />
<span className="underline decoration-1 underline-offset-2">{deploy.deploy_url}</span>
</a>
</div>
)}
<div className="flex items-center gap-2 mt-2">
<Button
variant="outline"
size="sm"
onClick={() => handleDeploy(sites[activeSiteIndex].id, deploy.id, 'publish')}
disabled={isActionLoading}
className="flex items-center gap-1 text-bolt-elements-textPrimary dark:text-bolt-elements-textPrimary"
>
<BuildingLibraryIcon className="h-4 w-4 text-bolt-elements-item-contentAccent dark:text-bolt-elements-item-contentAccent" />
Publish
</Button>
{deploy.state === 'ready' ? (
<Button
variant="outline"
size="sm"
onClick={() => handleDeploy(sites[activeSiteIndex].id, deploy.id, 'lock')}
disabled={isActionLoading}
className="flex items-center gap-1 text-bolt-elements-textPrimary dark:text-bolt-elements-textPrimary"
>
<LockClosedIcon className="h-4 w-4 text-bolt-elements-item-contentAccent dark:text-bolt-elements-item-contentAccent" />
Lock
</Button>
) : (
<Button
variant="outline"
size="sm"
onClick={() => handleDeploy(sites[activeSiteIndex].id, deploy.id, 'unlock')}
disabled={isActionLoading}
className="flex items-center gap-1 text-bolt-elements-textPrimary dark:text-bolt-elements-textPrimary"
>
<LockOpenIcon className="h-4 w-4 text-bolt-elements-item-contentAccent dark:text-bolt-elements-item-contentAccent" />
Unlock
</Button>
)}
</div>
</div>
))}
</div>
</div>
)}
{activeSiteIndex !== -1 && builds.length > 0 && (
<div className="bg-bolt-elements-background dark:bg-bolt-elements-background-depth-1 border border-bolt-elements-borderColor dark:border-bolt-elements-borderColor rounded-lg p-4">
<div className="flex items-center justify-between mb-3">
<h4 className="text-sm font-medium flex items-center gap-2 text-bolt-elements-textPrimary dark:text-bolt-elements-textPrimary">
<CodeBracketIcon className="h-4 w-4 text-bolt-elements-item-contentAccent dark:text-bolt-elements-item-contentAccent" />
Recent Builds
</h4>
</div>
<div className="space-y-2">
{builds.map((build) => (
<div
key={build.id}
className="bg-bolt-elements-background dark:bg-bolt-elements-background-depth-1 border border-bolt-elements-borderColor dark:border-bolt-elements-borderColor rounded-lg p-3"
>
<div className="flex items-center justify-between">
<div className="flex items-center gap-2">
<Badge
variant={
build.done && !build.error ? 'default' : build.error ? 'destructive' : 'outline'
}
className="flex items-center gap-1"
>
{build.done && !build.error ? (
<CheckCircleIcon className="h-4 w-4" />
) : build.error ? (
<XCircleIcon className="h-4 w-4" />
) : (
<CodeBracketIcon className="h-4 w-4" />
)}
<span className="text-bolt-elements-textPrimary dark:text-bolt-elements-textPrimary">
{build.done ? (build.error ? 'Failed' : 'Completed') : 'In Progress'}
</span>
</Badge>
</div>
<span className="text-xs text-bolt-elements-textSecondary dark:text-bolt-elements-textSecondary">
{formatDistanceToNow(new Date(build.created_at))} ago
</span>
</div>
{build.error && (
<div className="mt-2 text-xs text-bolt-elements-textDestructive dark:text-bolt-elements-textDestructive flex items-center gap-1">
<XCircleIcon className="h-3 w-3 text-bolt-elements-textDestructive dark:text-bolt-elements-textDestructive" />
Error: {build.error}
</div>
)}
</div>
))}
</div>
</div>
)}
</div>
)}
</div>
</CollapsibleContent>
</Collapsible>
</div>
);
};
return (
<div className="space-y-6 bg-bolt-elements-background dark:bg-bolt-elements-background border border-bolt-elements-borderColor dark:border-bolt-elements-borderColor rounded-lg">
<div className="p-6">
<div className="flex items-center justify-between">
<div className="flex items-center gap-2">
<div className="text-[#00AD9F]">
<NetlifyLogo />
</div>
<h2 className="text-lg font-medium text-bolt-elements-textPrimary">Netlify Connection</h2>
</div>
</div>
{!connection.user ? (
<div className="mt-4">
<label className="block text-sm text-bolt-elements-textSecondary dark:text-bolt-elements-textSecondary mb-2">
API Token
</label>
<input
type="password"
value={tokenInput}
onChange={(e) => setTokenInput(e.target.value)}
placeholder="Enter your Netlify API token"
className={classNames(
'w-full px-3 py-2 rounded-lg text-sm',
'bg-[#F8F8F8] dark:bg-[#1A1A1A]',
'border border-[#E5E5E5] dark:border-[#333333]',
'text-bolt-elements-textPrimary placeholder-bolt-elements-textTertiary',
'focus:outline-none focus:ring-1 focus:ring-bolt-elements-borderColorActive',
'disabled:opacity-50',
)}
/>
<div className="mt-2 text-sm text-bolt-elements-textSecondary">
<a
href="https://app.netlify.com/user/applications#personal-access-tokens"
target="_blank"
rel="noopener noreferrer"
className="text-bolt-elements-borderColorActive hover:underline inline-flex items-center gap-1"
>
Get your token
<div className="i-ph:arrow-square-out w-4 h-4" />
</a>
</div>
<div className="flex items-center justify-between mt-4">
<button
onClick={handleConnect}
disabled={isConnecting || !tokenInput}
className={classNames(
'px-4 py-2 rounded-lg text-sm flex items-center gap-2',
'bg-[#303030] text-white',
'hover:bg-[#5E41D0] hover:text-white',
'disabled:opacity-50 disabled:cursor-not-allowed transition-all duration-200',
'transform active:scale-95',
)}
>
{isConnecting ? (
<>
<div className="i-ph:spinner-gap animate-spin" />
Connecting...
</>
) : (
<>
<div className="i-ph:plug-charging w-4 h-4" />
Connect
</>
)}
</button>
</div>
</div>
) : (
<div className="flex flex-col w-full gap-4 mt-4">
<div className="flex items-center gap-3">
<button
onClick={handleDisconnect}
className={classNames(
'px-4 py-2 rounded-lg text-sm flex items-center gap-2',
'bg-red-500 text-white',
'hover:bg-red-600',
)}
>
<div className="i-ph:plug w-4 h-4" />
Disconnect
</button>
<span className="text-sm text-bolt-elements-textSecondary flex items-center gap-1">
<div className="i-ph:check-circle w-4 h-4 text-green-500" />
Connected to Netlify
</span>
</div>
{renderStats()}
</div>
)}
</div>
</div>
);
}

View File

@@ -0,0 +1,290 @@
import React, { useEffect, useState } from 'react';
import { motion } from 'framer-motion';
import { toast } from 'react-toastify';
import { useStore } from '@nanostores/react';
import { logStore } from '~/lib/stores/logs';
import { classNames } from '~/utils/classNames';
import {
vercelConnection,
isConnecting,
isFetchingStats,
updateVercelConnection,
fetchVercelStats,
} from '~/lib/stores/vercel';
export default function VercelConnection() {
const connection = useStore(vercelConnection);
const connecting = useStore(isConnecting);
const fetchingStats = useStore(isFetchingStats);
const [isProjectsExpanded, setIsProjectsExpanded] = useState(false);
useEffect(() => {
const fetchProjects = async () => {
if (connection.user && connection.token) {
await fetchVercelStats(connection.token);
}
};
fetchProjects();
}, [connection.user, connection.token]);
const handleConnect = async (event: React.FormEvent) => {
event.preventDefault();
isConnecting.set(true);
try {
const response = await fetch('https://api.vercel.com/v2/user', {
headers: {
Authorization: `Bearer ${connection.token}`,
'Content-Type': 'application/json',
},
});
if (!response.ok) {
throw new Error('Invalid token or unauthorized');
}
const userData = (await response.json()) as any;
updateVercelConnection({
user: userData.user || userData, // Handle both possible structures
token: connection.token,
});
await fetchVercelStats(connection.token);
toast.success('Successfully connected to Vercel');
} catch (error) {
console.error('Auth error:', error);
logStore.logError('Failed to authenticate with Vercel', { error });
toast.error('Failed to connect to Vercel');
updateVercelConnection({ user: null, token: '' });
} finally {
isConnecting.set(false);
}
};
const handleDisconnect = () => {
updateVercelConnection({ user: null, token: '' });
toast.success('Disconnected from Vercel');
};
console.log('connection', connection);
return (
<motion.div
className="bg-[#FFFFFF] dark:bg-[#0A0A0A] rounded-lg border border-[#E5E5E5] dark:border-[#1A1A1A]"
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ delay: 0.3 }}
>
<div className="p-6 space-y-6">
<div className="flex items-center justify-between">
<div className="flex items-center gap-2">
<img
className="w-5 h-5 dark:invert"
height="24"
width="24"
crossOrigin="anonymous"
src={`https://cdn.simpleicons.org/vercel/black`}
/>
<h3 className="text-base font-medium text-bolt-elements-textPrimary">Vercel Connection</h3>
</div>
</div>
{!connection.user ? (
<div className="space-y-4">
<div>
<label className="block text-sm text-bolt-elements-textSecondary mb-2">Personal Access Token</label>
<input
type="password"
value={connection.token}
onChange={(e) => updateVercelConnection({ ...connection, token: e.target.value })}
disabled={connecting}
placeholder="Enter your Vercel personal access token"
className={classNames(
'w-full px-3 py-2 rounded-lg text-sm',
'bg-[#F8F8F8] dark:bg-[#1A1A1A]',
'border border-[#E5E5E5] dark:border-[#333333]',
'text-bolt-elements-textPrimary placeholder-bolt-elements-textTertiary',
'focus:outline-none focus:ring-1 focus:ring-bolt-elements-borderColorActive',
'disabled:opacity-50',
)}
/>
<div className="mt-2 text-sm text-bolt-elements-textSecondary">
<a
href="https://vercel.com/account/tokens"
target="_blank"
rel="noopener noreferrer"
className="text-bolt-elements-borderColorActive hover:underline inline-flex items-center gap-1"
>
Get your token
<div className="i-ph:arrow-square-out w-4 h-4" />
</a>
</div>
</div>
<button
onClick={handleConnect}
disabled={connecting || !connection.token}
className={classNames(
'px-4 py-2 rounded-lg text-sm flex items-center gap-2',
'bg-[#303030] text-white',
'hover:bg-[#5E41D0] hover:text-white',
'disabled:opacity-50 disabled:cursor-not-allowed transition-all duration-200',
'transform active:scale-95',
)}
>
{connecting ? (
<>
<div className="i-ph:spinner-gap animate-spin" />
Connecting...
</>
) : (
<>
<div className="i-ph:plug-charging w-4 h-4" />
Connect
</>
)}
</button>
</div>
) : (
<div className="space-y-6">
<div className="flex items-center justify-between">
<div className="flex items-center gap-3">
<button
onClick={handleDisconnect}
className={classNames(
'px-4 py-2 rounded-lg text-sm flex items-center gap-2',
'bg-red-500 text-white',
'hover:bg-red-600',
)}
>
<div className="i-ph:plug w-4 h-4" />
Disconnect
</button>
<span className="text-sm text-bolt-elements-textSecondary flex items-center gap-1">
<div className="i-ph:check-circle w-4 h-4 text-green-500" />
Connected to Vercel
</span>
</div>
</div>
<div className="flex items-center gap-4 p-4 bg-[#F8F8F8] dark:bg-[#1A1A1A] rounded-lg">
{/* Debug output */}
<pre className="hidden">{JSON.stringify(connection.user, null, 2)}</pre>
<img
src={`https://vercel.com/api/www/avatar?u=${connection.user?.username || connection.user?.user?.username}`}
referrerPolicy="no-referrer"
crossOrigin="anonymous"
alt="User Avatar"
className="w-12 h-12 rounded-full border-2 border-bolt-elements-borderColorActive"
/>
<div>
<h4 className="text-sm font-medium text-bolt-elements-textPrimary">
{connection.user?.username || connection.user?.user?.username || 'Vercel User'}
</h4>
<p className="text-sm text-bolt-elements-textSecondary">
{connection.user?.email || connection.user?.user?.email || 'No email available'}
</p>
</div>
</div>
{fetchingStats ? (
<div className="flex items-center gap-2 text-sm text-bolt-elements-textSecondary">
<div className="i-ph:spinner-gap w-4 h-4 animate-spin" />
Fetching Vercel projects...
</div>
) : (
<div>
<button
onClick={() => setIsProjectsExpanded(!isProjectsExpanded)}
className="w-full bg-transparent text-left text-sm font-medium text-bolt-elements-textPrimary mb-3 flex items-center gap-2"
>
<div className="i-ph:buildings w-4 h-4" />
Your Projects ({connection.stats?.totalProjects || 0})
<div
className={classNames(
'i-ph:caret-down w-4 h-4 ml-auto transition-transform',
isProjectsExpanded ? 'rotate-180' : '',
)}
/>
</button>
{isProjectsExpanded && connection.stats?.projects?.length ? (
<div className="grid gap-3">
{connection.stats.projects.map((project) => (
<a
key={project.id}
href={`https://vercel.com/dashboard/${project.id}`}
target="_blank"
rel="noopener noreferrer"
className="block p-4 rounded-lg border border-bolt-elements-borderColor hover:border-bolt-elements-borderColorActive transition-colors"
>
<div className="flex items-center justify-between">
<div>
<h5 className="text-sm font-medium text-bolt-elements-textPrimary flex items-center gap-2">
<div className="i-ph:globe w-4 h-4 text-bolt-elements-borderColorActive" />
{project.name}
</h5>
<div className="flex items-center gap-2 mt-2 text-xs text-bolt-elements-textSecondary">
{project.targets?.production?.alias && project.targets.production.alias.length > 0 ? (
<>
<a
href={`https://${project.targets.production.alias.find((a: string) => a.endsWith('.vercel.app') && !a.includes('-projects.vercel.app')) || project.targets.production.alias[0]}`}
target="_blank"
rel="noopener noreferrer"
className="hover:text-bolt-elements-borderColorActive"
>
{project.targets.production.alias.find(
(a: string) => a.endsWith('.vercel.app') && !a.includes('-projects.vercel.app'),
) || project.targets.production.alias[0]}
</a>
<span></span>
<span className="flex items-center gap-1">
<div className="i-ph:clock w-3 h-3" />
{new Date(project.createdAt).toLocaleDateString()}
</span>
</>
) : project.latestDeployments && project.latestDeployments.length > 0 ? (
<>
<a
href={`https://${project.latestDeployments[0].url}`}
target="_blank"
rel="noopener noreferrer"
className="hover:text-bolt-elements-borderColorActive"
>
{project.latestDeployments[0].url}
</a>
<span></span>
<span className="flex items-center gap-1">
<div className="i-ph:clock w-3 h-3" />
{new Date(project.latestDeployments[0].created).toLocaleDateString()}
</span>
</>
) : null}
</div>
</div>
{project.framework && (
<div className="text-xs text-bolt-elements-textSecondary px-2 py-1 rounded-md bg-[#F0F0F0] dark:bg-[#252525]">
<span className="flex items-center gap-1">
<div className="i-ph:code w-3 h-3" />
{project.framework}
</span>
</div>
)}
</div>
</a>
))}
</div>
) : isProjectsExpanded ? (
<div className="text-sm text-bolt-elements-textSecondary flex items-center gap-2">
<div className="i-ph:info w-4 h-4" />
No projects found in your Vercel account
</div>
) : null}
</div>
)}
</div>
)}
</div>
</motion.div>
);
}

View File

@@ -0,0 +1,183 @@
import React, { useEffect } from 'react';
import { classNames } from '~/utils/classNames';
import type { GitHubAuthState } from '~/components/@settings/tabs/connections/types/GitHub';
import Cookies from 'js-cookie';
import { getLocalStorage } from '~/lib/persistence';
const GITHUB_TOKEN_KEY = 'github_token';
interface ConnectionFormProps {
authState: GitHubAuthState;
setAuthState: React.Dispatch<React.SetStateAction<GitHubAuthState>>;
onSave: (e: React.FormEvent) => void;
onDisconnect: () => void;
}
export function ConnectionForm({ authState, setAuthState, onSave, onDisconnect }: ConnectionFormProps) {
// Check for saved token on mount
useEffect(() => {
const savedToken = Cookies.get(GITHUB_TOKEN_KEY) || Cookies.get('githubToken') || getLocalStorage(GITHUB_TOKEN_KEY);
if (savedToken && !authState.tokenInfo?.token) {
setAuthState((prev: GitHubAuthState) => ({
...prev,
tokenInfo: {
token: savedToken,
scope: [],
avatar_url: '',
name: null,
created_at: new Date().toISOString(),
followers: 0,
},
}));
// Ensure the token is also saved with the correct key for API requests
Cookies.set('githubToken', savedToken);
}
}, []);
return (
<div className="rounded-xl bg-white dark:bg-[#0A0A0A] border border-[#E5E5E5] dark:border-[#1A1A1A] overflow-hidden">
<div className="p-6">
<div className="flex items-center justify-between mb-6">
<div className="flex items-center gap-3">
<div className="p-2 rounded-lg bg-[#F5F5F5] dark:bg-[#1A1A1A] border border-[#E5E5E5] dark:border-[#1A1A1A]">
<div className="i-ph:plug-fill text-bolt-elements-textTertiary" />
</div>
<div>
<h3 className="text-lg font-medium text-bolt-elements-textPrimary">Connection Settings</h3>
<p className="text-sm text-bolt-elements-textSecondary">Configure your GitHub connection</p>
</div>
</div>
</div>
<form onSubmit={onSave} className="space-y-4">
<div>
<label htmlFor="username" className="block text-sm font-medium text-bolt-elements-textSecondary mb-2">
GitHub Username
</label>
<input
id="username"
type="text"
value={authState.username}
onChange={(e) => setAuthState((prev: GitHubAuthState) => ({ ...prev, username: e.target.value }))}
className={classNames(
'w-full px-4 py-2.5 bg-[#F5F5F5] dark:bg-[#1A1A1A] border rounded-lg',
'text-bolt-elements-textPrimary placeholder-bolt-elements-textTertiary text-base',
'border-[#E5E5E5] dark:border-[#1A1A1A]',
'focus:ring-2 focus:ring-purple-500/50 focus:border-purple-500',
'transition-all duration-200',
)}
placeholder="e.g., octocat"
/>
</div>
<div>
<div className="flex items-center justify-between mb-2">
<label htmlFor="token" className="block text-sm font-medium text-bolt-elements-textSecondary">
Personal Access Token
</label>
<a
href="https://github.com/settings/tokens/new?scopes=repo,user,read:org,workflow,delete_repo,write:packages,read:packages"
target="_blank"
rel="noopener noreferrer"
className={classNames(
'inline-flex items-center gap-1.5 text-xs',
'text-purple-500 hover:text-purple-600 dark:text-purple-400 dark:hover:text-purple-300',
'transition-colors duration-200',
)}
>
<span>Generate new token</span>
<div className="i-ph:plus-circle" />
</a>
</div>
<input
id="token"
type="password"
value={authState.tokenInfo?.token || ''}
onChange={(e) =>
setAuthState((prev: GitHubAuthState) => ({
...prev,
tokenInfo: {
token: e.target.value,
scope: [],
avatar_url: '',
name: null,
created_at: new Date().toISOString(),
followers: 0,
},
username: '',
isConnected: false,
isVerifying: false,
isLoadingRepos: false,
}))
}
className={classNames(
'w-full px-4 py-2.5 bg-[#F5F5F5] dark:bg-[#1A1A1A] border rounded-lg',
'text-bolt-elements-textPrimary placeholder-bolt-elements-textTertiary text-base',
'border-[#E5E5E5] dark:border-[#1A1A1A]',
'focus:ring-2 focus:ring-purple-500/50 focus:border-purple-500',
'transition-all duration-200',
)}
placeholder="ghp_xxxxxxxxxxxx"
/>
</div>
<div className="flex items-center justify-between pt-4 border-t border-[#E5E5E5] dark:border-[#1A1A1A]">
<div className="flex items-center gap-4">
{!authState.isConnected ? (
<button
type="submit"
disabled={authState.isVerifying || !authState.username || !authState.tokenInfo?.token}
className={classNames(
'inline-flex items-center gap-2 px-4 py-2 text-sm font-medium rounded-lg transition-colors',
'bg-purple-500 hover:bg-purple-600',
'text-white',
'disabled:opacity-50 disabled:cursor-not-allowed',
)}
>
{authState.isVerifying ? (
<>
<div className="i-ph:spinner animate-spin" />
<span>Verifying...</span>
</>
) : (
<>
<div className="i-ph:plug-fill" />
<span>Connect</span>
</>
)}
</button>
) : (
<>
<button
onClick={onDisconnect}
className={classNames(
'inline-flex items-center gap-2 px-4 py-2 text-sm font-medium rounded-lg transition-colors',
'bg-[#F5F5F5] hover:bg-red-500/10 hover:text-red-500',
'dark:bg-[#1A1A1A] dark:hover:bg-red-500/20 dark:hover:text-red-500',
'text-bolt-elements-textPrimary',
)}
>
<div className="i-ph:plug-fill" />
<span>Disconnect</span>
</button>
<span className="inline-flex items-center gap-2 px-3 py-1.5 text-sm text-green-600 dark:text-green-400 bg-green-500/5 rounded-lg border border-green-500/20">
<div className="i-ph:check-circle-fill" />
<span>Connected</span>
</span>
</>
)}
</div>
{authState.rateLimits && (
<div className="flex items-center gap-2 text-sm text-bolt-elements-textTertiary">
<div className="i-ph:clock-countdown opacity-60" />
<span>Rate limit resets at {authState.rateLimits.reset.toLocaleTimeString()}</span>
</div>
)}
</div>
</form>
</div>
</div>
);
}

View File

@@ -0,0 +1,150 @@
import { useState } from 'react';
import * as Dialog from '@radix-ui/react-dialog';
import { classNames } from '~/utils/classNames';
import type { GitHubRepoInfo } from '~/components/@settings/tabs/connections/types/GitHub';
import { GitBranch } from '@phosphor-icons/react';
interface GitHubBranch {
name: string;
default?: boolean;
}
interface CreateBranchDialogProps {
isOpen: boolean;
onClose: () => void;
onConfirm: (branchName: string, sourceBranch: string) => void;
repository: GitHubRepoInfo;
branches?: GitHubBranch[];
}
export function CreateBranchDialog({ isOpen, onClose, onConfirm, repository, branches }: CreateBranchDialogProps) {
const [branchName, setBranchName] = useState('');
const [sourceBranch, setSourceBranch] = useState(branches?.find((b) => b.default)?.name || 'main');
const handleSubmit = (e: React.FormEvent) => {
e.preventDefault();
onConfirm(branchName, sourceBranch);
setBranchName('');
onClose();
};
return (
<Dialog.Root open={isOpen} onOpenChange={onClose}>
<Dialog.Portal>
<Dialog.Overlay className="fixed inset-0 bg-black/50 dark:bg-black/80" />
<Dialog.Content
className={classNames(
'fixed top-[50%] left-[50%] translate-x-[-50%] translate-y-[-50%]',
'w-full max-w-md p-6 rounded-xl shadow-lg',
'bg-white dark:bg-[#0A0A0A]',
'border border-[#E5E5E5] dark:border-[#1A1A1A]',
)}
>
<Dialog.Title className="text-lg font-medium text-bolt-elements-textPrimary mb-4">
Create New Branch
</Dialog.Title>
<form onSubmit={handleSubmit}>
<div className="space-y-4">
<div>
<label htmlFor="branchName" className="block text-sm font-medium text-bolt-elements-textSecondary mb-2">
Branch Name
</label>
<input
id="branchName"
type="text"
value={branchName}
onChange={(e) => setBranchName(e.target.value)}
placeholder="feature/my-new-branch"
className={classNames(
'w-full px-3 py-2 rounded-lg',
'bg-[#F5F5F5] dark:bg-[#1A1A1A]',
'border border-[#E5E5E5] dark:border-[#1A1A1A]',
'text-bolt-elements-textPrimary placeholder:text-bolt-elements-textTertiary',
'focus:outline-none focus:ring-2 focus:ring-purple-500/50',
)}
required
/>
</div>
<div>
<label
htmlFor="sourceBranch"
className="block text-sm font-medium text-bolt-elements-textSecondary mb-2"
>
Source Branch
</label>
<select
id="sourceBranch"
value={sourceBranch}
onChange={(e) => setSourceBranch(e.target.value)}
className={classNames(
'w-full px-3 py-2 rounded-lg',
'bg-[#F5F5F5] dark:bg-[#1A1A1A]',
'border border-[#E5E5E5] dark:border-[#1A1A1A]',
'text-bolt-elements-textPrimary',
'focus:outline-none focus:ring-2 focus:ring-purple-500/50',
)}
>
{branches?.map((branch) => (
<option key={branch.name} value={branch.name}>
{branch.name} {branch.default ? '(default)' : ''}
</option>
))}
</select>
</div>
<div className="mt-4 p-3 bg-[#F5F5F5] dark:bg-[#1A1A1A] rounded-lg">
<h4 className="text-sm font-medium text-bolt-elements-textSecondary mb-2">Branch Overview</h4>
<ul className="space-y-2 text-sm text-bolt-elements-textSecondary">
<li className="flex items-center gap-2">
<GitBranch className="text-lg" />
Repository: {repository.name}
</li>
{branchName && (
<li className="flex items-center gap-2">
<div className="i-ph:check-circle text-green-500" />
New branch will be created as: {branchName}
</li>
)}
<li className="flex items-center gap-2">
<div className="i-ph:check-circle text-green-500" />
Based on: {sourceBranch}
</li>
</ul>
</div>
</div>
<div className="mt-6 flex justify-end gap-3">
<button
type="button"
onClick={onClose}
className={classNames(
'px-4 py-2 rounded-lg text-sm font-medium',
'text-bolt-elements-textPrimary',
'bg-[#F5F5F5] dark:bg-[#1A1A1A]',
'hover:bg-purple-500/10 hover:text-purple-500',
'dark:hover:bg-purple-500/20 dark:hover:text-purple-500',
'transition-colors',
)}
>
Cancel
</button>
<button
type="submit"
className={classNames(
'px-4 py-2 rounded-lg text-sm font-medium',
'text-white bg-purple-500',
'hover:bg-purple-600',
'transition-colors',
)}
>
Create Branch
</button>
</div>
</form>
</Dialog.Content>
</Dialog.Portal>
</Dialog.Root>
);
}

View File

@@ -0,0 +1,190 @@
import React, { useState } from 'react';
import * as Dialog from '@radix-ui/react-dialog';
import { motion } from 'framer-motion';
import { toast } from 'react-toastify';
import Cookies from 'js-cookie';
import type { GitHubUserResponse } from '~/types/GitHub';
interface GitHubAuthDialogProps {
isOpen: boolean;
onClose: () => void;
}
export function GitHubAuthDialog({ isOpen, onClose }: GitHubAuthDialogProps) {
const [token, setToken] = useState('');
const [isSubmitting, setIsSubmitting] = useState(false);
const [tokenType, setTokenType] = useState<'classic' | 'fine-grained'>('classic');
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
if (!token.trim()) {
return;
}
setIsSubmitting(true);
try {
const response = await fetch('https://api.github.com/user', {
headers: {
Accept: 'application/vnd.github.v3+json',
Authorization: `Bearer ${token}`,
},
});
if (response.ok) {
const userData = (await response.json()) as GitHubUserResponse;
// Save connection data
const connectionData = {
token,
tokenType,
user: {
login: userData.login,
avatar_url: userData.avatar_url,
name: userData.name || userData.login,
},
connected_at: new Date().toISOString(),
};
localStorage.setItem('github_connection', JSON.stringify(connectionData));
// Set cookies for API requests
Cookies.set('githubToken', token);
Cookies.set('githubUsername', userData.login);
Cookies.set('git:github.com', JSON.stringify({ username: token, password: 'x-oauth-basic' }));
toast.success(`Successfully connected as ${userData.login}`);
setToken('');
onClose();
} else {
if (response.status === 401) {
toast.error('Invalid GitHub token. Please check and try again.');
} else {
toast.error(`GitHub API error: ${response.status} ${response.statusText}`);
}
}
} catch (error) {
console.error('Error connecting to GitHub:', error);
toast.error('Failed to connect to GitHub. Please try again.');
} finally {
setIsSubmitting(false);
}
};
return (
<Dialog.Root open={isOpen} onOpenChange={(open) => !open && onClose()}>
<Dialog.Portal>
<Dialog.Overlay className="fixed inset-0 bg-black/50 backdrop-blur-sm z-[9999]" />
<div className="fixed inset-0 flex items-center justify-center z-[9999]">
<motion.div
initial={{ opacity: 0, scale: 0.95 }}
animate={{ opacity: 1, scale: 1 }}
exit={{ opacity: 0, scale: 0.95 }}
transition={{ duration: 0.2 }}
>
<Dialog.Content className="bg-white dark:bg-[#1A1A1A] rounded-lg shadow-xl max-w-sm w-full mx-4 overflow-hidden">
<div className="p-4 space-y-3">
<h2 className="text-lg font-semibold text-[#111111] dark:text-white">Access Private Repositories</h2>
<p className="text-sm text-[#666666] dark:text-[#999999]">
To access private repositories, you need to connect your GitHub account by providing a personal access
token.
</p>
<div className="bg-[#F9F9F9] dark:bg-[#252525] p-4 rounded-lg space-y-3">
<h3 className="text-base font-medium text-[#111111] dark:text-white">Connect with GitHub Token</h3>
<form onSubmit={handleSubmit} className="space-y-3">
<div>
<label className="block text-sm text-[#666666] dark:text-[#999999] mb-1">
GitHub Personal Access Token
</label>
<input
type="password"
value={token}
onChange={(e) => setToken(e.target.value)}
placeholder="ghp_xxxxxxxxxxxxxxxxxxxx"
className="w-full px-3 py-1.5 rounded-lg border border-[#E5E5E5] dark:border-[#333333] bg-white dark:bg-[#1A1A1A] text-[#111111] dark:text-white placeholder-[#999999] text-sm"
/>
<div className="mt-1 text-xs text-[#666666] dark:text-[#999999]">
Get your token at{' '}
<a
href="https://github.com/settings/tokens"
target="_blank"
rel="noopener noreferrer"
className="text-purple-500 hover:underline"
>
github.com/settings/tokens
</a>
</div>
</div>
<div className="space-y-1">
<label className="block text-sm text-[#666666] dark:text-[#999999]">Token Type</label>
<div className="flex gap-4">
<label className="flex items-center gap-2">
<input
type="radio"
checked={tokenType === 'classic'}
onChange={() => setTokenType('classic')}
className="w-3.5 h-3.5 accent-purple-500"
/>
<span className="text-sm text-[#111111] dark:text-white">Classic</span>
</label>
<label className="flex items-center gap-2">
<input
type="radio"
checked={tokenType === 'fine-grained'}
onChange={() => setTokenType('fine-grained')}
className="w-3.5 h-3.5 accent-purple-500"
/>
<span className="text-sm text-[#111111] dark:text-white">Fine-grained</span>
</label>
</div>
</div>
<button
type="submit"
disabled={isSubmitting}
className="w-full py-2 bg-purple-500 hover:bg-purple-600 text-white rounded-lg transition-colors disabled:opacity-50 disabled:cursor-not-allowed text-sm"
>
{isSubmitting ? 'Connecting...' : 'Connect to GitHub'}
</button>
</form>
</div>
<div className="bg-amber-50 dark:bg-amber-900/20 p-3 rounded-lg space-y-1.5">
<h3 className="text-sm text-amber-800 dark:text-amber-300 font-medium flex items-center gap-1.5">
<span className="i-ph:warning-circle w-4 h-4" />
Accessing Private Repositories
</h3>
<p className="text-xs text-amber-700 dark:text-amber-400">
Important things to know about accessing private repositories:
</p>
<ul className="list-disc pl-4 text-xs text-amber-700 dark:text-amber-400 space-y-0.5">
<li>You must be granted access to the repository by its owner</li>
<li>Your GitHub token must have the 'repo' scope</li>
<li>For organization repositories, you may need additional permissions</li>
<li>No token can give you access to repositories you don't have permission for</li>
</ul>
</div>
</div>
<div className="border-t border-[#E5E5E5] dark:border-[#333333] p-3 flex justify-end">
<Dialog.Close asChild>
<button
onClick={onClose}
className="px-4 py-1.5 bg-transparent bg-[#F5F5F5] hover:bg-[#E5E5E5] dark:bg-[#252525] dark:hover:bg-[#333333] rounded-lg text-[#111111] dark:text-white transition-colors text-sm"
>
Close
</button>
</Dialog.Close>
</div>
</Dialog.Content>
</motion.div>
</div>
</Dialog.Portal>
</Dialog.Root>
);
}

View File

@@ -0,0 +1,717 @@
import * as Dialog from '@radix-ui/react-dialog';
import { useState, useEffect, useCallback } from 'react';
import { toast } from 'react-toastify';
import { motion } from 'framer-motion';
import { Octokit } from '@octokit/rest';
// Internal imports
import { getLocalStorage } from '~/lib/persistence';
import { classNames } from '~/utils/classNames';
import type { GitHubUserResponse } from '~/types/GitHub';
import { logStore } from '~/lib/stores/logs';
import { workbenchStore } from '~/lib/stores/workbench';
import { extractRelativePath } from '~/utils/diff';
import { formatSize } from '~/utils/formatSize';
import type { FileMap, File } from '~/lib/stores/files';
// UI Components
import { Badge, EmptyState, StatusIndicator, SearchInput } from '~/components/ui';
interface PushToGitHubDialogProps {
isOpen: boolean;
onClose: () => void;
onPush: (repoName: string, username?: string, token?: string, isPrivate?: boolean) => Promise<string>;
}
interface GitHubRepo {
name: string;
full_name: string;
html_url: string;
description: string;
stargazers_count: number;
forks_count: number;
default_branch: string;
updated_at: string;
language: string;
private: boolean;
}
export function PushToGitHubDialog({ isOpen, onClose, onPush }: PushToGitHubDialogProps) {
const [repoName, setRepoName] = useState('');
const [isPrivate, setIsPrivate] = useState(false);
const [isLoading, setIsLoading] = useState(false);
const [user, setUser] = useState<GitHubUserResponse | null>(null);
const [recentRepos, setRecentRepos] = useState<GitHubRepo[]>([]);
const [filteredRepos, setFilteredRepos] = useState<GitHubRepo[]>([]);
const [repoSearchQuery, setRepoSearchQuery] = useState('');
const [isFetchingRepos, setIsFetchingRepos] = useState(false);
const [showSuccessDialog, setShowSuccessDialog] = useState(false);
const [createdRepoUrl, setCreatedRepoUrl] = useState('');
const [pushedFiles, setPushedFiles] = useState<{ path: string; size: number }[]>([]);
// Load GitHub connection on mount
useEffect(() => {
if (isOpen) {
const connection = getLocalStorage('github_connection');
if (connection?.user && connection?.token) {
setUser(connection.user);
// Only fetch if we have both user and token
if (connection.token.trim()) {
fetchRecentRepos(connection.token);
}
}
}
}, [isOpen]);
/*
* Filter repositories based on search query
* const debouncedSetRepoSearchQuery = useDebouncedCallback((value: string) => setRepoSearchQuery(value), 300);
*/
useEffect(() => {
if (recentRepos.length === 0) {
setFilteredRepos([]);
return;
}
if (!repoSearchQuery.trim()) {
setFilteredRepos(recentRepos);
return;
}
const query = repoSearchQuery.toLowerCase().trim();
const filtered = recentRepos.filter(
(repo) =>
repo.name.toLowerCase().includes(query) ||
(repo.description && repo.description.toLowerCase().includes(query)) ||
(repo.language && repo.language.toLowerCase().includes(query)),
);
setFilteredRepos(filtered);
}, [recentRepos, repoSearchQuery]);
const fetchRecentRepos = useCallback(async (token: string) => {
if (!token) {
logStore.logError('No GitHub token available');
toast.error('GitHub authentication required');
return;
}
try {
setIsFetchingRepos(true);
console.log('Fetching GitHub repositories with token:', token.substring(0, 5) + '...');
// Fetch ALL repos by paginating through all pages
let allRepos: GitHubRepo[] = [];
let page = 1;
let hasMore = true;
while (hasMore) {
const requestUrl = `https://api.github.com/user/repos?sort=updated&per_page=100&page=${page}&affiliation=owner,organization_member`;
const response = await fetch(requestUrl, {
headers: {
Accept: 'application/vnd.github.v3+json',
Authorization: `Bearer ${token.trim()}`,
},
});
if (!response.ok) {
let errorData: { message?: string } = {};
try {
errorData = await response.json();
console.error('Error response data:', errorData);
} catch (e) {
errorData = { message: 'Could not parse error response' };
console.error('Could not parse error response:', e);
}
if (response.status === 401) {
toast.error('GitHub token expired. Please reconnect your account.');
// Clear invalid token
const connection = getLocalStorage('github_connection');
if (connection) {
localStorage.removeItem('github_connection');
setUser(null);
}
} else if (response.status === 403 && response.headers.get('x-ratelimit-remaining') === '0') {
// Rate limit exceeded
const resetTime = response.headers.get('x-ratelimit-reset');
const resetDate = resetTime ? new Date(parseInt(resetTime) * 1000).toLocaleTimeString() : 'soon';
toast.error(`GitHub API rate limit exceeded. Limit resets at ${resetDate}`);
} else {
logStore.logError('Failed to fetch GitHub repositories', {
status: response.status,
statusText: response.statusText,
error: errorData,
});
toast.error(`Failed to fetch repositories: ${errorData.message || response.statusText}`);
}
return;
}
try {
const repos = (await response.json()) as GitHubRepo[];
allRepos = allRepos.concat(repos);
if (repos.length < 100) {
hasMore = false;
} else {
page += 1;
}
} catch (parseError) {
console.error('Error parsing JSON response:', parseError);
logStore.logError('Failed to parse GitHub repositories response', { parseError });
toast.error('Failed to parse repository data');
setRecentRepos([]);
return;
}
}
setRecentRepos(allRepos);
} catch (error) {
console.error('Exception while fetching GitHub repositories:', error);
logStore.logError('Failed to fetch GitHub repositories', { error });
toast.error('Failed to fetch recent repositories');
} finally {
setIsFetchingRepos(false);
}
}, []);
async function handleSubmit(e: React.FormEvent) {
e.preventDefault();
const connection = getLocalStorage('github_connection');
if (!connection?.token || !connection?.user) {
toast.error('Please connect your GitHub account in Settings > Connections first');
return;
}
if (!repoName.trim()) {
toast.error('Repository name is required');
return;
}
setIsLoading(true);
try {
// Check if repository exists first
const octokit = new Octokit({ auth: connection.token });
try {
const { data: existingRepo } = await octokit.repos.get({
owner: connection.user.login,
repo: repoName,
});
// If we get here, the repo exists
let confirmMessage = `Repository "${repoName}" already exists. Do you want to update it? This will add or modify files in the repository.`;
// Add visibility change warning if needed
if (existingRepo.private !== isPrivate) {
const visibilityChange = isPrivate
? 'This will also change the repository from public to private.'
: 'This will also change the repository from private to public.';
confirmMessage += `\n\n${visibilityChange}`;
}
const confirmOverwrite = window.confirm(confirmMessage);
if (!confirmOverwrite) {
setIsLoading(false);
return;
}
} catch (error) {
// 404 means repo doesn't exist, which is what we want for new repos
if (error instanceof Error && 'status' in error && error.status !== 404) {
throw error;
}
}
const repoUrl = await onPush(repoName, connection.user.login, connection.token, isPrivate);
setCreatedRepoUrl(repoUrl);
// Get list of pushed files
const files = workbenchStore.files.get();
const filesList = Object.entries(files as FileMap)
.filter(([, dirent]) => dirent?.type === 'file' && !dirent.isBinary)
.map(([path, dirent]) => ({
path: extractRelativePath(path),
size: new TextEncoder().encode((dirent as File).content || '').length,
}));
setPushedFiles(filesList);
setShowSuccessDialog(true);
} catch (error) {
console.error('Error pushing to GitHub:', error);
toast.error('Failed to push to GitHub. Please check your repository name and try again.');
} finally {
setIsLoading(false);
}
}
const handleClose = () => {
setRepoName('');
setIsPrivate(false);
setShowSuccessDialog(false);
setCreatedRepoUrl('');
onClose();
};
// Success Dialog
if (showSuccessDialog) {
return (
<Dialog.Root open={isOpen} onOpenChange={(open) => !open && handleClose()}>
<Dialog.Portal>
<Dialog.Overlay className="fixed inset-0 bg-black/50 backdrop-blur-sm z-[9999]" />
<div className="fixed inset-0 flex items-center justify-center z-[9999]">
<motion.div
initial={{ opacity: 0, scale: 0.95 }}
animate={{ opacity: 1, scale: 1 }}
exit={{ opacity: 0, scale: 0.95 }}
transition={{ duration: 0.2 }}
className="w-[90vw] md:w-[600px] max-h-[85vh] overflow-y-auto"
>
<Dialog.Content
className="bg-white dark:bg-bolt-elements-background-depth-1 rounded-lg border border-bolt-elements-borderColor dark:border-bolt-elements-borderColor-dark shadow-xl"
aria-describedby="success-dialog-description"
>
<div className="p-6 space-y-4">
<div className="flex items-center justify-between">
<div className="flex items-center gap-3">
<div className="w-10 h-10 rounded-xl bg-green-500/10 flex items-center justify-center text-green-500">
<div className="i-ph:check-circle w-5 h-5" />
</div>
<div>
<h3 className="text-lg font-medium text-bolt-elements-textPrimary dark:text-bolt-elements-textPrimary-dark">
Successfully pushed to GitHub
</h3>
<p
id="success-dialog-description"
className="text-sm text-bolt-elements-textSecondary dark:text-bolt-elements-textSecondary-dark"
>
Your code is now available on GitHub
</p>
</div>
</div>
<Dialog.Close asChild>
<button
onClick={handleClose}
className="p-2 rounded-lg transition-all duration-200 ease-in-out bg-transparent text-bolt-elements-textTertiary hover:text-bolt-elements-textPrimary dark:text-bolt-elements-textTertiary-dark dark:hover:text-bolt-elements-textPrimary-dark hover:bg-bolt-elements-background-depth-2 dark:hover:bg-bolt-elements-background-depth-3 focus:outline-none focus:ring-2 focus:ring-bolt-elements-borderColor dark:focus:ring-bolt-elements-borderColor-dark"
>
<span className="i-ph:x block w-5 h-5" aria-hidden="true" />
<span className="sr-only">Close dialog</span>
</button>
</Dialog.Close>
</div>
<div className="bg-bolt-elements-background-depth-2 dark:bg-bolt-elements-background-depth-3 rounded-lg p-4 text-left border border-bolt-elements-borderColor dark:border-bolt-elements-borderColor-dark">
<p className="text-sm font-medium text-bolt-elements-textPrimary dark:text-bolt-elements-textPrimary-dark mb-2 flex items-center gap-2">
<span className="i-ph:github-logo w-4 h-4 text-purple-500" />
Repository URL
</p>
<div className="flex items-center gap-2">
<code className="flex-1 text-sm bg-bolt-elements-background-depth-1 dark:bg-bolt-elements-background-depth-4 px-3 py-2 rounded border border-bolt-elements-borderColor dark:border-bolt-elements-borderColor-dark text-bolt-elements-textPrimary dark:text-bolt-elements-textPrimary-dark font-mono">
{createdRepoUrl}
</code>
<motion.button
onClick={() => {
navigator.clipboard.writeText(createdRepoUrl);
toast.success('URL copied to clipboard');
}}
className="p-2 text-bolt-elements-textSecondary hover:text-bolt-elements-textPrimary dark:text-bolt-elements-textSecondary-dark dark:hover:text-bolt-elements-textPrimary-dark bg-bolt-elements-background-depth-1 dark:bg-bolt-elements-background-depth-4 rounded-lg border border-bolt-elements-borderColor dark:border-bolt-elements-borderColor-dark"
whileHover={{ scale: 1.05 }}
whileTap={{ scale: 0.95 }}
>
<div className="i-ph:copy w-4 h-4" />
</motion.button>
</div>
</div>
<div className="bg-bolt-elements-background-depth-2 dark:bg-bolt-elements-background-depth-3 rounded-lg p-4 border border-bolt-elements-borderColor dark:border-bolt-elements-borderColor-dark">
<p className="text-sm font-medium text-bolt-elements-textPrimary dark:text-bolt-elements-textPrimary-dark mb-2 flex items-center gap-2">
<span className="i-ph:files w-4 h-4 text-purple-500" />
Pushed Files ({pushedFiles.length})
</p>
<div className="max-h-[200px] overflow-y-auto custom-scrollbar pr-2">
{pushedFiles.map((file) => (
<div
key={file.path}
className="flex items-center justify-between py-1.5 text-sm text-bolt-elements-textPrimary dark:text-bolt-elements-textPrimary-dark border-b border-bolt-elements-borderColor/30 dark:border-bolt-elements-borderColor-dark/30 last:border-0"
>
<span className="font-mono truncate flex-1 text-xs">{file.path}</span>
<span className="text-xs px-2 py-0.5 rounded-full bg-bolt-elements-background-depth-3 dark:bg-bolt-elements-background-depth-4 text-bolt-elements-textSecondary dark:text-bolt-elements-textSecondary-dark ml-2">
{formatSize(file.size)}
</span>
</div>
))}
</div>
</div>
<div className="flex justify-end gap-2 pt-2">
<motion.a
href={createdRepoUrl}
target="_blank"
rel="noopener noreferrer"
className="px-4 py-2 rounded-lg bg-purple-500 text-white hover:bg-purple-600 text-sm inline-flex items-center gap-2"
whileHover={{ scale: 1.02 }}
whileTap={{ scale: 0.98 }}
>
<div className="i-ph:github-logo w-4 h-4" />
View Repository
</motion.a>
<motion.button
onClick={() => {
navigator.clipboard.writeText(createdRepoUrl);
toast.success('URL copied to clipboard');
}}
className="px-4 py-2 rounded-lg bg-bolt-elements-background-depth-2 dark:bg-bolt-elements-background-depth-3 text-bolt-elements-textSecondary dark:text-bolt-elements-textSecondary-dark hover:bg-bolt-elements-background-depth-3 dark:hover:bg-bolt-elements-background-depth-4 text-sm inline-flex items-center gap-2 border border-bolt-elements-borderColor dark:border-bolt-elements-borderColor-dark"
whileHover={{ scale: 1.02 }}
whileTap={{ scale: 0.98 }}
>
<div className="i-ph:copy w-4 h-4" />
Copy URL
</motion.button>
<motion.button
onClick={handleClose}
className="px-4 py-2 rounded-lg bg-bolt-elements-background-depth-2 dark:bg-bolt-elements-background-depth-3 text-bolt-elements-textSecondary dark:text-bolt-elements-textSecondary-dark hover:bg-bolt-elements-background-depth-3 dark:hover:bg-bolt-elements-background-depth-4 text-sm border border-bolt-elements-borderColor dark:border-bolt-elements-borderColor-dark"
whileHover={{ scale: 1.02 }}
whileTap={{ scale: 0.98 }}
>
Close
</motion.button>
</div>
</div>
</Dialog.Content>
</motion.div>
</div>
</Dialog.Portal>
</Dialog.Root>
);
}
if (!user) {
return (
<Dialog.Root open={isOpen} onOpenChange={(open) => !open && handleClose()}>
<Dialog.Portal>
<Dialog.Overlay className="fixed inset-0 bg-black/50 backdrop-blur-sm z-[9999]" />
<div className="fixed inset-0 flex items-center justify-center z-[9999]">
<motion.div
initial={{ opacity: 0, scale: 0.95 }}
animate={{ opacity: 1, scale: 1 }}
exit={{ opacity: 0, scale: 0.95 }}
transition={{ duration: 0.2 }}
className="w-[90vw] md:w-[500px]"
>
<Dialog.Content
className="bg-white dark:bg-bolt-elements-background-depth-1 rounded-lg p-6 border border-bolt-elements-borderColor dark:border-bolt-elements-borderColor-dark shadow-xl"
aria-describedby="connection-required-description"
>
<div className="relative text-center space-y-4">
<Dialog.Close asChild>
<button
onClick={handleClose}
className="absolute right-0 top-0 p-2 rounded-lg transition-all duration-200 ease-in-out bg-transparent text-bolt-elements-textTertiary hover:text-bolt-elements-textPrimary dark:text-bolt-elements-textTertiary-dark dark:hover:text-bolt-elements-textPrimary-dark hover:bg-bolt-elements-background-depth-2 dark:hover:bg-bolt-elements-background-depth-3 focus:outline-none focus:ring-2 focus:ring-bolt-elements-borderColor dark:focus:ring-bolt-elements-borderColor-dark"
>
<span className="i-ph:x block w-5 h-5" aria-hidden="true" />
<span className="sr-only">Close dialog</span>
</button>
</Dialog.Close>
<motion.div
initial={{ scale: 0.8 }}
animate={{ scale: 1 }}
transition={{ delay: 0.1 }}
className="mx-auto w-16 h-16 rounded-xl bg-bolt-elements-background-depth-3 flex items-center justify-center text-purple-500"
>
<div className="i-ph:github-logo w-8 h-8" />
</motion.div>
<h3 className="text-lg font-medium text-bolt-elements-textPrimary dark:text-bolt-elements-textPrimary-dark">
GitHub Connection Required
</h3>
<p
id="connection-required-description"
className="text-sm text-bolt-elements-textSecondary dark:text-bolt-elements-textSecondary-dark max-w-md mx-auto"
>
To push your code to GitHub, you need to connect your GitHub account in Settings {'>'} Connections
first.
</p>
<div className="pt-2 flex justify-center gap-3">
<motion.button
className="px-4 py-2 rounded-lg bg-bolt-elements-background-depth-2 dark:bg-bolt-elements-background-depth-3 text-bolt-elements-textSecondary dark:text-bolt-elements-textSecondary-dark text-sm hover:bg-bolt-elements-background-depth-3 dark:hover:bg-bolt-elements-background-depth-4 border border-bolt-elements-borderColor dark:border-bolt-elements-borderColor-dark"
whileHover={{ scale: 1.02 }}
whileTap={{ scale: 0.98 }}
onClick={handleClose}
>
Close
</motion.button>
<motion.a
href="/settings/connections"
className="px-4 py-2 rounded-lg bg-purple-500 text-white text-sm hover:bg-purple-600 inline-flex items-center gap-2"
whileHover={{ scale: 1.02 }}
whileTap={{ scale: 0.98 }}
>
<div className="i-ph:gear" />
Go to Settings
</motion.a>
</div>
</div>
</Dialog.Content>
</motion.div>
</div>
</Dialog.Portal>
</Dialog.Root>
);
}
return (
<Dialog.Root open={isOpen} onOpenChange={(open) => !open && handleClose()}>
<Dialog.Portal>
<Dialog.Overlay className="fixed inset-0 bg-black/50 backdrop-blur-sm z-[9999]" />
<div className="fixed inset-0 flex items-center justify-center z-[9999]">
<motion.div
initial={{ opacity: 0, scale: 0.95 }}
animate={{ opacity: 1, scale: 1 }}
exit={{ opacity: 0, scale: 0.95 }}
transition={{ duration: 0.2 }}
className="w-[90vw] md:w-[500px]"
>
<Dialog.Content
className="bg-white dark:bg-bolt-elements-background-depth-1 rounded-lg border border-bolt-elements-borderColor dark:border-bolt-elements-borderColor-dark shadow-xl"
aria-describedby="push-dialog-description"
>
<div className="p-6">
<div className="flex items-center gap-4 mb-6">
<motion.div
initial={{ scale: 0.8 }}
animate={{ scale: 1 }}
transition={{ delay: 0.1 }}
className="w-10 h-10 rounded-xl bg-bolt-elements-background-depth-3 flex items-center justify-center text-purple-500"
>
<div className="i-ph:github-logo w-5 h-5" />
</motion.div>
<div>
<Dialog.Title className="text-lg font-medium text-bolt-elements-textPrimary dark:text-bolt-elements-textPrimary-dark">
Push to GitHub
</Dialog.Title>
<p
id="push-dialog-description"
className="text-sm text-bolt-elements-textSecondary dark:text-bolt-elements-textSecondary-dark"
>
Push your code to a new or existing GitHub repository
</p>
</div>
<Dialog.Close asChild>
<button
onClick={handleClose}
className="ml-auto p-2 rounded-lg transition-all duration-200 ease-in-out bg-transparent text-bolt-elements-textTertiary hover:text-bolt-elements-textPrimary dark:text-bolt-elements-textTertiary-dark dark:hover:text-bolt-elements-textPrimary-dark hover:bg-bolt-elements-background-depth-2 dark:hover:bg-bolt-elements-background-depth-3 focus:outline-none focus:ring-2 focus:ring-bolt-elements-borderColor dark:focus:ring-bolt-elements-borderColor-dark"
>
<span className="i-ph:x block w-5 h-5" aria-hidden="true" />
<span className="sr-only">Close dialog</span>
</button>
</Dialog.Close>
</div>
<div className="flex items-center gap-3 mb-6 p-4 bg-bolt-elements-background-depth-2 dark:bg-bolt-elements-background-depth-3 rounded-lg border border-bolt-elements-borderColor dark:border-bolt-elements-borderColor-dark">
<div className="relative">
<img src={user.avatar_url} alt={user.login} className="w-10 h-10 rounded-full" />
<div className="absolute -bottom-1 -right-1 w-5 h-5 rounded-full bg-purple-500 flex items-center justify-center text-white">
<div className="i-ph:github-logo w-3 h-3" />
</div>
</div>
<div>
<p className="text-sm font-medium text-bolt-elements-textPrimary dark:text-bolt-elements-textPrimary-dark">
{user.name || user.login}
</p>
<p className="text-sm text-bolt-elements-textSecondary dark:text-bolt-elements-textSecondary-dark">
@{user.login}
</p>
</div>
</div>
<form onSubmit={handleSubmit} className="space-y-4">
<div className="space-y-2">
<label
htmlFor="repoName"
className="text-sm text-bolt-elements-textSecondary dark:text-bolt-elements-textSecondary-dark"
>
Repository Name
</label>
<div className="relative">
<div className="absolute left-3 top-1/2 -translate-y-1/2 text-bolt-elements-textTertiary dark:text-bolt-elements-textTertiary-dark">
<span className="i-ph:git-branch w-4 h-4" />
</div>
<input
id="repoName"
type="text"
value={repoName}
onChange={(e) => setRepoName(e.target.value)}
placeholder="my-awesome-project"
className="w-full pl-10 px-4 py-2 rounded-lg bg-bolt-elements-background-depth-2 dark:bg-bolt-elements-background-depth-3 border border-bolt-elements-borderColor dark:border-bolt-elements-borderColor-dark text-bolt-elements-textPrimary dark:text-bolt-elements-textPrimary-dark placeholder-bolt-elements-textTertiary dark:placeholder-bolt-elements-textTertiary-dark focus:outline-none focus:ring-2 focus:ring-purple-500"
required
/>
</div>
</div>
<div className="space-y-2">
<div className="flex items-center justify-between mb-2">
<label className="text-sm text-bolt-elements-textSecondary dark:text-bolt-elements-textSecondary-dark">
Recent Repositories
</label>
<span className="text-xs text-bolt-elements-textTertiary dark:text-bolt-elements-textTertiary-dark">
{filteredRepos.length} of {recentRepos.length}
</span>
</div>
<div className="mb-2">
<SearchInput
placeholder="Search repositories..."
value={repoSearchQuery}
onChange={(e) => setRepoSearchQuery(e.target.value)}
onClear={() => setRepoSearchQuery('')}
className="bg-bolt-elements-background-depth-2 dark:bg-bolt-elements-background-depth-3 border border-bolt-elements-borderColor dark:border-bolt-elements-borderColor-dark text-sm"
/>
</div>
{recentRepos.length === 0 && !isFetchingRepos ? (
<EmptyState
icon="i-ph:github-logo"
title="No repositories found"
description="We couldn't find any repositories in your GitHub account."
variant="compact"
/>
) : (
<div className="space-y-2 max-h-[200px] overflow-y-auto pr-2 custom-scrollbar">
{filteredRepos.length === 0 && repoSearchQuery.trim() !== '' ? (
<EmptyState
icon="i-ph:magnifying-glass"
title="No matching repositories"
description="Try a different search term"
variant="compact"
/>
) : (
filteredRepos.map((repo) => (
<motion.button
key={repo.full_name}
type="button"
onClick={() => setRepoName(repo.name)}
className="w-full p-3 text-left rounded-lg bg-bolt-elements-background-depth-2 dark:bg-bolt-elements-background-depth-3 hover:bg-bolt-elements-background-depth-3 dark:hover:bg-bolt-elements-background-depth-4 transition-colors group border border-bolt-elements-borderColor dark:border-bolt-elements-borderColor-dark hover:border-purple-500/30"
whileHover={{ scale: 1.01 }}
whileTap={{ scale: 0.99 }}
>
<div className="flex items-center justify-between">
<div className="flex items-center gap-2">
<div className="i-ph:git-branch w-4 h-4 text-purple-500" />
<span className="text-sm font-medium text-bolt-elements-textPrimary dark:text-bolt-elements-textPrimary-dark group-hover:text-purple-500">
{repo.name}
</span>
</div>
{repo.private && (
<Badge variant="primary" size="sm" icon="i-ph:lock w-3 h-3">
Private
</Badge>
)}
</div>
{repo.description && (
<p className="mt-1 text-xs text-bolt-elements-textSecondary dark:text-bolt-elements-textSecondary-dark line-clamp-2">
{repo.description}
</p>
)}
<div className="mt-2 flex items-center gap-2 flex-wrap">
{repo.language && (
<Badge variant="subtle" size="sm" icon="i-ph:code w-3 h-3">
{repo.language}
</Badge>
)}
<Badge variant="subtle" size="sm" icon="i-ph:star w-3 h-3">
{repo.stargazers_count.toLocaleString()}
</Badge>
<Badge variant="subtle" size="sm" icon="i-ph:git-fork w-3 h-3">
{repo.forks_count.toLocaleString()}
</Badge>
<Badge variant="subtle" size="sm" icon="i-ph:clock w-3 h-3">
{new Date(repo.updated_at).toLocaleDateString()}
</Badge>
</div>
</motion.button>
))
)}
</div>
)}
</div>
{isFetchingRepos && (
<div className="flex items-center justify-center py-4">
<StatusIndicator status="loading" pulse={true} label="Loading repositories..." />
</div>
)}
<div className="p-3 bg-bolt-elements-background-depth-2 dark:bg-bolt-elements-background-depth-3 rounded-lg border border-bolt-elements-borderColor dark:border-bolt-elements-borderColor-dark">
<div className="flex items-center gap-2">
<input
type="checkbox"
id="private"
checked={isPrivate}
onChange={(e) => setIsPrivate(e.target.checked)}
className="rounded border-bolt-elements-borderColor dark:border-bolt-elements-borderColor-dark text-purple-500 focus:ring-purple-500 dark:bg-bolt-elements-background-depth-3"
/>
<label
htmlFor="private"
className="text-sm text-bolt-elements-textPrimary dark:text-bolt-elements-textPrimary-dark"
>
Make repository private
</label>
</div>
<p className="text-xs text-bolt-elements-textTertiary dark:text-bolt-elements-textTertiary-dark mt-2 ml-6">
Private repositories are only visible to you and people you share them with
</p>
</div>
<div className="pt-4 flex gap-2">
<motion.button
type="button"
onClick={handleClose}
className="px-4 py-2 rounded-lg bg-bolt-elements-background-depth-2 dark:bg-bolt-elements-background-depth-3 text-bolt-elements-textSecondary dark:text-bolt-elements-textSecondary-dark hover:bg-bolt-elements-background-depth-3 dark:hover:bg-bolt-elements-background-depth-4 text-sm border border-bolt-elements-borderColor dark:border-bolt-elements-borderColor-dark"
whileHover={{ scale: 1.02 }}
whileTap={{ scale: 0.98 }}
>
Cancel
</motion.button>
<motion.button
type="submit"
disabled={isLoading}
className={classNames(
'flex-1 px-4 py-2 bg-purple-500 text-white rounded-lg hover:bg-purple-600 text-sm inline-flex items-center justify-center gap-2',
isLoading ? 'opacity-50 cursor-not-allowed' : '',
)}
whileHover={!isLoading ? { scale: 1.02 } : {}}
whileTap={!isLoading ? { scale: 0.98 } : {}}
>
{isLoading ? (
<>
<div className="i-ph:spinner-gap animate-spin w-4 h-4" />
Pushing...
</>
) : (
<>
<div className="i-ph:github-logo w-4 h-4" />
Push to GitHub
</>
)}
</motion.button>
</div>
</form>
</div>
</Dialog.Content>
</motion.div>
</div>
</Dialog.Portal>
</Dialog.Root>
);
}

View File

@@ -0,0 +1,146 @@
import React from 'react';
import { motion } from 'framer-motion';
import type { GitHubRepoInfo } from '~/types/GitHub';
interface RepositoryCardProps {
repo: GitHubRepoInfo;
onSelect: () => void;
}
import { useMemo } from 'react';
export function RepositoryCard({ repo, onSelect }: RepositoryCardProps) {
// Use a consistent styling for all repository cards
const getCardStyle = () => {
return 'from-bolt-elements-background-depth-1 to-bolt-elements-background-depth-1 dark:from-bolt-elements-background-depth-2-dark dark:to-bolt-elements-background-depth-2-dark';
};
// Format the date in a more readable format
const formatDate = (dateString: string) => {
const date = new Date(dateString);
const now = new Date();
const diffTime = Math.abs(now.getTime() - date.getTime());
const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
if (diffDays <= 1) {
return 'Today';
}
if (diffDays <= 2) {
return 'Yesterday';
}
if (diffDays <= 7) {
return `${diffDays} days ago`;
}
if (diffDays <= 30) {
return `${Math.floor(diffDays / 7)} weeks ago`;
}
return date.toLocaleDateString(undefined, {
year: 'numeric',
month: 'short',
day: 'numeric',
});
};
const cardStyle = useMemo(() => getCardStyle(), []);
// const formattedDate = useMemo(() => formatDate(repo.updated_at), [repo.updated_at]);
return (
<motion.div
className={`p-5 rounded-xl bg-gradient-to-br ${cardStyle} border border-bolt-elements-borderColor dark:border-bolt-elements-borderColor-dark hover:border-purple-500/40 transition-all duration-300 shadow-sm hover:shadow-md`}
whileHover={{
scale: 1.02,
y: -2,
transition: { type: 'spring', stiffness: 400, damping: 17 },
}}
whileTap={{ scale: 0.98 }}
initial={{ opacity: 0, y: 10 }}
animate={{ opacity: 1, y: 0 }}
transition={{ duration: 0.3 }}
>
<div className="flex items-start justify-between mb-3 gap-3">
<div className="flex items-start gap-3">
<div className="w-10 h-10 rounded-xl bg-bolt-elements-background-depth-1/80 dark:bg-bolt-elements-background-depth-4/80 backdrop-blur-sm flex items-center justify-center text-purple-500 shadow-sm">
<span className="i-ph:git-branch w-5 h-5" />
</div>
<div>
<h3 className="font-medium text-bolt-elements-textPrimary dark:text-bolt-elements-textPrimary-dark text-base">
{repo.name}
</h3>
<p className="text-xs text-bolt-elements-textTertiary dark:text-bolt-elements-textTertiary-dark flex items-center gap-1">
<span className="i-ph:user w-3 h-3" />
{repo.full_name.split('/')[0]}
</p>
</div>
</div>
<motion.button
onClick={onSelect}
className="px-4 py-2 h-9 rounded-lg bg-purple-500 text-white hover:bg-purple-600 transition-all duration-200 flex items-center gap-2 min-w-[100px] justify-center text-sm shadow-sm hover:shadow-md"
whileHover={{ scale: 1.05 }}
whileTap={{ scale: 0.95 }}
>
<span className="i-ph:git-pull-request w-3.5 h-3.5" />
Import
</motion.button>
</div>
{repo.description && (
<div className="mb-4 bg-bolt-elements-background-depth-1/50 dark:bg-bolt-elements-background-depth-4/50 backdrop-blur-sm p-3 rounded-lg border border-bolt-elements-borderColor/30 dark:border-bolt-elements-borderColor-dark/30">
<p className="text-sm text-bolt-elements-textSecondary dark:text-bolt-elements-textSecondary-dark line-clamp-2">
{repo.description}
</p>
</div>
)}
<div className="flex flex-wrap items-center gap-2">
{repo.private && (
<span className="flex items-center gap-1 px-2 py-1 rounded-lg bg-purple-500/10 text-purple-600 dark:text-purple-400 text-xs">
<span className="i-ph:lock w-3 h-3" />
Private
</span>
)}
{repo.language && (
<span className="flex items-center gap-1 px-2 py-1 rounded-lg bg-bolt-elements-background-depth-1/50 dark:bg-bolt-elements-background-depth-4/50 backdrop-blur-sm text-bolt-elements-textSecondary dark:text-bolt-elements-textSecondary-dark text-xs border border-bolt-elements-borderColor/30 dark:border-bolt-elements-borderColor-dark/30">
<span className="i-ph:code w-3 h-3" />
{repo.language}
</span>
)}
<span className="flex items-center gap-1 px-2 py-1 rounded-lg bg-bolt-elements-background-depth-1/50 dark:bg-bolt-elements-background-depth-4/50 backdrop-blur-sm text-bolt-elements-textSecondary dark:text-bolt-elements-textSecondary-dark text-xs border border-bolt-elements-borderColor/30 dark:border-bolt-elements-borderColor-dark/30">
<span className="i-ph:star w-3 h-3" />
{repo.stargazers_count.toLocaleString()}
</span>
{repo.forks_count > 0 && (
<span className="flex items-center gap-1 px-2 py-1 rounded-lg bg-bolt-elements-background-depth-1/50 dark:bg-bolt-elements-background-depth-4/50 backdrop-blur-sm text-bolt-elements-textSecondary dark:text-bolt-elements-textSecondary-dark text-xs border border-bolt-elements-borderColor/30 dark:border-bolt-elements-borderColor-dark/30">
<span className="i-ph:git-fork w-3 h-3" />
{repo.forks_count.toLocaleString()}
</span>
)}
</div>
<div className="mt-3 pt-3 border-t border-bolt-elements-borderColor/30 dark:border-bolt-elements-borderColor-dark/30 flex items-center justify-between">
<span className="flex items-center gap-1 text-xs text-bolt-elements-textTertiary dark:text-bolt-elements-textTertiary-dark">
<span className="i-ph:clock w-3 h-3" />
Updated {formatDate(repo.updated_at)}
</span>
{repo.topics && repo.topics.length > 0 && (
<span className="text-xs text-bolt-elements-textTertiary dark:text-bolt-elements-textTertiary-dark">
{repo.topics.slice(0, 1).map((topic) => (
<span
key={topic}
className="px-1.5 py-0.5 rounded-full bg-bolt-elements-background-depth-1/50 dark:bg-bolt-elements-background-depth-4/50 text-xs"
>
{topic}
</span>
))}
{repo.topics.length > 1 && <span className="ml-1">+{repo.topics.length - 1}</span>}
</span>
)}
</div>
</motion.div>
);
}

View File

@@ -0,0 +1,14 @@
import { createContext } from 'react';
// Create a context to share the setShowAuthDialog function with child components
export interface RepositoryDialogContextType {
setShowAuthDialog: React.Dispatch<React.SetStateAction<boolean>>;
}
// Default context value with a no-op function
export const RepositoryDialogContext = createContext<RepositoryDialogContextType>({
// This is intentionally empty as it will be overridden by the provider
setShowAuthDialog: () => {
// No operation
},
});

View File

@@ -0,0 +1,58 @@
import React, { useContext } from 'react';
import type { GitHubRepoInfo } from '~/types/GitHub';
import { EmptyState, StatusIndicator } from '~/components/ui';
import { RepositoryCard } from './RepositoryCard';
import { RepositoryDialogContext } from './RepositoryDialogContext';
interface RepositoryListProps {
repos: GitHubRepoInfo[];
isLoading: boolean;
onSelect: (repo: GitHubRepoInfo) => void;
activeTab: string;
}
export function RepositoryList({ repos, isLoading, onSelect, activeTab }: RepositoryListProps) {
// Access the parent component's setShowAuthDialog function
const { setShowAuthDialog } = useContext(RepositoryDialogContext);
if (isLoading) {
return (
<div className="flex flex-col items-center justify-center py-8 text-bolt-elements-textSecondary dark:text-bolt-elements-textSecondary-dark">
<StatusIndicator status="loading" pulse={true} size="lg" label="Loading repositories..." className="mb-2" />
<p className="text-xs text-bolt-elements-textTertiary dark:text-bolt-elements-textTertiary-dark">
This may take a moment
</p>
</div>
);
}
if (repos.length === 0) {
if (activeTab === 'my-repos') {
return (
<EmptyState
icon="i-ph:folder-simple-dashed"
title="No repositories found"
description="Connect your GitHub account or create a new repository to get started"
actionLabel="Connect GitHub Account"
onAction={() => setShowAuthDialog(true)}
/>
);
} else {
return (
<EmptyState
icon="i-ph:magnifying-glass"
title="No repositories found"
description="Try searching with different keywords or filters"
/>
);
}
}
return (
<div className="space-y-3">
{repos.map((repo) => (
<RepositoryCard key={repo.full_name} repo={repo} onSelect={() => onSelect(repo)} />
))}
</div>
);
}

View File

@@ -0,0 +1,993 @@
import type { GitHubRepoInfo, GitHubContent, RepositoryStats, GitHubUserResponse } from '~/types/GitHub';
import { useState, useEffect } from 'react';
import { toast } from 'react-toastify';
import * as Dialog from '@radix-ui/react-dialog';
import { classNames } from '~/utils/classNames';
import { getLocalStorage } from '~/lib/persistence';
import { motion, AnimatePresence } from 'framer-motion';
import Cookies from 'js-cookie';
// Import UI components
import { Input, SearchInput, Badge, FilterChip } from '~/components/ui';
// Import the components we've extracted
import { RepositoryList } from './RepositoryList';
import { StatsDialog } from './StatsDialog';
import { GitHubAuthDialog } from './GitHubAuthDialog';
import { RepositoryDialogContext } from './RepositoryDialogContext';
interface GitHubTreeResponse {
tree: Array<{
path: string;
type: string;
size?: number;
}>;
}
interface RepositorySelectionDialogProps {
isOpen: boolean;
onClose: () => void;
onSelect: (url: string) => void;
}
interface SearchFilters {
language?: string;
stars?: number;
forks?: number;
}
export function RepositorySelectionDialog({ isOpen, onClose, onSelect }: RepositorySelectionDialogProps) {
const [selectedRepository, setSelectedRepository] = useState<GitHubRepoInfo | null>(null);
const [isLoading, setIsLoading] = useState(false);
const [repositories, setRepositories] = useState<GitHubRepoInfo[]>([]);
const [searchQuery, setSearchQuery] = useState('');
const [searchResults, setSearchResults] = useState<GitHubRepoInfo[]>([]);
const [activeTab, setActiveTab] = useState<'my-repos' | 'search' | 'url'>('my-repos');
const [customUrl, setCustomUrl] = useState('');
const [branches, setBranches] = useState<{ name: string; default?: boolean }[]>([]);
const [selectedBranch, setSelectedBranch] = useState('');
const [filters, setFilters] = useState<SearchFilters>({});
const [showStatsDialog, setShowStatsDialog] = useState(false);
const [currentStats, setCurrentStats] = useState<RepositoryStats | null>(null);
const [pendingGitUrl, setPendingGitUrl] = useState<string>('');
const [showAuthDialog, setShowAuthDialog] = useState(false);
// Handle GitHub auth dialog close and refresh repositories
const handleAuthDialogClose = () => {
setShowAuthDialog(false);
// If we're on the my-repos tab, refresh the repository list
if (activeTab === 'my-repos') {
fetchUserRepos();
}
};
// Initialize GitHub connection and fetch repositories
useEffect(() => {
const savedConnection = getLocalStorage('github_connection');
// If no connection exists but environment variables are set, create a connection
if (!savedConnection && import.meta.env.VITE_GITHUB_ACCESS_TOKEN) {
const token = import.meta.env.VITE_GITHUB_ACCESS_TOKEN;
const tokenType = import.meta.env.VITE_GITHUB_TOKEN_TYPE === 'fine-grained' ? 'fine-grained' : 'classic';
// Fetch GitHub user info to initialize the connection
fetch('https://api.github.com/user', {
headers: {
Accept: 'application/vnd.github.v3+json',
Authorization: `Bearer ${token}`,
},
})
.then((response) => {
if (!response.ok) {
throw new Error('Invalid token or unauthorized');
}
return response.json();
})
.then((data: unknown) => {
const userData = data as GitHubUserResponse;
// Save connection to local storage
const newConnection = {
token,
tokenType,
user: {
login: userData.login,
avatar_url: userData.avatar_url,
name: userData.name || userData.login,
},
connected_at: new Date().toISOString(),
};
localStorage.setItem('github_connection', JSON.stringify(newConnection));
// Also save as cookies for API requests
Cookies.set('githubToken', token);
Cookies.set('githubUsername', userData.login);
Cookies.set('git:github.com', JSON.stringify({ username: token, password: 'x-oauth-basic' }));
// Refresh repositories after connection is established
if (isOpen && activeTab === 'my-repos') {
fetchUserRepos();
}
})
.catch((error) => {
console.error('Failed to initialize GitHub connection from environment variables:', error);
});
}
}, [isOpen]);
// Fetch repositories when dialog opens or tab changes
useEffect(() => {
if (isOpen && activeTab === 'my-repos') {
fetchUserRepos();
}
}, [isOpen, activeTab]);
const fetchUserRepos = async () => {
const connection = getLocalStorage('github_connection');
if (!connection?.token) {
toast.error('Please connect your GitHub account first');
return;
}
setIsLoading(true);
try {
const response = await fetch('https://api.github.com/user/repos?sort=updated&per_page=100&type=all', {
headers: {
Accept: 'application/vnd.github.v3+json',
Authorization: `Bearer ${connection.token}`,
},
});
if (!response.ok) {
throw new Error('Failed to fetch repositories');
}
const data = await response.json();
// Add type assertion and validation
if (
Array.isArray(data) &&
data.every((item) => typeof item === 'object' && item !== null && 'full_name' in item)
) {
setRepositories(data as GitHubRepoInfo[]);
} else {
throw new Error('Invalid repository data format');
}
} catch (error) {
console.error('Error fetching repos:', error);
toast.error('Failed to fetch your repositories');
} finally {
setIsLoading(false);
}
};
const handleSearch = async (query: string) => {
setIsLoading(true);
setSearchResults([]);
try {
let searchQuery = query;
if (filters.language) {
searchQuery += ` language:${filters.language}`;
}
if (filters.stars) {
searchQuery += ` stars:>${filters.stars}`;
}
if (filters.forks) {
searchQuery += ` forks:>${filters.forks}`;
}
const response = await fetch(
`https://api.github.com/search/repositories?q=${encodeURIComponent(searchQuery)}&sort=stars&order=desc`,
{
headers: {
Accept: 'application/vnd.github.v3+json',
},
},
);
if (!response.ok) {
throw new Error('Failed to search repositories');
}
const data = await response.json();
// Add type assertion and validation
if (typeof data === 'object' && data !== null && 'items' in data && Array.isArray(data.items)) {
setSearchResults(data.items as GitHubRepoInfo[]);
} else {
throw new Error('Invalid search results format');
}
} catch (error) {
console.error('Error searching repos:', error);
toast.error('Failed to search repositories');
} finally {
setIsLoading(false);
}
};
const fetchBranches = async (repo: GitHubRepoInfo) => {
setIsLoading(true);
try {
const connection = getLocalStorage('github_connection');
const headers: HeadersInit = connection?.token
? {
Accept: 'application/vnd.github.v3+json',
Authorization: `Bearer ${connection.token}`,
}
: {};
const response = await fetch(`https://api.github.com/repos/${repo.full_name}/branches`, {
headers,
});
if (!response.ok) {
throw new Error('Failed to fetch branches');
}
const data = await response.json();
// Add type assertion and validation
if (Array.isArray(data) && data.every((item) => typeof item === 'object' && item !== null && 'name' in item)) {
setBranches(
data.map((branch) => ({
name: branch.name,
default: branch.name === repo.default_branch,
})),
);
} else {
throw new Error('Invalid branch data format');
}
} catch (error) {
console.error('Error fetching branches:', error);
toast.error('Failed to fetch branches');
} finally {
setIsLoading(false);
}
};
const handleRepoSelect = async (repo: GitHubRepoInfo) => {
setSelectedRepository(repo);
await fetchBranches(repo);
};
const formatGitUrl = (url: string): string => {
// Remove any tree references and ensure .git extension
const baseUrl = url
.replace(/\/tree\/[^/]+/, '') // Remove /tree/branch-name
.replace(/\/$/, '') // Remove trailing slash
.replace(/\.git$/, ''); // Remove .git if present
return `${baseUrl}.git`;
};
const verifyRepository = async (repoUrl: string): Promise<RepositoryStats | null> => {
try {
// Extract branch from URL if present (format: url#branch)
let branch: string | null = null;
let cleanUrl = repoUrl;
if (repoUrl.includes('#')) {
const parts = repoUrl.split('#');
cleanUrl = parts[0];
branch = parts[1];
}
const [owner, repo] = cleanUrl
.replace(/\.git$/, '')
.split('/')
.slice(-2);
// Try to get token from local storage first
const connection = getLocalStorage('github_connection');
// If no connection in local storage, check environment variables
let headers: HeadersInit = {};
if (connection?.token) {
headers = {
Accept: 'application/vnd.github.v3+json',
Authorization: `Bearer ${connection.token}`,
};
} else if (import.meta.env.VITE_GITHUB_ACCESS_TOKEN) {
// Use token from environment variables
headers = {
Accept: 'application/vnd.github.v3+json',
Authorization: `Bearer ${import.meta.env.VITE_GITHUB_ACCESS_TOKEN}`,
};
}
// First, get the repository info to determine the default branch
const repoInfoResponse = await fetch(`https://api.github.com/repos/${owner}/${repo}`, {
headers,
});
if (!repoInfoResponse.ok) {
if (repoInfoResponse.status === 401 || repoInfoResponse.status === 403) {
throw new Error(
`Authentication failed (${repoInfoResponse.status}). Your GitHub token may be invalid or missing the required permissions.`,
);
} else if (repoInfoResponse.status === 404) {
throw new Error(
`Repository not found or is private (${repoInfoResponse.status}). To access private repositories, you need to connect your GitHub account or provide a valid token with appropriate permissions.`,
);
} else {
throw new Error(
`Failed to fetch repository information: ${repoInfoResponse.statusText} (${repoInfoResponse.status})`,
);
}
}
const repoInfo = (await repoInfoResponse.json()) as { default_branch: string };
let defaultBranch = repoInfo.default_branch || 'main';
// If a branch was specified in the URL, use that instead of the default
if (branch) {
defaultBranch = branch;
}
// Try to fetch the repository tree using the selected branch
let treeResponse = await fetch(
`https://api.github.com/repos/${owner}/${repo}/git/trees/${defaultBranch}?recursive=1`,
{
headers,
},
);
// If the selected branch doesn't work, try common branch names
if (!treeResponse.ok) {
// Try 'master' branch if default branch failed
treeResponse = await fetch(`https://api.github.com/repos/${owner}/${repo}/git/trees/master?recursive=1`, {
headers,
});
// If master also fails, try 'main' branch
if (!treeResponse.ok) {
treeResponse = await fetch(`https://api.github.com/repos/${owner}/${repo}/git/trees/main?recursive=1`, {
headers,
});
}
// If all common branches fail, throw an error
if (!treeResponse.ok) {
throw new Error(
'Failed to fetch repository structure. Please check the repository URL and your access permissions.',
);
}
}
const treeData = (await treeResponse.json()) as GitHubTreeResponse;
// Calculate repository stats
let totalSize = 0;
let totalFiles = 0;
const languages: { [key: string]: number } = {};
let hasPackageJson = false;
let hasDependencies = false;
for (const file of treeData.tree) {
if (file.type === 'blob') {
totalFiles++;
if (file.size) {
totalSize += file.size;
}
// Check for package.json
if (file.path === 'package.json') {
hasPackageJson = true;
// Fetch package.json content to check dependencies
const contentResponse = await fetch(`https://api.github.com/repos/${owner}/${repo}/contents/package.json`, {
headers,
});
if (contentResponse.ok) {
const content = (await contentResponse.json()) as GitHubContent;
const packageJson = JSON.parse(Buffer.from(content.content, 'base64').toString());
hasDependencies = !!(
packageJson.dependencies ||
packageJson.devDependencies ||
packageJson.peerDependencies
);
}
}
// Detect language based on file extension
const ext = file.path.split('.').pop()?.toLowerCase();
if (ext) {
languages[ext] = (languages[ext] || 0) + (file.size || 0);
}
}
}
const stats: RepositoryStats = {
totalFiles,
totalSize,
languages,
hasPackageJson,
hasDependencies,
};
return stats;
} catch (error) {
console.error('Error verifying repository:', error);
// Check if it's an authentication error and show the auth dialog
const errorMessage = error instanceof Error ? error.message : 'Failed to verify repository';
if (
errorMessage.includes('Authentication failed') ||
errorMessage.includes('may be private') ||
errorMessage.includes('Repository not found or is private') ||
errorMessage.includes('Unauthorized') ||
errorMessage.includes('401') ||
errorMessage.includes('403') ||
errorMessage.includes('404') ||
errorMessage.includes('access permissions')
) {
setShowAuthDialog(true);
}
toast.error(errorMessage);
return null;
}
};
const handleImport = async () => {
try {
let gitUrl: string;
if (activeTab === 'url' && customUrl) {
gitUrl = formatGitUrl(customUrl);
} else if (selectedRepository) {
gitUrl = formatGitUrl(selectedRepository.html_url);
if (selectedBranch) {
gitUrl = `${gitUrl}#${selectedBranch}`;
}
} else {
return;
}
// Verify repository before importing
const stats = await verifyRepository(gitUrl);
if (!stats) {
return;
}
setCurrentStats(stats);
setPendingGitUrl(gitUrl);
setShowStatsDialog(true);
} catch (error) {
console.error('Error preparing repository:', error);
// Check if it's an authentication error
const errorMessage = error instanceof Error ? error.message : 'Failed to prepare repository. Please try again.';
// Show the GitHub auth dialog for any authentication or permission errors
if (
errorMessage.includes('Authentication failed') ||
errorMessage.includes('may be private') ||
errorMessage.includes('Repository not found or is private') ||
errorMessage.includes('Unauthorized') ||
errorMessage.includes('401') ||
errorMessage.includes('403') ||
errorMessage.includes('404') ||
errorMessage.includes('access permissions')
) {
// Directly show the auth dialog instead of just showing a toast
setShowAuthDialog(true);
toast.error(
<div className="space-y-2">
<p>{errorMessage}</p>
<button onClick={() => setShowAuthDialog(true)} className="underline font-medium block text-purple-500">
Learn how to access private repositories
</button>
</div>,
{ autoClose: 10000 }, // Keep the toast visible longer
);
} else {
toast.error(errorMessage);
}
}
};
const handleStatsConfirm = () => {
setShowStatsDialog(false);
if (pendingGitUrl) {
onSelect(pendingGitUrl);
onClose();
}
};
const handleFilterChange = (key: keyof SearchFilters, value: string) => {
let parsedValue: string | number | undefined = value;
if (key === 'stars' || key === 'forks') {
parsedValue = value ? parseInt(value, 10) : undefined;
}
setFilters((prev) => ({ ...prev, [key]: parsedValue }));
handleSearch(searchQuery);
};
// Handle dialog close properly
const handleClose = () => {
setIsLoading(false); // Reset loading state
setSearchQuery(''); // Reset search
setSearchResults([]); // Reset results
onClose();
};
return (
<RepositoryDialogContext.Provider value={{ setShowAuthDialog }}>
<Dialog.Root
open={isOpen}
onOpenChange={(open) => {
if (!open) {
handleClose();
}
}}
>
<Dialog.Portal>
<Dialog.Overlay className="fixed inset-0 bg-black/50 backdrop-blur-sm z-50" />
<Dialog.Content className="fixed top-[50%] left-[50%] -translate-x-1/2 -translate-y-1/2 w-[90vw] md:w-[650px] max-h-[85vh] overflow-hidden bg-white dark:bg-bolt-elements-background-depth-1 rounded-xl shadow-xl z-[51] border border-bolt-elements-borderColor dark:border-bolt-elements-borderColor-dark">
{/* Header */}
<div className="p-5 border-b border-bolt-elements-borderColor dark:border-bolt-elements-borderColor-dark flex items-center justify-between">
<div className="flex items-center gap-3">
<div className="w-10 h-10 rounded-xl bg-gradient-to-br from-purple-500/20 to-blue-500/10 flex items-center justify-center text-purple-500 shadow-sm">
<span className="i-ph:github-logo w-5 h-5" />
</div>
<div>
<Dialog.Title className="text-lg font-semibold text-bolt-elements-textPrimary dark:text-bolt-elements-textPrimary-dark">
Import GitHub Repository
</Dialog.Title>
<p className="text-sm text-bolt-elements-textSecondary dark:text-bolt-elements-textSecondary-dark">
Clone a repository from GitHub to your workspace
</p>
</div>
</div>
<Dialog.Close
onClick={handleClose}
className={classNames(
'p-2 rounded-lg transition-all duration-200 ease-in-out bg-transparent',
'text-bolt-elements-textTertiary hover:text-bolt-elements-textPrimary',
'dark:text-bolt-elements-textTertiary-dark dark:hover:text-bolt-elements-textPrimary-dark',
'hover:bg-bolt-elements-background-depth-2 dark:hover:bg-bolt-elements-background-depth-3',
'focus:outline-none focus:ring-2 focus:ring-bolt-elements-borderColor dark:focus:ring-bolt-elements-borderColor-dark',
)}
>
<span className="i-ph:x block w-5 h-5" aria-hidden="true" />
<span className="sr-only">Close dialog</span>
</Dialog.Close>
</div>
{/* Auth Info Banner */}
<div className="p-4 border-b border-bolt-elements-borderColor dark:border-bolt-elements-borderColor-dark flex items-center justify-between bg-gradient-to-r from-bolt-elements-background-depth-2 to-bolt-elements-background-depth-1 dark:from-bolt-elements-background-depth-3 dark:to-bolt-elements-background-depth-2">
<div className="flex items-center gap-2">
<span className="i-ph:info text-blue-500" />
<span className="text-sm text-bolt-elements-textSecondary dark:text-bolt-elements-textSecondary-dark">
Need to access private repositories?
</span>
</div>
<motion.button
onClick={() => setShowAuthDialog(true)}
className="px-3 py-1.5 rounded-lg bg-purple-500 hover:bg-purple-600 text-white text-sm transition-colors flex items-center gap-1.5 shadow-sm"
whileHover={{ scale: 1.02, boxShadow: '0 4px 8px rgba(124, 58, 237, 0.2)' }}
whileTap={{ scale: 0.98 }}
>
<span className="i-ph:github-logo w-4 h-4" />
Connect GitHub Account
</motion.button>
</div>
{/* Content */}
<div className="p-5">
{/* Tabs */}
<div className="mb-6">
<div className="bg-[#f0f0f0] dark:bg-[#1e1e1e] rounded-lg overflow-hidden border border-bolt-elements-borderColor dark:border-bolt-elements-borderColor-dark">
<div className="flex">
<button
onClick={() => setActiveTab('my-repos')}
className={classNames(
'flex-1 py-3 px-4 text-center text-sm font-medium transition-colors',
activeTab === 'my-repos'
? 'bg-[#e6e6e6] dark:bg-[#2a2a2a] text-bolt-elements-textPrimary dark:text-bolt-elements-textPrimary-dark'
: 'bg-[#f0f0f0] dark:bg-[#1e1e1e] text-bolt-elements-textSecondary dark:text-bolt-elements-textSecondary-dark hover:bg-[#e6e6e6] dark:hover:bg-[#2a2a2a]/50',
)}
>
My Repos
</button>
<button
onClick={() => setActiveTab('search')}
className={classNames(
'flex-1 py-3 px-4 text-center text-sm font-medium transition-colors',
activeTab === 'search'
? 'bg-[#e6e6e6] dark:bg-[#2a2a2a] text-bolt-elements-textPrimary dark:text-bolt-elements-textPrimary-dark'
: 'bg-[#f0f0f0] dark:bg-[#1e1e1e] text-bolt-elements-textSecondary dark:text-bolt-elements-textSecondary-dark hover:bg-[#e6e6e6] dark:hover:bg-[#2a2a2a]/50',
)}
>
Search
</button>
<button
onClick={() => setActiveTab('url')}
className={classNames(
'flex-1 py-3 px-4 text-center text-sm font-medium transition-colors',
activeTab === 'url'
? 'bg-[#e6e6e6] dark:bg-[#2a2a2a] text-bolt-elements-textPrimary dark:text-bolt-elements-textPrimary-dark'
: 'bg-[#f0f0f0] dark:bg-[#1e1e1e] text-bolt-elements-textSecondary dark:text-bolt-elements-textSecondary-dark hover:bg-[#e6e6e6] dark:hover:bg-[#2a2a2a]/50',
)}
>
From URL
</button>
</div>
</div>
</div>
{activeTab === 'url' ? (
<div className="space-y-5">
<div className="bg-gradient-to-br from-bolt-elements-background-depth-1 to-bolt-elements-background-depth-1 dark:from-bolt-elements-background-depth-2-dark dark:to-bolt-elements-background-depth-2-dark p-5 rounded-xl border border-bolt-elements-borderColor dark:border-bolt-elements-borderColor-dark">
<h3 className="text-base font-medium text-bolt-elements-textPrimary dark:text-bolt-elements-textPrimary-dark mb-3 flex items-center gap-2">
<span className="i-ph:link-simple w-4 h-4 text-purple-500" />
Repository URL
</h3>
<div className="relative">
<div className="absolute left-3 top-1/2 -translate-y-1/2 text-purple-500">
<span className="i-ph:github-logo w-5 h-5" />
</div>
<Input
type="text"
placeholder="Enter GitHub repository URL (e.g., https://github.com/user/repo)"
value={customUrl}
onChange={(e) => setCustomUrl(e.target.value)}
className="w-full pl-10 py-3 border-bolt-elements-borderColor dark:border-bolt-elements-borderColor-dark focus:ring-2 focus:ring-purple-500 focus:border-transparent"
/>
</div>
<div className="mt-3 text-xs text-bolt-elements-textSecondary dark:text-bolt-elements-textSecondary-dark bg-white/50 dark:bg-bolt-elements-background-depth-4/50 p-3 rounded-lg border border-bolt-elements-borderColor/30 dark:border-bolt-elements-borderColor-dark/30 backdrop-blur-sm">
<p className="flex items-start gap-2">
<span className="i-ph:info w-3.5 h-3.5 flex-shrink-0 mt-0.5 text-blue-500" />
<span>
You can paste any GitHub repository URL, including specific branches or tags.
<br />
<span className="text-bolt-elements-textTertiary dark:text-bolt-elements-textTertiary-dark">
Example: https://github.com/username/repository/tree/branch-name
</span>
</span>
</p>
</div>
</div>
<div className="flex items-center gap-3 text-sm text-bolt-elements-textSecondary dark:text-bolt-elements-textSecondary-dark">
<div className="h-px flex-grow bg-bolt-elements-borderColor dark:bg-bolt-elements-borderColor-dark"></div>
<span>Ready to import?</span>
<div className="h-px flex-grow bg-bolt-elements-borderColor dark:bg-bolt-elements-borderColor-dark"></div>
</div>
<motion.button
onClick={handleImport}
disabled={!customUrl}
className={classNames(
'w-full h-12 px-4 py-2 rounded-xl text-white transition-all duration-200 flex items-center gap-2 justify-center',
customUrl
? 'bg-gradient-to-r from-purple-500 to-purple-600 hover:from-purple-600 hover:to-purple-700 shadow-md'
: 'bg-gray-300 dark:bg-gray-700 cursor-not-allowed',
)}
whileHover={customUrl ? { scale: 1.02, boxShadow: '0 4px 12px rgba(124, 58, 237, 0.3)' } : {}}
whileTap={customUrl ? { scale: 0.98 } : {}}
>
<span className="i-ph:git-pull-request w-5 h-5" />
Import Repository
</motion.button>
</div>
) : (
<>
{activeTab === 'search' && (
<div className="space-y-5 mb-5">
<div className="bg-gradient-to-br from-blue-500/5 to-cyan-500/5 p-5 rounded-xl border border-bolt-elements-borderColor dark:border-bolt-elements-borderColor-dark">
<h3 className="text-base font-medium text-bolt-elements-textPrimary dark:text-bolt-elements-textPrimary-dark mb-3 flex items-center gap-2">
<span className="i-ph:magnifying-glass w-4 h-4 text-blue-500" />
Search GitHub
</h3>
<div className="flex gap-2">
<div className="flex-1">
<SearchInput
placeholder="Search GitHub repositories..."
value={searchQuery}
onChange={(e) => {
setSearchQuery(e.target.value);
if (e.target.value.length > 2) {
handleSearch(e.target.value);
}
}}
onKeyDown={(e) => {
if (e.key === 'Enter' && searchQuery.length > 2) {
handleSearch(searchQuery);
}
}}
onClear={() => {
setSearchQuery('');
setSearchResults([]);
}}
iconClassName="text-blue-500"
className="py-3 bg-white dark:bg-bolt-elements-background-depth-4 border border-bolt-elements-borderColor dark:border-bolt-elements-borderColor-dark text-bolt-elements-textPrimary dark:text-bolt-elements-textPrimary-dark focus:outline-none focus:ring-2 focus:ring-blue-500 shadow-sm"
loading={isLoading}
/>
</div>
<motion.button
onClick={() => setFilters({})}
className="px-3 py-2 rounded-lg bg-white dark:bg-bolt-elements-background-depth-4 text-bolt-elements-textSecondary hover:text-bolt-elements-textPrimary border border-bolt-elements-borderColor dark:border-bolt-elements-borderColor-dark shadow-sm"
whileHover={{ scale: 1.05 }}
whileTap={{ scale: 0.95 }}
title="Clear filters"
>
<span className="i-ph:funnel-simple w-4 h-4" />
</motion.button>
</div>
<div className="mt-3">
<div className="text-xs text-bolt-elements-textSecondary dark:text-bolt-elements-textSecondary-dark mb-2">
Filters
</div>
{/* Active filters */}
{(filters.language || filters.stars || filters.forks) && (
<div className="flex flex-wrap gap-2 mb-3">
<AnimatePresence>
{filters.language && (
<FilterChip
label="Language"
value={filters.language}
icon="i-ph:code"
active
onRemove={() => {
const newFilters = { ...filters };
delete newFilters.language;
setFilters(newFilters);
if (searchQuery.length > 2) {
handleSearch(searchQuery);
}
}}
/>
)}
{filters.stars && (
<FilterChip
label="Stars"
value={`>${filters.stars}`}
icon="i-ph:star"
active
onRemove={() => {
const newFilters = { ...filters };
delete newFilters.stars;
setFilters(newFilters);
if (searchQuery.length > 2) {
handleSearch(searchQuery);
}
}}
/>
)}
{filters.forks && (
<FilterChip
label="Forks"
value={`>${filters.forks}`}
icon="i-ph:git-fork"
active
onRemove={() => {
const newFilters = { ...filters };
delete newFilters.forks;
setFilters(newFilters);
if (searchQuery.length > 2) {
handleSearch(searchQuery);
}
}}
/>
)}
</AnimatePresence>
</div>
)}
<div className="grid grid-cols-3 gap-2">
<div className="relative col-span-3 md:col-span-1">
<div className="absolute left-2 top-1/2 -translate-y-1/2 text-bolt-elements-textTertiary dark:text-bolt-elements-textTertiary-dark">
<span className="i-ph:code w-3.5 h-3.5" />
</div>
<input
type="text"
placeholder="Language (e.g., javascript)"
value={filters.language || ''}
onChange={(e) => {
setFilters({ ...filters, language: e.target.value });
if (searchQuery.length > 2) {
handleSearch(searchQuery);
}
}}
className="w-full pl-8 px-3 py-2 text-sm rounded-lg bg-white dark:bg-bolt-elements-background-depth-4 border border-bolt-elements-borderColor dark:border-bolt-elements-borderColor-dark focus:outline-none focus:ring-2 focus:ring-blue-500"
/>
</div>
<div className="relative">
<div className="absolute left-2 top-1/2 -translate-y-1/2 text-bolt-elements-textTertiary dark:text-bolt-elements-textTertiary-dark">
<span className="i-ph:star w-3.5 h-3.5" />
</div>
<input
type="number"
placeholder="Min stars"
value={filters.stars || ''}
onChange={(e) => handleFilterChange('stars', e.target.value)}
className="w-full pl-8 px-3 py-2 text-sm rounded-lg bg-white dark:bg-bolt-elements-background-depth-4 border border-bolt-elements-borderColor dark:border-bolt-elements-borderColor-dark focus:outline-none focus:ring-2 focus:ring-blue-500"
/>
</div>
<div className="relative">
<div className="absolute left-2 top-1/2 -translate-y-1/2 text-bolt-elements-textTertiary dark:text-bolt-elements-textTertiary-dark">
<span className="i-ph:git-fork w-3.5 h-3.5" />
</div>
<input
type="number"
placeholder="Min forks"
value={filters.forks || ''}
onChange={(e) => handleFilterChange('forks', e.target.value)}
className="w-full pl-8 px-3 py-2 text-sm rounded-lg bg-white dark:bg-bolt-elements-background-depth-4 border border-bolt-elements-borderColor dark:border-bolt-elements-borderColor-dark focus:outline-none focus:ring-2 focus:ring-blue-500"
/>
</div>
</div>
</div>
<div className="mt-3 text-xs text-bolt-elements-textSecondary dark:text-bolt-elements-textSecondary-dark bg-white/50 dark:bg-bolt-elements-background-depth-4/50 p-3 rounded-lg border border-bolt-elements-borderColor/30 dark:border-bolt-elements-borderColor-dark/30 backdrop-blur-sm">
<p className="flex items-start gap-2">
<span className="i-ph:info w-3.5 h-3.5 flex-shrink-0 mt-0.5 text-blue-500" />
<span>
Search for repositories by name, description, or topics. Use filters to narrow down
results.
</span>
</p>
</div>
</div>
</div>
)}
<div className="space-y-3 max-h-[400px] overflow-y-auto pr-2 custom-scrollbar">
{selectedRepository ? (
<div className="space-y-5 bg-gradient-to-br from-purple-500/5 to-blue-500/5 p-5 rounded-xl border border-bolt-elements-borderColor dark:border-bolt-elements-borderColor-dark">
<div className="flex items-center justify-between">
<div className="flex items-center gap-3">
<motion.button
onClick={() => setSelectedRepository(null)}
className="p-2 rounded-lg hover:bg-white dark:hover:bg-bolt-elements-background-depth-4 text-bolt-elements-textSecondary hover:text-bolt-elements-textPrimary shadow-sm"
whileHover={{ scale: 1.1 }}
whileTap={{ scale: 0.9 }}
>
<span className="i-ph:arrow-left w-4 h-4" />
</motion.button>
<div>
<h3 className="font-medium text-bolt-elements-textPrimary dark:text-bolt-elements-textPrimary-dark text-lg">
{selectedRepository.name}
</h3>
<p className="text-xs text-bolt-elements-textTertiary dark:text-bolt-elements-textTertiary-dark flex items-center gap-1">
<span className="i-ph:user w-3 h-3" />
{selectedRepository.full_name.split('/')[0]}
</p>
</div>
</div>
{selectedRepository.private && (
<Badge variant="primary" size="md" icon="i-ph:lock w-3 h-3">
Private
</Badge>
)}
</div>
{selectedRepository.description && (
<div className="bg-white/50 dark:bg-bolt-elements-background-depth-4/50 p-3 rounded-lg border border-bolt-elements-borderColor/30 dark:border-bolt-elements-borderColor-dark/30 backdrop-blur-sm">
<p className="text-sm text-bolt-elements-textSecondary dark:text-bolt-elements-textSecondary-dark">
{selectedRepository.description}
</p>
</div>
)}
<div className="flex flex-wrap items-center gap-2">
{selectedRepository.language && (
<Badge variant="subtle" size="md" icon="i-ph:code w-3 h-3">
{selectedRepository.language}
</Badge>
)}
<Badge variant="subtle" size="md" icon="i-ph:star w-3 h-3">
{selectedRepository.stargazers_count.toLocaleString()}
</Badge>
{selectedRepository.forks_count > 0 && (
<Badge variant="subtle" size="md" icon="i-ph:git-fork w-3 h-3">
{selectedRepository.forks_count.toLocaleString()}
</Badge>
)}
</div>
<div className="pt-3 border-t border-bolt-elements-borderColor/30 dark:border-bolt-elements-borderColor-dark/30">
<div className="flex items-center gap-2 mb-2">
<span className="i-ph:git-branch w-4 h-4 text-purple-500" />
<label className="text-sm font-medium text-bolt-elements-textPrimary dark:text-bolt-elements-textPrimary-dark">
Select Branch
</label>
</div>
<select
value={selectedBranch}
onChange={(e) => setSelectedBranch(e.target.value)}
className="w-full px-3 py-3 rounded-lg bg-white dark:bg-bolt-elements-background-depth-4 border border-bolt-elements-borderColor dark:border-bolt-elements-borderColor-dark text-bolt-elements-textPrimary dark:text-bolt-elements-textPrimary-dark focus:outline-none focus:ring-2 focus:ring-purple-500 shadow-sm"
>
{branches.map((branch) => (
<option
key={branch.name}
value={branch.name}
className="bg-white dark:bg-bolt-elements-background-depth-4 text-bolt-elements-textPrimary dark:text-bolt-elements-textPrimary-dark"
>
{branch.name} {branch.default ? '(default)' : ''}
</option>
))}
</select>
</div>
<div className="flex items-center gap-3 text-sm text-bolt-elements-textSecondary dark:text-bolt-elements-textSecondary-dark">
<div className="h-px flex-grow bg-bolt-elements-borderColor/30 dark:bg-bolt-elements-borderColor-dark/30"></div>
<span>Ready to import?</span>
<div className="h-px flex-grow bg-bolt-elements-borderColor/30 dark:bg-bolt-elements-borderColor-dark/30"></div>
</div>
<motion.button
onClick={handleImport}
className="w-full h-12 px-4 py-2 rounded-xl bg-gradient-to-r from-purple-500 to-purple-600 hover:from-purple-600 hover:to-purple-700 text-white transition-all duration-200 flex items-center gap-2 justify-center shadow-md"
whileHover={{ scale: 1.02, boxShadow: '0 4px 12px rgba(124, 58, 237, 0.3)' }}
whileTap={{ scale: 0.98 }}
>
<span className="i-ph:git-pull-request w-5 h-5" />
Import {selectedRepository.name}
</motion.button>
</div>
) : (
<RepositoryList
repos={activeTab === 'my-repos' ? repositories : searchResults}
isLoading={isLoading}
onSelect={handleRepoSelect}
activeTab={activeTab}
/>
)}
</div>
</>
)}
</div>
</Dialog.Content>
</Dialog.Portal>
{/* GitHub Auth Dialog */}
<GitHubAuthDialog isOpen={showAuthDialog} onClose={handleAuthDialogClose} />
{/* Repository Stats Dialog */}
{currentStats && (
<StatsDialog
isOpen={showStatsDialog}
onClose={() => setShowStatsDialog(false)}
onConfirm={handleStatsConfirm}
stats={currentStats}
isLargeRepo={currentStats.totalSize > 50 * 1024 * 1024}
/>
)}
</Dialog.Root>
</RepositoryDialogContext.Provider>
);
}

View File

@@ -0,0 +1,83 @@
import React from 'react';
import * as Dialog from '@radix-ui/react-dialog';
import { motion } from 'framer-motion';
import type { RepositoryStats } from '~/types/GitHub';
import { formatSize } from '~/utils/formatSize';
import { RepositoryStats as RepoStats } from '~/components/ui';
interface StatsDialogProps {
isOpen: boolean;
onClose: () => void;
onConfirm: () => void;
stats: RepositoryStats;
isLargeRepo?: boolean;
}
export function StatsDialog({ isOpen, onClose, onConfirm, stats, isLargeRepo }: StatsDialogProps) {
return (
<Dialog.Root open={isOpen} onOpenChange={(open) => !open && onClose()}>
<Dialog.Portal>
<Dialog.Overlay className="fixed inset-0 bg-black/50 backdrop-blur-sm z-[9999]" />
<div className="fixed inset-0 flex items-center justify-center z-[9999]">
<motion.div
initial={{ opacity: 0, scale: 0.95 }}
animate={{ opacity: 1, scale: 1 }}
exit={{ opacity: 0, scale: 0.95 }}
transition={{ duration: 0.2 }}
className="w-[90vw] md:w-[500px]"
>
<Dialog.Content className="bg-white dark:bg-bolt-elements-background-depth-1 rounded-lg border border-bolt-elements-borderColor dark:border-bolt-elements-borderColor-dark shadow-xl">
<div className="p-6 space-y-4">
<div className="flex items-center gap-3">
<div className="w-10 h-10 rounded-xl bg-bolt-elements-background-depth-3 flex items-center justify-center text-purple-500">
<span className="i-ph:git-branch w-5 h-5" />
</div>
<div>
<h3 className="text-lg font-medium text-bolt-elements-textPrimary dark:text-bolt-elements-textPrimary-dark">
Repository Overview
</h3>
<p className="text-sm text-bolt-elements-textSecondary dark:text-bolt-elements-textSecondary-dark">
Review repository details before importing
</p>
</div>
</div>
<div className="mt-4 bg-bolt-elements-background-depth-2 dark:bg-bolt-elements-background-depth-3 p-4 rounded-lg">
<RepoStats stats={stats} />
</div>
{isLargeRepo && (
<div className="p-3 bg-yellow-50 dark:bg-yellow-500/10 rounded-lg text-sm flex items-start gap-2">
<span className="i-ph:warning text-yellow-600 dark:text-yellow-500 w-4 h-4 flex-shrink-0 mt-0.5" />
<div className="text-yellow-800 dark:text-yellow-500">
This repository is quite large ({formatSize(stats.totalSize)}). Importing it might take a while
and could impact performance.
</div>
</div>
)}
</div>
<div className="border-t border-bolt-elements-borderColor dark:border-bolt-elements-borderColor-dark p-4 flex justify-end gap-3 bg-bolt-elements-background-depth-2 dark:bg-bolt-elements-background-depth-3 rounded-b-lg">
<motion.button
onClick={onClose}
className="px-4 py-2 rounded-lg bg-bolt-elements-background-depth-3 dark:bg-bolt-elements-background-depth-4 text-bolt-elements-textSecondary hover:text-bolt-elements-textPrimary dark:text-bolt-elements-textSecondary-dark dark:hover:text-bolt-elements-textPrimary-dark transition-colors"
whileHover={{ scale: 1.02 }}
whileTap={{ scale: 0.98 }}
>
Cancel
</motion.button>
<motion.button
onClick={onConfirm}
className="px-4 py-2 rounded-lg bg-purple-500 text-white hover:bg-purple-600 transition-colors"
whileHover={{ scale: 1.02 }}
whileTap={{ scale: 0.98 }}
>
Import Repository
</motion.button>
</div>
</Dialog.Content>
</motion.div>
</div>
</Dialog.Portal>
</Dialog.Root>
);
}

View File

@@ -0,0 +1,95 @@
export interface GitHubUserResponse {
login: string;
avatar_url: string;
html_url: string;
name: string;
bio: string;
public_repos: number;
followers: number;
following: number;
public_gists: number;
created_at: string;
updated_at: string;
}
export interface GitHubRepoInfo {
name: string;
full_name: string;
html_url: string;
description: string;
stargazers_count: number;
forks_count: number;
default_branch: string;
updated_at: string;
language: string;
languages_url: string;
}
export interface GitHubOrganization {
login: string;
avatar_url: string;
description: string;
html_url: string;
}
export interface GitHubEvent {
id: string;
type: string;
created_at: string;
repo: {
name: string;
url: string;
};
payload: {
action?: string;
ref?: string;
ref_type?: string;
description?: string;
};
}
export interface GitHubLanguageStats {
[key: string]: number;
}
export interface GitHubStats {
repos: GitHubRepoInfo[];
totalStars: number;
totalForks: number;
organizations: GitHubOrganization[];
recentActivity: GitHubEvent[];
languages: GitHubLanguageStats;
totalGists: number;
}
export interface GitHubConnection {
user: GitHubUserResponse | null;
token: string;
tokenType: 'classic' | 'fine-grained';
stats?: GitHubStats;
}
export interface GitHubTokenInfo {
token: string;
scope: string[];
avatar_url: string;
name: string | null;
created_at: string;
followers: number;
}
export interface GitHubRateLimits {
limit: number;
remaining: number;
reset: Date;
used: number;
}
export interface GitHubAuthState {
username: string;
tokenInfo: GitHubTokenInfo | null;
isConnected: boolean;
isVerifying: boolean;
isLoadingRepos: boolean;
rateLimits?: GitHubRateLimits;
}

View File

@@ -0,0 +1,721 @@
import { useState, useRef, useCallback, useEffect } from 'react';
import { Button } from '~/components/ui/Button';
import { ConfirmationDialog, SelectionDialog } from '~/components/ui/Dialog';
import { Card, CardHeader, CardTitle, CardDescription, CardContent, CardFooter } from '~/components/ui/Card';
import { motion } from 'framer-motion';
import { useDataOperations } from '~/lib/hooks/useDataOperations';
import { openDatabase } from '~/lib/persistence/db';
import { getAllChats, type Chat } from '~/lib/persistence/chats';
import { DataVisualization } from './DataVisualization';
import { classNames } from '~/utils/classNames';
import { toast } from 'react-toastify';
// Create a custom hook to connect to the boltHistory database
function useBoltHistoryDB() {
const [db, setDb] = useState<IDBDatabase | null>(null);
const [isLoading, setIsLoading] = useState(true);
const [error, setError] = useState<Error | null>(null);
useEffect(() => {
const initDB = async () => {
try {
setIsLoading(true);
const database = await openDatabase();
setDb(database || null);
setIsLoading(false);
} catch (err) {
setError(err instanceof Error ? err : new Error('Unknown error initializing database'));
setIsLoading(false);
}
};
initDB();
return () => {
if (db) {
db.close();
}
};
}, []);
return { db, isLoading, error };
}
// Extend the Chat interface to include the missing properties
interface ExtendedChat extends Chat {
title?: string;
updatedAt?: number;
}
// Helper function to create a chat label and description
function createChatItem(chat: Chat): ChatItem {
return {
id: chat.id,
// Use description as title if available, or format a short ID
label: (chat as ExtendedChat).title || chat.description || `Chat ${chat.id.slice(0, 8)}`,
// Format the description with message count and timestamp
description: `${chat.messages.length} messages - Last updated: ${new Date((chat as ExtendedChat).updatedAt || Date.parse(chat.timestamp)).toLocaleString()}`,
};
}
interface SettingsCategory {
id: string;
label: string;
description: string;
}
interface ChatItem {
id: string;
label: string;
description: string;
}
export function DataTab() {
// Use our custom hook for the boltHistory database
const { db, isLoading: dbLoading } = useBoltHistoryDB();
const fileInputRef = useRef<HTMLInputElement>(null);
const apiKeyFileInputRef = useRef<HTMLInputElement>(null);
const chatFileInputRef = useRef<HTMLInputElement>(null);
// State for confirmation dialogs
const [showResetInlineConfirm, setShowResetInlineConfirm] = useState(false);
const [showDeleteInlineConfirm, setShowDeleteInlineConfirm] = useState(false);
const [showSettingsSelection, setShowSettingsSelection] = useState(false);
const [showChatsSelection, setShowChatsSelection] = useState(false);
// State for settings categories and available chats
const [settingsCategories] = useState<SettingsCategory[]>([
{ id: 'core', label: 'Core Settings', description: 'User profile and main settings' },
{ id: 'providers', label: 'Providers', description: 'API keys and provider configurations' },
{ id: 'features', label: 'Features', description: 'Feature flags and settings' },
{ id: 'ui', label: 'UI', description: 'UI configuration and preferences' },
{ id: 'connections', label: 'Connections', description: 'External service connections' },
{ id: 'debug', label: 'Debug', description: 'Debug settings and logs' },
{ id: 'updates', label: 'Updates', description: 'Update settings and notifications' },
]);
const [availableChats, setAvailableChats] = useState<ExtendedChat[]>([]);
const [chatItems, setChatItems] = useState<ChatItem[]>([]);
// Data operations hook with boltHistory database
const {
isExporting,
isImporting,
isResetting,
isDownloadingTemplate,
handleExportSettings,
handleExportSelectedSettings,
handleExportAllChats,
handleExportSelectedChats,
handleImportSettings,
handleImportChats,
handleResetSettings,
handleResetChats,
handleDownloadTemplate,
handleImportAPIKeys,
} = useDataOperations({
customDb: db || undefined, // Pass the boltHistory database, converting null to undefined
onReloadSettings: () => window.location.reload(),
onReloadChats: () => {
// Reload chats after reset
if (db) {
getAllChats(db).then((chats) => {
// Cast to ExtendedChat to handle additional properties
const extendedChats = chats as ExtendedChat[];
setAvailableChats(extendedChats);
setChatItems(extendedChats.map((chat) => createChatItem(chat)));
});
}
},
onResetSettings: () => setShowResetInlineConfirm(false),
onResetChats: () => setShowDeleteInlineConfirm(false),
});
// Loading states for operations not provided by the hook
const [isDeleting, setIsDeleting] = useState(false);
const [isImportingKeys, setIsImportingKeys] = useState(false);
// Load available chats
useEffect(() => {
if (db) {
console.log('Loading chats from boltHistory database', {
name: db.name,
version: db.version,
objectStoreNames: Array.from(db.objectStoreNames),
});
getAllChats(db)
.then((chats) => {
console.log('Found chats:', chats.length);
// Cast to ExtendedChat to handle additional properties
const extendedChats = chats as ExtendedChat[];
setAvailableChats(extendedChats);
// Create ChatItems for selection dialog
setChatItems(extendedChats.map((chat) => createChatItem(chat)));
})
.catch((error) => {
console.error('Error loading chats:', error);
toast.error('Failed to load chats: ' + (error instanceof Error ? error.message : 'Unknown error'));
});
}
}, [db]);
// Handle file input changes
const handleFileInputChange = useCallback(
(event: React.ChangeEvent<HTMLInputElement>) => {
const file = event.target.files?.[0];
if (file) {
handleImportSettings(file);
}
},
[handleImportSettings],
);
const handleAPIKeyFileInputChange = useCallback(
(event: React.ChangeEvent<HTMLInputElement>) => {
const file = event.target.files?.[0];
if (file) {
setIsImportingKeys(true);
handleImportAPIKeys(file).finally(() => setIsImportingKeys(false));
}
},
[handleImportAPIKeys],
);
const handleChatFileInputChange = useCallback(
(event: React.ChangeEvent<HTMLInputElement>) => {
const file = event.target.files?.[0];
if (file) {
handleImportChats(file);
}
},
[handleImportChats],
);
// Wrapper for reset chats to handle loading state
const handleResetChatsWithState = useCallback(() => {
setIsDeleting(true);
handleResetChats().finally(() => setIsDeleting(false));
}, [handleResetChats]);
return (
<div className="space-y-12">
{/* Hidden file inputs */}
<input ref={fileInputRef} type="file" accept=".json" onChange={handleFileInputChange} className="hidden" />
<input
ref={apiKeyFileInputRef}
type="file"
accept=".json"
onChange={handleAPIKeyFileInputChange}
className="hidden"
/>
<input
ref={chatFileInputRef}
type="file"
accept=".json"
onChange={handleChatFileInputChange}
className="hidden"
/>
{/* Reset Settings Confirmation Dialog */}
<ConfirmationDialog
isOpen={showResetInlineConfirm}
onClose={() => setShowResetInlineConfirm(false)}
title="Reset All Settings?"
description="This will reset all your settings to their default values. This action cannot be undone."
confirmLabel="Reset Settings"
cancelLabel="Cancel"
variant="destructive"
isLoading={isResetting}
onConfirm={handleResetSettings}
/>
{/* Delete Chats Confirmation Dialog */}
<ConfirmationDialog
isOpen={showDeleteInlineConfirm}
onClose={() => setShowDeleteInlineConfirm(false)}
title="Delete All Chats?"
description="This will permanently delete all your chat history. This action cannot be undone."
confirmLabel="Delete All"
cancelLabel="Cancel"
variant="destructive"
isLoading={isDeleting}
onConfirm={handleResetChatsWithState}
/>
{/* Settings Selection Dialog */}
<SelectionDialog
isOpen={showSettingsSelection}
onClose={() => setShowSettingsSelection(false)}
title="Select Settings to Export"
items={settingsCategories}
onConfirm={(selectedIds) => {
handleExportSelectedSettings(selectedIds);
setShowSettingsSelection(false);
}}
confirmLabel="Export Selected"
/>
{/* Chats Selection Dialog */}
<SelectionDialog
isOpen={showChatsSelection}
onClose={() => setShowChatsSelection(false)}
title="Select Chats to Export"
items={chatItems}
onConfirm={(selectedIds) => {
handleExportSelectedChats(selectedIds);
setShowChatsSelection(false);
}}
confirmLabel="Export Selected"
/>
{/* Chats Section */}
<div>
<h2 className="text-xl font-semibold mb-4 text-bolt-elements-textPrimary">Chats</h2>
{dbLoading ? (
<div className="flex items-center justify-center p-4">
<div className="i-ph-spinner-gap-bold animate-spin w-6 h-6 mr-2" />
<span>Loading chats database...</span>
</div>
) : (
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
<Card>
<CardHeader>
<div className="flex items-center mb-2">
<motion.div className="text-accent-500 mr-2" whileHover={{ scale: 1.1 }} whileTap={{ scale: 0.9 }}>
<div className="i-ph-download-duotone w-5 h-5" />
</motion.div>
<CardTitle className="text-lg group-hover:text-bolt-elements-item-contentAccent transition-colors">
Export All Chats
</CardTitle>
</div>
<CardDescription>Export all your chats to a JSON file.</CardDescription>
</CardHeader>
<CardFooter>
<motion.div whileHover={{ scale: 1.03 }} whileTap={{ scale: 0.97 }} className="w-full">
<Button
onClick={async () => {
try {
if (!db) {
toast.error('Database not available');
return;
}
console.log('Database information:', {
name: db.name,
version: db.version,
objectStoreNames: Array.from(db.objectStoreNames),
});
if (availableChats.length === 0) {
toast.warning('No chats available to export');
return;
}
await handleExportAllChats();
} catch (error) {
console.error('Error exporting chats:', error);
toast.error(
`Failed to export chats: ${error instanceof Error ? error.message : 'Unknown error'}`,
);
}
}}
disabled={isExporting || availableChats.length === 0}
variant="outline"
size="sm"
className={classNames(
'hover:text-bolt-elements-item-contentAccent hover:border-bolt-elements-item-backgroundAccent hover:bg-bolt-elements-item-backgroundAccent transition-colors w-full justify-center',
isExporting || availableChats.length === 0 ? 'cursor-not-allowed' : '',
)}
>
{isExporting ? (
<>
<div className="i-ph-spinner-gap-bold animate-spin w-4 h-4 mr-2" />
Exporting...
</>
) : availableChats.length === 0 ? (
'No Chats to Export'
) : (
'Export All'
)}
</Button>
</motion.div>
</CardFooter>
</Card>
<Card>
<CardHeader>
<div className="flex items-center mb-2">
<motion.div className="text-accent-500 mr-2" whileHover={{ scale: 1.1 }} whileTap={{ scale: 0.9 }}>
<div className="i-ph:list-checks w-5 h-5" />
</motion.div>
<CardTitle className="text-lg group-hover:text-bolt-elements-item-contentAccent transition-colors">
Export Selected Chats
</CardTitle>
</div>
<CardDescription>Choose specific chats to export.</CardDescription>
</CardHeader>
<CardFooter>
<motion.div whileHover={{ scale: 1.03 }} whileTap={{ scale: 0.97 }} className="w-full">
<Button
onClick={() => setShowChatsSelection(true)}
disabled={isExporting || chatItems.length === 0}
variant="outline"
size="sm"
className={classNames(
'hover:text-bolt-elements-item-contentAccent hover:border-bolt-elements-item-backgroundAccent hover:bg-bolt-elements-item-backgroundAccent transition-colors w-full justify-center',
isExporting || chatItems.length === 0 ? 'cursor-not-allowed' : '',
)}
>
{isExporting ? (
<>
<div className="i-ph-spinner-gap-bold animate-spin w-4 h-4 mr-2" />
Exporting...
</>
) : (
'Select Chats'
)}
</Button>
</motion.div>
</CardFooter>
</Card>
<Card>
<CardHeader>
<div className="flex items-center mb-2">
<motion.div className="text-accent-500 mr-2" whileHover={{ scale: 1.1 }} whileTap={{ scale: 0.9 }}>
<div className="i-ph-upload-duotone w-5 h-5" />
</motion.div>
<CardTitle className="text-lg group-hover:text-bolt-elements-item-contentAccent transition-colors">
Import Chats
</CardTitle>
</div>
<CardDescription>Import chats from a JSON file.</CardDescription>
</CardHeader>
<CardFooter>
<motion.div whileHover={{ scale: 1.03 }} whileTap={{ scale: 0.97 }} className="w-full">
<Button
onClick={() => chatFileInputRef.current?.click()}
disabled={isImporting}
variant="outline"
size="sm"
className={classNames(
'hover:text-bolt-elements-item-contentAccent hover:border-bolt-elements-item-backgroundAccent hover:bg-bolt-elements-item-backgroundAccent transition-colors w-full justify-center',
isImporting ? 'cursor-not-allowed' : '',
)}
>
{isImporting ? (
<>
<div className="i-ph-spinner-gap-bold animate-spin w-4 h-4 mr-2" />
Importing...
</>
) : (
'Import Chats'
)}
</Button>
</motion.div>
</CardFooter>
</Card>
<Card>
<CardHeader>
<div className="flex items-center mb-2">
<motion.div
className="text-red-500 dark:text-red-400 mr-2"
whileHover={{ scale: 1.1 }}
whileTap={{ scale: 0.9 }}
>
<div className="i-ph-trash-duotone w-5 h-5" />
</motion.div>
<CardTitle className="text-lg group-hover:text-bolt-elements-item-contentAccent transition-colors">
Delete All Chats
</CardTitle>
</div>
<CardDescription>Delete all your chat history.</CardDescription>
</CardHeader>
<CardFooter>
<motion.div whileHover={{ scale: 1.03 }} whileTap={{ scale: 0.97 }} className="w-full">
<Button
onClick={() => setShowDeleteInlineConfirm(true)}
disabled={isDeleting || chatItems.length === 0}
variant="outline"
size="sm"
className={classNames(
'hover:text-bolt-elements-item-contentAccent hover:border-bolt-elements-item-backgroundAccent hover:bg-bolt-elements-item-backgroundAccent transition-colors w-full justify-center',
isDeleting || chatItems.length === 0 ? 'cursor-not-allowed' : '',
)}
>
{isDeleting ? (
<>
<div className="i-ph-spinner-gap-bold animate-spin w-4 h-4 mr-2" />
Deleting...
</>
) : (
'Delete All'
)}
</Button>
</motion.div>
</CardFooter>
</Card>
</div>
)}
</div>
{/* Settings Section */}
<div>
<h2 className="text-xl font-semibold mb-4 text-bolt-elements-textPrimary">Settings</h2>
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
<Card>
<CardHeader>
<div className="flex items-center mb-2">
<motion.div className="text-accent-500 mr-2" whileHover={{ scale: 1.1 }} whileTap={{ scale: 0.9 }}>
<div className="i-ph-download-duotone w-5 h-5" />
</motion.div>
<CardTitle className="text-lg group-hover:text-bolt-elements-item-contentAccent transition-colors">
Export All Settings
</CardTitle>
</div>
<CardDescription>Export all your settings to a JSON file.</CardDescription>
</CardHeader>
<CardFooter>
<motion.div whileHover={{ scale: 1.03 }} whileTap={{ scale: 0.97 }} className="w-full">
<Button
onClick={handleExportSettings}
disabled={isExporting}
variant="outline"
size="sm"
className={classNames(
'hover:text-bolt-elements-item-contentAccent hover:border-bolt-elements-item-backgroundAccent hover:bg-bolt-elements-item-backgroundAccent transition-colors w-full justify-center',
isExporting ? 'cursor-not-allowed' : '',
)}
>
{isExporting ? (
<>
<div className="i-ph-spinner-gap-bold animate-spin w-4 h-4 mr-2" />
Exporting...
</>
) : (
'Export All'
)}
</Button>
</motion.div>
</CardFooter>
</Card>
<Card>
<CardHeader>
<div className="flex items-center mb-2">
<motion.div className="text-accent-500 mr-2" whileHover={{ scale: 1.1 }} whileTap={{ scale: 0.9 }}>
<div className="i-ph-filter-duotone w-5 h-5" />
</motion.div>
<CardTitle className="text-lg group-hover:text-bolt-elements-item-contentAccent transition-colors">
Export Selected Settings
</CardTitle>
</div>
<CardDescription>Choose specific settings to export.</CardDescription>
</CardHeader>
<CardFooter>
<motion.div whileHover={{ scale: 1.03 }} whileTap={{ scale: 0.97 }} className="w-full">
<Button
onClick={() => setShowSettingsSelection(true)}
disabled={isExporting || settingsCategories.length === 0}
variant="outline"
size="sm"
className={classNames(
'hover:text-bolt-elements-item-contentAccent hover:border-bolt-elements-item-backgroundAccent hover:bg-bolt-elements-item-backgroundAccent transition-colors w-full justify-center',
isExporting || settingsCategories.length === 0 ? 'cursor-not-allowed' : '',
)}
>
{isExporting ? (
<>
<div className="i-ph-spinner-gap-bold animate-spin w-4 h-4 mr-2" />
Exporting...
</>
) : (
'Select Settings'
)}
</Button>
</motion.div>
</CardFooter>
</Card>
<Card>
<CardHeader>
<div className="flex items-center mb-2">
<motion.div className="text-accent-500 mr-2" whileHover={{ scale: 1.1 }} whileTap={{ scale: 0.9 }}>
<div className="i-ph-upload-duotone w-5 h-5" />
</motion.div>
<CardTitle className="text-lg group-hover:text-bolt-elements-item-contentAccent transition-colors">
Import Settings
</CardTitle>
</div>
<CardDescription>Import settings from a JSON file.</CardDescription>
</CardHeader>
<CardFooter>
<motion.div whileHover={{ scale: 1.03 }} whileTap={{ scale: 0.97 }} className="w-full">
<Button
onClick={() => fileInputRef.current?.click()}
disabled={isImporting}
variant="outline"
size="sm"
className={classNames(
'hover:text-bolt-elements-item-contentAccent hover:border-bolt-elements-item-backgroundAccent hover:bg-bolt-elements-item-backgroundAccent transition-colors w-full justify-center',
isImporting ? 'cursor-not-allowed' : '',
)}
>
{isImporting ? (
<>
<div className="i-ph-spinner-gap-bold animate-spin w-4 h-4 mr-2" />
Importing...
</>
) : (
'Import Settings'
)}
</Button>
</motion.div>
</CardFooter>
</Card>
<Card>
<CardHeader>
<div className="flex items-center mb-2">
<motion.div
className="text-red-500 dark:text-red-400 mr-2"
whileHover={{ scale: 1.1 }}
whileTap={{ scale: 0.9 }}
>
<div className="i-ph-arrow-counter-clockwise-duotone w-5 h-5" />
</motion.div>
<CardTitle className="text-lg group-hover:text-bolt-elements-item-contentAccent transition-colors">
Reset All Settings
</CardTitle>
</div>
<CardDescription>Reset all settings to their default values.</CardDescription>
</CardHeader>
<CardFooter>
<motion.div whileHover={{ scale: 1.03 }} whileTap={{ scale: 0.97 }} className="w-full">
<Button
onClick={() => setShowResetInlineConfirm(true)}
disabled={isResetting}
variant="outline"
size="sm"
className={classNames(
'hover:text-bolt-elements-item-contentAccent hover:border-bolt-elements-item-backgroundAccent hover:bg-bolt-elements-item-backgroundAccent transition-colors w-full justify-center',
isResetting ? 'cursor-not-allowed' : '',
)}
>
{isResetting ? (
<>
<div className="i-ph-spinner-gap-bold animate-spin w-4 h-4 mr-2" />
Resetting...
</>
) : (
'Reset All'
)}
</Button>
</motion.div>
</CardFooter>
</Card>
</div>
</div>
{/* API Keys Section */}
<div>
<h2 className="text-xl font-semibold mb-4 text-bolt-elements-textPrimary">API Keys</h2>
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
<Card>
<CardHeader>
<div className="flex items-center mb-2">
<motion.div className="text-accent-500 mr-2" whileHover={{ scale: 1.1 }} whileTap={{ scale: 0.9 }}>
<div className="i-ph-file-text-duotone w-5 h-5" />
</motion.div>
<CardTitle className="text-lg group-hover:text-bolt-elements-item-contentAccent transition-colors">
Download Template
</CardTitle>
</div>
<CardDescription>Download a template file for your API keys.</CardDescription>
</CardHeader>
<CardFooter>
<motion.div whileHover={{ scale: 1.03 }} whileTap={{ scale: 0.97 }} className="w-full">
<Button
onClick={handleDownloadTemplate}
disabled={isDownloadingTemplate}
variant="outline"
size="sm"
className={classNames(
'hover:text-bolt-elements-item-contentAccent hover:border-bolt-elements-item-backgroundAccent hover:bg-bolt-elements-item-backgroundAccent transition-colors w-full justify-center',
isDownloadingTemplate ? 'cursor-not-allowed' : '',
)}
>
{isDownloadingTemplate ? (
<>
<div className="i-ph-spinner-gap-bold animate-spin w-4 h-4 mr-2" />
Downloading...
</>
) : (
'Download'
)}
</Button>
</motion.div>
</CardFooter>
</Card>
<Card>
<CardHeader>
<div className="flex items-center mb-2">
<motion.div className="text-accent-500 mr-2" whileHover={{ scale: 1.1 }} whileTap={{ scale: 0.9 }}>
<div className="i-ph-upload-duotone w-5 h-5" />
</motion.div>
<CardTitle className="text-lg group-hover:text-bolt-elements-item-contentAccent transition-colors">
Import API Keys
</CardTitle>
</div>
<CardDescription>Import API keys from a JSON file.</CardDescription>
</CardHeader>
<CardFooter>
<motion.div whileHover={{ scale: 1.03 }} whileTap={{ scale: 0.97 }} className="w-full">
<Button
onClick={() => apiKeyFileInputRef.current?.click()}
disabled={isImportingKeys}
variant="outline"
size="sm"
className={classNames(
'hover:text-bolt-elements-item-contentAccent hover:border-bolt-elements-item-backgroundAccent hover:bg-bolt-elements-item-backgroundAccent transition-colors w-full justify-center',
isImportingKeys ? 'cursor-not-allowed' : '',
)}
>
{isImportingKeys ? (
<>
<div className="i-ph-spinner-gap-bold animate-spin w-4 h-4 mr-2" />
Importing...
</>
) : (
'Import Keys'
)}
</Button>
</motion.div>
</CardFooter>
</Card>
</div>
</div>
{/* Data Visualization */}
<div>
<h2 className="text-xl font-semibold mb-4 text-bolt-elements-textPrimary">Data Usage</h2>
<Card>
<CardContent className="p-5">
<DataVisualization chats={availableChats} />
</CardContent>
</Card>
</div>
</div>
);
}

View File

@@ -0,0 +1,384 @@
import { useState, useEffect } from 'react';
import {
Chart as ChartJS,
CategoryScale,
LinearScale,
BarElement,
Title,
Tooltip,
Legend,
ArcElement,
PointElement,
LineElement,
} from 'chart.js';
import { Bar, Pie } from 'react-chartjs-2';
import type { Chat } from '~/lib/persistence/chats';
import { classNames } from '~/utils/classNames';
// Register ChartJS components
ChartJS.register(CategoryScale, LinearScale, BarElement, Title, Tooltip, Legend, ArcElement, PointElement, LineElement);
type DataVisualizationProps = {
chats: Chat[];
};
export function DataVisualization({ chats }: DataVisualizationProps) {
const [chatsByDate, setChatsByDate] = useState<Record<string, number>>({});
const [messagesByRole, setMessagesByRole] = useState<Record<string, number>>({});
const [apiKeyUsage, setApiKeyUsage] = useState<Array<{ provider: string; count: number }>>([]);
const [averageMessagesPerChat, setAverageMessagesPerChat] = useState<number>(0);
const [isDarkMode, setIsDarkMode] = useState(false);
useEffect(() => {
const isDark = document.documentElement.classList.contains('dark');
setIsDarkMode(isDark);
const observer = new MutationObserver((mutations) => {
mutations.forEach((mutation) => {
if (mutation.attributeName === 'class') {
setIsDarkMode(document.documentElement.classList.contains('dark'));
}
});
});
observer.observe(document.documentElement, { attributes: true });
return () => observer.disconnect();
}, []);
useEffect(() => {
if (!chats || chats.length === 0) {
return;
}
// Process chat data
const chatDates: Record<string, number> = {};
const roleCounts: Record<string, number> = {};
const apiUsage: Record<string, number> = {};
let totalMessages = 0;
chats.forEach((chat) => {
const date = new Date(chat.timestamp).toLocaleDateString();
chatDates[date] = (chatDates[date] || 0) + 1;
chat.messages.forEach((message) => {
roleCounts[message.role] = (roleCounts[message.role] || 0) + 1;
totalMessages++;
if (message.role === 'assistant') {
const providerMatch = message.content.match(/provider:\s*([\w-]+)/i);
const provider = providerMatch ? providerMatch[1] : 'unknown';
apiUsage[provider] = (apiUsage[provider] || 0) + 1;
}
});
});
const sortedDates = Object.keys(chatDates).sort((a, b) => new Date(a).getTime() - new Date(b).getTime());
const sortedChatsByDate: Record<string, number> = {};
sortedDates.forEach((date) => {
sortedChatsByDate[date] = chatDates[date];
});
setChatsByDate(sortedChatsByDate);
setMessagesByRole(roleCounts);
setApiKeyUsage(Object.entries(apiUsage).map(([provider, count]) => ({ provider, count })));
setAverageMessagesPerChat(totalMessages / chats.length);
}, [chats]);
// Get theme colors from CSS variables to ensure theme consistency
const getThemeColor = (varName: string): string => {
// Get the CSS variable value from document root
if (typeof document !== 'undefined') {
return getComputedStyle(document.documentElement).getPropertyValue(varName).trim();
}
// Fallback for SSR
return isDarkMode ? '#FFFFFF' : '#000000';
};
// Theme-aware chart colors with enhanced dark mode visibility using CSS variables
const chartColors = {
grid: isDarkMode ? 'rgba(255, 255, 255, 0.2)' : 'rgba(0, 0, 0, 0.1)',
text: getThemeColor('--bolt-elements-textPrimary'),
textSecondary: getThemeColor('--bolt-elements-textSecondary'),
background: getThemeColor('--bolt-elements-bg-depth-1'),
accent: getThemeColor('--bolt-elements-button-primary-text'),
border: getThemeColor('--bolt-elements-borderColor'),
};
const getChartColors = (index: number) => {
// Define color palettes based on Bolt design tokens
const baseColors = [
// Indigo
{
base: getThemeColor('--bolt-elements-button-primary-text'),
},
// Pink
{
base: isDarkMode ? 'rgb(244, 114, 182)' : 'rgb(236, 72, 153)',
},
// Green
{
base: getThemeColor('--bolt-elements-icon-success'),
},
// Yellow
{
base: isDarkMode ? 'rgb(250, 204, 21)' : 'rgb(234, 179, 8)',
},
// Blue
{
base: isDarkMode ? 'rgb(56, 189, 248)' : 'rgb(14, 165, 233)',
},
];
// Get the base color for this index
const color = baseColors[index % baseColors.length].base;
// Parse color and generate variations with appropriate opacity
let r = 0,
g = 0,
b = 0;
// Handle rgb/rgba format
const rgbMatch = color.match(/rgb\((\d+),\s*(\d+),\s*(\d+)\)/);
const rgbaMatch = color.match(/rgba\((\d+),\s*(\d+),\s*(\d+),\s*([0-9.]+)\)/);
if (rgbMatch) {
[, r, g, b] = rgbMatch.map(Number);
} else if (rgbaMatch) {
[, r, g, b] = rgbaMatch.map(Number);
} else if (color.startsWith('#')) {
// Handle hex format
const hex = color.slice(1);
const bigint = parseInt(hex, 16);
r = (bigint >> 16) & 255;
g = (bigint >> 8) & 255;
b = bigint & 255;
}
return {
bg: `rgba(${r}, ${g}, ${b}, ${isDarkMode ? 0.7 : 0.5})`,
border: `rgba(${r}, ${g}, ${b}, ${isDarkMode ? 0.9 : 0.8})`,
};
};
const chartData = {
history: {
labels: Object.keys(chatsByDate),
datasets: [
{
label: 'Chats Created',
data: Object.values(chatsByDate),
backgroundColor: getChartColors(0).bg,
borderColor: getChartColors(0).border,
borderWidth: 1,
},
],
},
roles: {
labels: Object.keys(messagesByRole),
datasets: [
{
label: 'Messages by Role',
data: Object.values(messagesByRole),
backgroundColor: Object.keys(messagesByRole).map((_, i) => getChartColors(i).bg),
borderColor: Object.keys(messagesByRole).map((_, i) => getChartColors(i).border),
borderWidth: 1,
},
],
},
apiUsage: {
labels: apiKeyUsage.map((item) => item.provider),
datasets: [
{
label: 'API Usage',
data: apiKeyUsage.map((item) => item.count),
backgroundColor: apiKeyUsage.map((_, i) => getChartColors(i).bg),
borderColor: apiKeyUsage.map((_, i) => getChartColors(i).border),
borderWidth: 1,
},
],
},
};
const baseChartOptions = {
responsive: true,
maintainAspectRatio: false,
color: chartColors.text,
plugins: {
legend: {
position: 'top' as const,
labels: {
color: chartColors.text,
font: {
weight: 'bold' as const,
size: 12,
},
padding: 16,
usePointStyle: true,
},
},
title: {
display: true,
color: chartColors.text,
font: {
size: 16,
weight: 'bold' as const,
},
padding: 16,
},
tooltip: {
titleColor: chartColors.text,
bodyColor: chartColors.text,
backgroundColor: isDarkMode
? 'rgba(23, 23, 23, 0.8)' // Dark bg using Tailwind gray-900
: 'rgba(255, 255, 255, 0.8)', // Light bg
borderColor: chartColors.border,
borderWidth: 1,
},
},
};
const chartOptions = {
...baseChartOptions,
plugins: {
...baseChartOptions.plugins,
title: {
...baseChartOptions.plugins.title,
text: 'Chat History',
},
},
scales: {
x: {
grid: {
color: chartColors.grid,
drawBorder: false,
},
border: {
display: false,
},
ticks: {
color: chartColors.text,
font: {
weight: 500,
},
},
},
y: {
grid: {
color: chartColors.grid,
drawBorder: false,
},
border: {
display: false,
},
ticks: {
color: chartColors.text,
font: {
weight: 500,
},
},
},
},
};
const pieOptions = {
...baseChartOptions,
plugins: {
...baseChartOptions.plugins,
title: {
...baseChartOptions.plugins.title,
text: 'Message Distribution',
},
legend: {
...baseChartOptions.plugins.legend,
position: 'right' as const,
},
datalabels: {
color: chartColors.text,
font: {
weight: 'bold' as const,
},
},
},
};
if (chats.length === 0) {
return (
<div className="text-center py-8">
<div className="i-ph-chart-line-duotone w-12 h-12 mx-auto mb-4 text-bolt-elements-textTertiary opacity-80" />
<h3 className="text-lg font-medium text-bolt-elements-textPrimary mb-2">No Data Available</h3>
<p className="text-bolt-elements-textSecondary">
Start creating chats to see your usage statistics and data visualization.
</p>
</div>
);
}
const cardClasses = classNames(
'p-6 rounded-lg shadow-sm',
'bg-bolt-elements-bg-depth-1',
'border border-bolt-elements-borderColor',
);
const statClasses = classNames('text-3xl font-bold text-bolt-elements-textPrimary', 'flex items-center gap-3');
return (
<div className="space-y-8">
<div className="grid grid-cols-1 md:grid-cols-3 gap-6">
<div className={cardClasses}>
<h3 className="text-lg font-medium text-bolt-elements-textPrimary mb-4">Total Chats</h3>
<div className={statClasses}>
<div className="i-ph-chats-duotone w-8 h-8 text-indigo-500 dark:text-indigo-400" />
<span>{chats.length}</span>
</div>
</div>
<div className={cardClasses}>
<h3 className="text-lg font-medium text-bolt-elements-textPrimary mb-4">Total Messages</h3>
<div className={statClasses}>
<div className="i-ph-chat-text-duotone w-8 h-8 text-pink-500 dark:text-pink-400" />
<span>{Object.values(messagesByRole).reduce((sum, count) => sum + count, 0)}</span>
</div>
</div>
<div className={cardClasses}>
<h3 className="text-lg font-medium text-bolt-elements-textPrimary mb-4">Avg. Messages/Chat</h3>
<div className={statClasses}>
<div className="i-ph-chart-bar-duotone w-8 h-8 text-green-500 dark:text-green-400" />
<span>{averageMessagesPerChat.toFixed(1)}</span>
</div>
</div>
</div>
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
<div className={cardClasses}>
<h3 className="text-lg font-medium text-bolt-elements-textPrimary mb-6">Chat History</h3>
<div className="h-64">
<Bar data={chartData.history} options={chartOptions} />
</div>
</div>
<div className={cardClasses}>
<h3 className="text-lg font-medium text-bolt-elements-textPrimary mb-6">Message Distribution</h3>
<div className="h-64">
<Pie data={chartData.roles} options={pieOptions} />
</div>
</div>
</div>
{apiKeyUsage.length > 0 && (
<div className={cardClasses}>
<h3 className="text-lg font-medium text-bolt-elements-textPrimary mb-6">API Usage by Provider</h3>
<div className="h-64">
<Pie data={chartData.apiUsage} options={pieOptions} />
</div>
</div>
)}
</div>
);
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,295 @@
// Remove unused imports
import React, { memo, useCallback } from 'react';
import { motion } from 'framer-motion';
import { Switch } from '~/components/ui/Switch';
import { useSettings } from '~/lib/hooks/useSettings';
import { classNames } from '~/utils/classNames';
import { toast } from 'react-toastify';
import { PromptLibrary } from '~/lib/common/prompt-library';
interface FeatureToggle {
id: string;
title: string;
description: string;
icon: string;
enabled: boolean;
beta?: boolean;
experimental?: boolean;
tooltip?: string;
}
const FeatureCard = memo(
({
feature,
index,
onToggle,
}: {
feature: FeatureToggle;
index: number;
onToggle: (id: string, enabled: boolean) => void;
}) => (
<motion.div
key={feature.id}
layoutId={feature.id}
className={classNames(
'relative group cursor-pointer',
'bg-bolt-elements-background-depth-2',
'hover:bg-bolt-elements-background-depth-3',
'transition-colors duration-200',
'rounded-lg overflow-hidden',
)}
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ delay: index * 0.1 }}
>
<div className="p-4">
<div className="flex items-center justify-between">
<div className="flex items-center gap-3">
<div className={classNames(feature.icon, 'w-5 h-5 text-bolt-elements-textSecondary')} />
<div className="flex items-center gap-2">
<h4 className="font-medium text-bolt-elements-textPrimary">{feature.title}</h4>
{feature.beta && (
<span className="px-2 py-0.5 text-xs rounded-full bg-blue-500/10 text-blue-500 font-medium">Beta</span>
)}
{feature.experimental && (
<span className="px-2 py-0.5 text-xs rounded-full bg-orange-500/10 text-orange-500 font-medium">
Experimental
</span>
)}
</div>
</div>
<Switch checked={feature.enabled} onCheckedChange={(checked) => onToggle(feature.id, checked)} />
</div>
<p className="mt-2 text-sm text-bolt-elements-textSecondary">{feature.description}</p>
{feature.tooltip && <p className="mt-1 text-xs text-bolt-elements-textTertiary">{feature.tooltip}</p>}
</div>
</motion.div>
),
);
const FeatureSection = memo(
({
title,
features,
icon,
description,
onToggleFeature,
}: {
title: string;
features: FeatureToggle[];
icon: string;
description: string;
onToggleFeature: (id: string, enabled: boolean) => void;
}) => (
<motion.div
layout
className="flex flex-col gap-4"
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ duration: 0.3 }}
>
<div className="flex items-center gap-3">
<div className={classNames(icon, 'text-xl text-purple-500')} />
<div>
<h3 className="text-lg font-medium text-bolt-elements-textPrimary">{title}</h3>
<p className="text-sm text-bolt-elements-textSecondary">{description}</p>
</div>
</div>
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
{features.map((feature, index) => (
<FeatureCard key={feature.id} feature={feature} index={index} onToggle={onToggleFeature} />
))}
</div>
</motion.div>
),
);
export default function FeaturesTab() {
const {
autoSelectTemplate,
isLatestBranch,
contextOptimizationEnabled,
eventLogs,
setAutoSelectTemplate,
enableLatestBranch,
enableContextOptimization,
setEventLogs,
setPromptId,
promptId,
} = useSettings();
// Enable features by default on first load
React.useEffect(() => {
// Only set defaults if values are undefined
if (isLatestBranch === undefined) {
enableLatestBranch(false); // Default: OFF - Don't auto-update from main branch
}
if (contextOptimizationEnabled === undefined) {
enableContextOptimization(true); // Default: ON - Enable context optimization
}
if (autoSelectTemplate === undefined) {
setAutoSelectTemplate(true); // Default: ON - Enable auto-select templates
}
if (promptId === undefined) {
setPromptId('default'); // Default: 'default'
}
if (eventLogs === undefined) {
setEventLogs(true); // Default: ON - Enable event logging
}
}, []); // Only run once on component mount
const handleToggleFeature = useCallback(
(id: string, enabled: boolean) => {
switch (id) {
case 'latestBranch': {
enableLatestBranch(enabled);
toast.success(`Main branch updates ${enabled ? 'enabled' : 'disabled'}`);
break;
}
case 'autoSelectTemplate': {
setAutoSelectTemplate(enabled);
toast.success(`Auto select template ${enabled ? 'enabled' : 'disabled'}`);
break;
}
case 'contextOptimization': {
enableContextOptimization(enabled);
toast.success(`Context optimization ${enabled ? 'enabled' : 'disabled'}`);
break;
}
case 'eventLogs': {
setEventLogs(enabled);
toast.success(`Event logging ${enabled ? 'enabled' : 'disabled'}`);
break;
}
default:
break;
}
},
[enableLatestBranch, setAutoSelectTemplate, enableContextOptimization, setEventLogs],
);
const features = {
stable: [
{
id: 'latestBranch',
title: 'Main Branch Updates',
description: 'Get the latest updates from the main branch',
icon: 'i-ph:git-branch',
enabled: isLatestBranch,
tooltip: 'Enabled by default to receive updates from the main development branch',
},
{
id: 'autoSelectTemplate',
title: 'Auto Select Template',
description: 'Automatically select starter template',
icon: 'i-ph:selection',
enabled: autoSelectTemplate,
tooltip: 'Enabled by default to automatically select the most appropriate starter template',
},
{
id: 'contextOptimization',
title: 'Context Optimization',
description: 'Optimize context for better responses',
icon: 'i-ph:brain',
enabled: contextOptimizationEnabled,
tooltip: 'Enabled by default for improved AI responses',
},
{
id: 'eventLogs',
title: 'Event Logging',
description: 'Enable detailed event logging and history',
icon: 'i-ph:list-bullets',
enabled: eventLogs,
tooltip: 'Enabled by default to record detailed logs of system events and user actions',
},
],
beta: [],
};
return (
<div className="flex flex-col gap-8">
<FeatureSection
title="Core Features"
features={features.stable}
icon="i-ph:check-circle"
description="Essential features that are enabled by default for optimal performance"
onToggleFeature={handleToggleFeature}
/>
{features.beta.length > 0 && (
<FeatureSection
title="Beta Features"
features={features.beta}
icon="i-ph:test-tube"
description="New features that are ready for testing but may have some rough edges"
onToggleFeature={handleToggleFeature}
/>
)}
<motion.div
layout
className={classNames(
'bg-bolt-elements-background-depth-2',
'hover:bg-bolt-elements-background-depth-3',
'transition-all duration-200',
'rounded-lg p-4',
'group',
)}
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ delay: 0.3 }}
>
<div className="flex items-center gap-4">
<div
className={classNames(
'p-2 rounded-lg text-xl',
'bg-bolt-elements-background-depth-3 group-hover:bg-bolt-elements-background-depth-4',
'transition-colors duration-200',
'text-purple-500',
)}
>
<div className="i-ph:book" />
</div>
<div className="flex-1">
<h4 className="text-sm font-medium text-bolt-elements-textPrimary group-hover:text-purple-500 transition-colors">
Prompt Library
</h4>
<p className="text-xs text-bolt-elements-textSecondary mt-0.5">
Choose a prompt from the library to use as the system prompt
</p>
</div>
<select
value={promptId}
onChange={(e) => {
setPromptId(e.target.value);
toast.success('Prompt template updated');
}}
className={classNames(
'p-2 rounded-lg text-sm min-w-[200px]',
'bg-bolt-elements-background-depth-3 border border-bolt-elements-borderColor',
'text-bolt-elements-textPrimary',
'focus:outline-none focus:ring-2 focus:ring-purple-500/30',
'group-hover:border-purple-500/30',
'transition-all duration-200',
)}
>
{PromptLibrary.getList().map((x) => (
<option key={x.id} value={x.id}>
{x.label}
</option>
))}
</select>
</div>
</motion.div>
</div>
);
}

View File

@@ -0,0 +1,300 @@
import React, { useState, useEffect } from 'react';
import { motion } from 'framer-motion';
import { logStore } from '~/lib/stores/logs';
import { useStore } from '@nanostores/react';
import { formatDistanceToNow } from 'date-fns';
import { classNames } from '~/utils/classNames';
import * as DropdownMenu from '@radix-ui/react-dropdown-menu';
interface NotificationDetails {
type?: string;
message?: string;
currentVersion?: string;
latestVersion?: string;
branch?: string;
updateUrl?: string;
}
type FilterType = 'all' | 'system' | 'error' | 'warning' | 'update' | 'info' | 'provider' | 'network';
const NotificationsTab = () => {
const [filter, setFilter] = useState<FilterType>('all');
const logs = useStore(logStore.logs);
useEffect(() => {
const startTime = performance.now();
return () => {
const duration = performance.now() - startTime;
logStore.logPerformanceMetric('NotificationsTab', 'mount-duration', duration);
};
}, []);
const handleClearNotifications = () => {
const count = Object.keys(logs).length;
logStore.logInfo('Cleared notifications', {
type: 'notification_clear',
message: `Cleared ${count} notifications`,
clearedCount: count,
component: 'notifications',
});
logStore.clearLogs();
};
const handleUpdateAction = (updateUrl: string) => {
logStore.logInfo('Update link clicked', {
type: 'update_click',
message: 'User clicked update link',
updateUrl,
component: 'notifications',
});
window.open(updateUrl, '_blank');
};
const handleFilterChange = (newFilter: FilterType) => {
logStore.logInfo('Notification filter changed', {
type: 'filter_change',
message: `Filter changed to ${newFilter}`,
previousFilter: filter,
newFilter,
component: 'notifications',
});
setFilter(newFilter);
};
const filteredLogs = Object.values(logs)
.filter((log) => {
if (filter === 'all') {
return true;
}
if (filter === 'update') {
return log.details?.type === 'update';
}
if (filter === 'system') {
return log.category === 'system';
}
if (filter === 'provider') {
return log.category === 'provider';
}
if (filter === 'network') {
return log.category === 'network';
}
return log.level === filter;
})
.sort((a, b) => new Date(b.timestamp).getTime() - new Date(a.timestamp).getTime());
const getNotificationStyle = (level: string, type?: string) => {
if (type === 'update') {
return {
icon: 'i-ph:arrow-circle-up',
color: 'text-purple-500 dark:text-purple-400',
bg: 'hover:bg-purple-500/10 dark:hover:bg-purple-500/20',
};
}
switch (level) {
case 'error':
return {
icon: 'i-ph:warning-circle',
color: 'text-red-500 dark:text-red-400',
bg: 'hover:bg-red-500/10 dark:hover:bg-red-500/20',
};
case 'warning':
return {
icon: 'i-ph:warning',
color: 'text-yellow-500 dark:text-yellow-400',
bg: 'hover:bg-yellow-500/10 dark:hover:bg-yellow-500/20',
};
case 'info':
return {
icon: 'i-ph:info',
color: 'text-blue-500 dark:text-blue-400',
bg: 'hover:bg-blue-500/10 dark:hover:bg-blue-500/20',
};
default:
return {
icon: 'i-ph:bell',
color: 'text-gray-500 dark:text-gray-400',
bg: 'hover:bg-gray-500/10 dark:hover:bg-gray-500/20',
};
}
};
const renderNotificationDetails = (details: NotificationDetails) => {
if (details.type === 'update') {
return (
<div className="flex flex-col gap-2">
<p className="text-sm text-gray-600 dark:text-gray-400">{details.message}</p>
<div className="flex flex-col gap-1 text-xs text-gray-500 dark:text-gray-500">
<p>Current Version: {details.currentVersion}</p>
<p>Latest Version: {details.latestVersion}</p>
<p>Branch: {details.branch}</p>
</div>
<button
onClick={() => details.updateUrl && handleUpdateAction(details.updateUrl)}
className={classNames(
'mt-2 inline-flex items-center gap-2',
'rounded-lg px-3 py-1.5',
'text-sm font-medium',
'bg-[#FAFAFA] dark:bg-[#0A0A0A]',
'border border-[#E5E5E5] dark:border-[#1A1A1A]',
'text-gray-900 dark:text-white',
'hover:bg-purple-500/10 dark:hover:bg-purple-500/20',
'transition-all duration-200',
)}
>
<span className="i-ph:git-branch text-lg" />
View Changes
</button>
</div>
);
}
return details.message ? <p className="text-sm text-gray-600 dark:text-gray-400">{details.message}</p> : null;
};
const filterOptions: { id: FilterType; label: string; icon: string; color: string }[] = [
{ id: 'all', label: 'All Notifications', icon: 'i-ph:bell', color: '#9333ea' },
{ id: 'system', label: 'System', icon: 'i-ph:gear', color: '#6b7280' },
{ id: 'update', label: 'Updates', icon: 'i-ph:arrow-circle-up', color: '#9333ea' },
{ id: 'error', label: 'Errors', icon: 'i-ph:warning-circle', color: '#ef4444' },
{ id: 'warning', label: 'Warnings', icon: 'i-ph:warning', color: '#f59e0b' },
{ id: 'info', label: 'Information', icon: 'i-ph:info', color: '#3b82f6' },
{ id: 'provider', label: 'Providers', icon: 'i-ph:robot', color: '#10b981' },
{ id: 'network', label: 'Network', icon: 'i-ph:wifi-high', color: '#6366f1' },
];
return (
<div className="flex h-full flex-col gap-6">
<div className="flex items-center justify-between">
<DropdownMenu.Root>
<DropdownMenu.Trigger asChild>
<button
className={classNames(
'flex items-center gap-2',
'rounded-lg px-3 py-1.5',
'text-sm text-gray-900 dark:text-white',
'bg-[#FAFAFA] dark:bg-[#0A0A0A]',
'border border-[#E5E5E5] dark:border-[#1A1A1A]',
'hover:bg-purple-500/10 dark:hover:bg-purple-500/20',
'transition-all duration-200',
)}
>
<span
className={classNames('text-lg', filterOptions.find((opt) => opt.id === filter)?.icon || 'i-ph:funnel')}
style={{ color: filterOptions.find((opt) => opt.id === filter)?.color }}
/>
{filterOptions.find((opt) => opt.id === filter)?.label || 'Filter Notifications'}
<span className="i-ph:caret-down text-lg text-gray-500 dark:text-gray-400" />
</button>
</DropdownMenu.Trigger>
<DropdownMenu.Portal>
<DropdownMenu.Content
className="min-w-[200px] bg-white dark:bg-[#0A0A0A] rounded-lg shadow-lg py-1 z-[250] animate-in fade-in-0 zoom-in-95 border border-[#E5E5E5] dark:border-[#1A1A1A]"
sideOffset={5}
align="start"
side="bottom"
>
{filterOptions.map((option) => (
<DropdownMenu.Item
key={option.id}
className="group flex items-center px-4 py-2.5 text-sm text-gray-700 dark:text-gray-200 hover:bg-purple-500/10 dark:hover:bg-purple-500/20 cursor-pointer transition-colors"
onClick={() => handleFilterChange(option.id)}
>
<div className="mr-3 flex h-5 w-5 items-center justify-center">
<div
className={classNames(option.icon, 'text-lg group-hover:text-purple-500 transition-colors')}
style={{ color: option.color }}
/>
</div>
<span className="group-hover:text-purple-500 transition-colors">{option.label}</span>
</DropdownMenu.Item>
))}
</DropdownMenu.Content>
</DropdownMenu.Portal>
</DropdownMenu.Root>
<button
onClick={handleClearNotifications}
className={classNames(
'group flex items-center gap-2',
'rounded-lg px-3 py-1.5',
'text-sm text-gray-900 dark:text-white',
'bg-[#FAFAFA] dark:bg-[#0A0A0A]',
'border border-[#E5E5E5] dark:border-[#1A1A1A]',
'hover:bg-purple-500/10 dark:hover:bg-purple-500/20',
'transition-all duration-200',
)}
>
<span className="i-ph:trash text-lg text-gray-500 dark:text-gray-400 group-hover:text-purple-500 transition-colors" />
Clear All
</button>
</div>
<div className="flex flex-col gap-4">
{filteredLogs.length === 0 ? (
<motion.div
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
className={classNames(
'flex flex-col items-center justify-center gap-4',
'rounded-lg p-8 text-center',
'bg-[#FAFAFA] dark:bg-[#0A0A0A]',
'border border-[#E5E5E5] dark:border-[#1A1A1A]',
)}
>
<span className="i-ph:bell-slash text-4xl text-gray-400 dark:text-gray-600" />
<div className="flex flex-col gap-1">
<h3 className="text-sm font-medium text-gray-900 dark:text-white">No Notifications</h3>
<p className="text-sm text-gray-500 dark:text-gray-400">You're all caught up!</p>
</div>
</motion.div>
) : (
filteredLogs.map((log) => {
const style = getNotificationStyle(log.level, log.details?.type);
return (
<motion.div
key={log.id}
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
className={classNames(
'flex flex-col gap-2',
'rounded-lg p-4',
'bg-[#FAFAFA] dark:bg-[#0A0A0A]',
'border border-[#E5E5E5] dark:border-[#1A1A1A]',
style.bg,
'transition-all duration-200',
)}
>
<div className="flex items-start justify-between gap-4">
<div className="flex items-start gap-3">
<span className={classNames('text-lg', style.icon, style.color)} />
<div className="flex flex-col gap-1">
<h3 className="text-sm font-medium text-gray-900 dark:text-white">{log.message}</h3>
{log.details && renderNotificationDetails(log.details as NotificationDetails)}
<p className="text-xs text-gray-500 dark:text-gray-400">
Category: {log.category}
{log.subCategory ? ` > ${log.subCategory}` : ''}
</p>
</div>
</div>
<time className="shrink-0 text-xs text-gray-500 dark:text-gray-400">
{formatDistanceToNow(new Date(log.timestamp), { addSuffix: true })}
</time>
</div>
</motion.div>
);
})
)}
</div>
</div>
);
};
export default NotificationsTab;

View File

@@ -0,0 +1,181 @@
import { useState, useCallback } from 'react';
import { useStore } from '@nanostores/react';
import { classNames } from '~/utils/classNames';
import { profileStore, updateProfile } from '~/lib/stores/profile';
import { toast } from 'react-toastify';
import { debounce } from '~/utils/debounce';
export default function ProfileTab() {
const profile = useStore(profileStore);
const [isUploading, setIsUploading] = useState(false);
// Create debounced update functions
const debouncedUpdate = useCallback(
debounce((field: 'username' | 'bio', value: string) => {
updateProfile({ [field]: value });
toast.success(`${field.charAt(0).toUpperCase() + field.slice(1)} updated`);
}, 1000),
[],
);
const handleAvatarUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0];
if (!file) {
return;
}
try {
setIsUploading(true);
// Convert the file to base64
const reader = new FileReader();
reader.onloadend = () => {
const base64String = reader.result as string;
updateProfile({ avatar: base64String });
setIsUploading(false);
toast.success('Profile picture updated');
};
reader.onerror = () => {
console.error('Error reading file:', reader.error);
setIsUploading(false);
toast.error('Failed to update profile picture');
};
reader.readAsDataURL(file);
} catch (error) {
console.error('Error uploading avatar:', error);
setIsUploading(false);
toast.error('Failed to update profile picture');
}
};
const handleProfileUpdate = (field: 'username' | 'bio', value: string) => {
// Update the store immediately for UI responsiveness
updateProfile({ [field]: value });
// Debounce the toast notification
debouncedUpdate(field, value);
};
return (
<div className="max-w-2xl mx-auto">
<div className="space-y-6">
{/* Personal Information Section */}
<div>
{/* Avatar Upload */}
<div className="flex items-start gap-6 mb-8">
<div
className={classNames(
'w-24 h-24 rounded-full overflow-hidden',
'bg-gray-100 dark:bg-gray-800/50',
'flex items-center justify-center',
'ring-1 ring-gray-200 dark:ring-gray-700',
'relative group',
'transition-all duration-300 ease-out',
'hover:ring-purple-500/30 dark:hover:ring-purple-500/30',
'hover:shadow-lg hover:shadow-purple-500/10',
)}
>
{profile.avatar ? (
<img
src={profile.avatar}
alt="Profile"
className={classNames(
'w-full h-full object-cover',
'transition-all duration-300 ease-out',
'group-hover:scale-105 group-hover:brightness-90',
)}
/>
) : (
<div className="i-ph:robot-fill w-16 h-16 text-gray-400 dark:text-gray-500 transition-colors group-hover:text-purple-500/70 transform -translate-y-1" />
)}
<label
className={classNames(
'absolute inset-0',
'flex items-center justify-center',
'bg-black/0 group-hover:bg-black/40',
'cursor-pointer transition-all duration-300 ease-out',
isUploading ? 'cursor-wait' : '',
)}
>
<input
type="file"
accept="image/*"
className="hidden"
onChange={handleAvatarUpload}
disabled={isUploading}
/>
{isUploading ? (
<div className="i-ph:spinner-gap w-6 h-6 text-white animate-spin" />
) : (
<div className="i-ph:camera-plus w-6 h-6 text-white opacity-0 group-hover:opacity-100 transition-all duration-300 ease-out transform group-hover:scale-110" />
)}
</label>
</div>
<div className="flex-1 pt-1">
<label className="block text-base font-medium text-gray-900 dark:text-gray-100 mb-1">
Profile Picture
</label>
<p className="text-sm text-gray-500 dark:text-gray-400">Upload a profile picture or avatar</p>
</div>
</div>
{/* Username Input */}
<div className="mb-6">
<label className="block text-sm font-medium text-gray-900 dark:text-gray-100 mb-2">Username</label>
<div className="relative group">
<div className="absolute left-3.5 top-1/2 -translate-y-1/2">
<div className="i-ph:user-circle-fill w-5 h-5 text-gray-400 dark:text-gray-500 transition-colors group-focus-within:text-purple-500" />
</div>
<input
type="text"
value={profile.username}
onChange={(e) => handleProfileUpdate('username', e.target.value)}
className={classNames(
'w-full pl-11 pr-4 py-2.5 rounded-xl',
'bg-white dark:bg-gray-800/50',
'border border-gray-200 dark:border-gray-700/50',
'text-gray-900 dark:text-white',
'placeholder-gray-400 dark:placeholder-gray-500',
'focus:outline-none focus:ring-2 focus:ring-purple-500/50 focus:border-purple-500/50',
'transition-all duration-300 ease-out',
)}
placeholder="Enter your username"
/>
</div>
</div>
{/* Bio Input */}
<div className="mb-8">
<label className="block text-sm font-medium text-gray-900 dark:text-gray-100 mb-2">Bio</label>
<div className="relative group">
<div className="absolute left-3.5 top-3">
<div className="i-ph:text-aa w-5 h-5 text-gray-400 dark:text-gray-500 transition-colors group-focus-within:text-purple-500" />
</div>
<textarea
value={profile.bio}
onChange={(e) => handleProfileUpdate('bio', e.target.value)}
className={classNames(
'w-full pl-11 pr-4 py-2.5 rounded-xl',
'bg-white dark:bg-gray-800/50',
'border border-gray-200 dark:border-gray-700/50',
'text-gray-900 dark:text-white',
'placeholder-gray-400 dark:placeholder-gray-500',
'focus:outline-none focus:ring-2 focus:ring-purple-500/50 focus:border-purple-500/50',
'transition-all duration-300 ease-out',
'resize-none',
'h-32',
)}
placeholder="Tell us about yourself"
/>
</div>
</div>
</div>
</div>
</div>
);
}

View File

@@ -0,0 +1,305 @@
import React, { useEffect, useState, useCallback } from 'react';
import { Switch } from '~/components/ui/Switch';
import { useSettings } from '~/lib/hooks/useSettings';
import { URL_CONFIGURABLE_PROVIDERS } from '~/lib/stores/settings';
import type { IProviderConfig } from '~/types/model';
import { logStore } from '~/lib/stores/logs';
import { motion } from 'framer-motion';
import { classNames } from '~/utils/classNames';
import { toast } from 'react-toastify';
import { providerBaseUrlEnvKeys } from '~/utils/constants';
import { SiAmazon, SiGoogle, SiHuggingface, SiPerplexity, SiOpenai } from 'react-icons/si';
import { BsRobot, BsCloud } from 'react-icons/bs';
import { TbBrain, TbCloudComputing } from 'react-icons/tb';
import { BiCodeBlock, BiChip } from 'react-icons/bi';
import { FaCloud, FaBrain } from 'react-icons/fa';
import type { IconType } from 'react-icons';
// Add type for provider names to ensure type safety
type ProviderName =
| 'AmazonBedrock'
| 'Anthropic'
| 'Cohere'
| 'Deepseek'
| 'Google'
| 'Groq'
| 'HuggingFace'
| 'Hyperbolic'
| 'Mistral'
| 'OpenAI'
| 'OpenRouter'
| 'Perplexity'
| 'Together'
| 'XAI';
// Update the PROVIDER_ICONS type to use the ProviderName type
const PROVIDER_ICONS: Record<ProviderName, IconType> = {
AmazonBedrock: SiAmazon,
Anthropic: FaBrain,
Cohere: BiChip,
Deepseek: BiCodeBlock,
Google: SiGoogle,
Groq: BsCloud,
HuggingFace: SiHuggingface,
Hyperbolic: TbCloudComputing,
Mistral: TbBrain,
OpenAI: SiOpenai,
OpenRouter: FaCloud,
Perplexity: SiPerplexity,
Together: BsCloud,
XAI: BsRobot,
};
// Update PROVIDER_DESCRIPTIONS to use the same type
const PROVIDER_DESCRIPTIONS: Partial<Record<ProviderName, string>> = {
Anthropic: 'Access Claude and other Anthropic models',
OpenAI: 'Use GPT-4, GPT-3.5, and other OpenAI models',
};
const CloudProvidersTab = () => {
const settings = useSettings();
const [editingProvider, setEditingProvider] = useState<string | null>(null);
const [filteredProviders, setFilteredProviders] = useState<IProviderConfig[]>([]);
const [categoryEnabled, setCategoryEnabled] = useState<boolean>(false);
// Load and filter providers
useEffect(() => {
const newFilteredProviders = Object.entries(settings.providers || {})
.filter(([key]) => !['Ollama', 'LMStudio', 'OpenAILike'].includes(key))
.map(([key, value]) => ({
name: key,
settings: value.settings,
staticModels: value.staticModels || [],
getDynamicModels: value.getDynamicModels,
getApiKeyLink: value.getApiKeyLink,
labelForGetApiKey: value.labelForGetApiKey,
icon: value.icon,
}));
const sorted = newFilteredProviders.sort((a, b) => a.name.localeCompare(b.name));
setFilteredProviders(sorted);
// Update category enabled state
const allEnabled = newFilteredProviders.every((p) => p.settings.enabled);
setCategoryEnabled(allEnabled);
}, [settings.providers]);
const handleToggleCategory = useCallback(
(enabled: boolean) => {
// Update all providers
filteredProviders.forEach((provider) => {
settings.updateProviderSettings(provider.name, { ...provider.settings, enabled });
});
setCategoryEnabled(enabled);
toast.success(enabled ? 'All cloud providers enabled' : 'All cloud providers disabled');
},
[filteredProviders, settings],
);
const handleToggleProvider = useCallback(
(provider: IProviderConfig, enabled: boolean) => {
// Update the provider settings in the store
settings.updateProviderSettings(provider.name, { ...provider.settings, enabled });
if (enabled) {
logStore.logProvider(`Provider ${provider.name} enabled`, { provider: provider.name });
toast.success(`${provider.name} enabled`);
} else {
logStore.logProvider(`Provider ${provider.name} disabled`, { provider: provider.name });
toast.success(`${provider.name} disabled`);
}
},
[settings],
);
const handleUpdateBaseUrl = useCallback(
(provider: IProviderConfig, baseUrl: string) => {
const newBaseUrl: string | undefined = baseUrl.trim() || undefined;
// Update the provider settings in the store
settings.updateProviderSettings(provider.name, { ...provider.settings, baseUrl: newBaseUrl });
logStore.logProvider(`Base URL updated for ${provider.name}`, {
provider: provider.name,
baseUrl: newBaseUrl,
});
toast.success(`${provider.name} base URL updated`);
setEditingProvider(null);
},
[settings],
);
return (
<div className="space-y-6">
<motion.div
className="space-y-4"
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ duration: 0.3 }}
>
<div className="flex items-center justify-between gap-4 mt-8 mb-4">
<div className="flex items-center gap-2">
<div
className={classNames(
'w-8 h-8 flex items-center justify-center rounded-lg',
'bg-bolt-elements-background-depth-3',
'text-purple-500',
)}
>
<TbCloudComputing className="w-5 h-5" />
</div>
<div>
<h4 className="text-md font-medium text-bolt-elements-textPrimary">Cloud Providers</h4>
<p className="text-sm text-bolt-elements-textSecondary">Connect to cloud-based AI models and services</p>
</div>
</div>
<div className="flex items-center gap-2">
<span className="text-sm text-bolt-elements-textSecondary">Enable All Cloud</span>
<Switch checked={categoryEnabled} onCheckedChange={handleToggleCategory} />
</div>
</div>
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
{filteredProviders.map((provider, index) => (
<motion.div
key={provider.name}
className={classNames(
'rounded-lg border bg-bolt-elements-background text-bolt-elements-textPrimary shadow-sm',
'bg-bolt-elements-background-depth-2',
'hover:bg-bolt-elements-background-depth-3',
'transition-all duration-200',
'relative overflow-hidden group',
'flex flex-col',
)}
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ delay: index * 0.1 }}
whileHover={{ scale: 1.02 }}
>
<div className="absolute top-0 right-0 p-2 flex gap-1">
{URL_CONFIGURABLE_PROVIDERS.includes(provider.name) && (
<motion.span
className="px-2 py-0.5 text-xs rounded-full bg-purple-500/10 text-purple-500 font-medium"
whileHover={{ scale: 1.05 }}
whileTap={{ scale: 0.95 }}
>
Configurable
</motion.span>
)}
</div>
<div className="flex items-start gap-4 p-4">
<motion.div
className={classNames(
'w-10 h-10 flex items-center justify-center rounded-xl',
'bg-bolt-elements-background-depth-3 group-hover:bg-bolt-elements-background-depth-4',
'transition-all duration-200',
provider.settings.enabled ? 'text-purple-500' : 'text-bolt-elements-textSecondary',
)}
whileHover={{ scale: 1.1 }}
whileTap={{ scale: 0.9 }}
>
<div className={classNames('w-6 h-6', 'transition-transform duration-200', 'group-hover:rotate-12')}>
{React.createElement(PROVIDER_ICONS[provider.name as ProviderName] || BsRobot, {
className: 'w-full h-full',
'aria-label': `${provider.name} logo`,
})}
</div>
</motion.div>
<div className="flex-1 min-w-0">
<div className="flex items-center justify-between gap-4 mb-2">
<div>
<h4 className="text-sm font-medium text-bolt-elements-textPrimary group-hover:text-purple-500 transition-colors">
{provider.name}
</h4>
<p className="text-xs text-bolt-elements-textSecondary mt-0.5">
{PROVIDER_DESCRIPTIONS[provider.name as keyof typeof PROVIDER_DESCRIPTIONS] ||
(URL_CONFIGURABLE_PROVIDERS.includes(provider.name)
? 'Configure custom endpoint for this provider'
: 'Standard AI provider integration')}
</p>
</div>
<Switch
checked={provider.settings.enabled}
onCheckedChange={(checked) => handleToggleProvider(provider, checked)}
/>
</div>
{provider.settings.enabled && URL_CONFIGURABLE_PROVIDERS.includes(provider.name) && (
<motion.div
initial={{ opacity: 0, height: 0 }}
animate={{ opacity: 1, height: 'auto' }}
exit={{ opacity: 0, height: 0 }}
transition={{ duration: 0.2 }}
>
<div className="flex items-center gap-2 mt-4">
{editingProvider === provider.name ? (
<input
type="text"
defaultValue={provider.settings.baseUrl}
placeholder={`Enter ${provider.name} base URL`}
className={classNames(
'flex-1 px-3 py-1.5 rounded-lg text-sm',
'bg-bolt-elements-background-depth-3 border border-bolt-elements-borderColor',
'text-bolt-elements-textPrimary placeholder-bolt-elements-textTertiary',
'focus:outline-none focus:ring-2 focus:ring-purple-500/30',
'transition-all duration-200',
)}
onKeyDown={(e) => {
if (e.key === 'Enter') {
handleUpdateBaseUrl(provider, e.currentTarget.value);
} else if (e.key === 'Escape') {
setEditingProvider(null);
}
}}
onBlur={(e) => handleUpdateBaseUrl(provider, e.target.value)}
autoFocus
/>
) : (
<div
className="flex-1 px-3 py-1.5 rounded-lg text-sm cursor-pointer group/url"
onClick={() => setEditingProvider(provider.name)}
>
<div className="flex items-center gap-2 text-bolt-elements-textSecondary">
<div className="i-ph:link text-sm" />
<span className="group-hover/url:text-purple-500 transition-colors">
{provider.settings.baseUrl || 'Click to set base URL'}
</span>
</div>
</div>
)}
</div>
{providerBaseUrlEnvKeys[provider.name]?.baseUrlKey && (
<div className="mt-2 text-xs text-green-500">
<div className="flex items-center gap-1">
<div className="i-ph:info" />
<span>Environment URL set in .env file</span>
</div>
</div>
)}
</motion.div>
)}
</div>
</div>
<motion.div
className="absolute inset-0 border-2 border-purple-500/0 rounded-lg pointer-events-none"
animate={{
borderColor: provider.settings.enabled ? 'rgba(168, 85, 247, 0.2)' : 'rgba(168, 85, 247, 0)',
scale: provider.settings.enabled ? 1 : 0.98,
}}
transition={{ duration: 0.2 }}
/>
</motion.div>
))}
</div>
</motion.div>
</div>
);
};
export default CloudProvidersTab;

View File

@@ -0,0 +1,777 @@
import React, { useEffect, useState, useCallback } from 'react';
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 { motion, AnimatePresence } from 'framer-motion';
import { classNames } from '~/utils/classNames';
import { BsRobot } from 'react-icons/bs';
import type { IconType } from 'react-icons';
import { BiChip } from 'react-icons/bi';
import { TbBrandOpenai } from 'react-icons/tb';
import { providerBaseUrlEnvKeys } from '~/utils/constants';
import { useToast } from '~/components/ui/use-toast';
import { Progress } from '~/components/ui/Progress';
import OllamaModelInstaller from './OllamaModelInstaller';
// Add type for provider names to ensure type safety
type ProviderName = 'Ollama' | 'LMStudio' | 'OpenAILike';
// Update the PROVIDER_ICONS type to use the ProviderName type
const PROVIDER_ICONS: Record<ProviderName, IconType> = {
Ollama: BsRobot,
LMStudio: BsRobot,
OpenAILike: TbBrandOpenai,
};
// Update PROVIDER_DESCRIPTIONS to use the same type
const PROVIDER_DESCRIPTIONS: Record<ProviderName, string> = {
Ollama: 'Run open-source models locally on your machine',
LMStudio: 'Local model inference with LM Studio',
OpenAILike: 'Connect to OpenAI-compatible API endpoints',
};
// Add a constant for the Ollama API base URL
const OLLAMA_API_URL = 'http://127.0.0.1:11434';
interface OllamaModel {
name: string;
digest: string;
size: number;
modified_at: string;
details?: {
family: string;
parameter_size: string;
quantization_level: string;
};
status?: 'idle' | 'updating' | 'updated' | 'error' | 'checking';
error?: string;
newDigest?: string;
progress?: {
current: number;
total: number;
status: string;
};
}
interface OllamaPullResponse {
status: string;
completed?: number;
total?: number;
digest?: string;
}
const isOllamaPullResponse = (data: unknown): data is OllamaPullResponse => {
return (
typeof data === 'object' &&
data !== null &&
'status' in data &&
typeof (data as OllamaPullResponse).status === 'string'
);
};
export default function LocalProvidersTab() {
const { providers, updateProviderSettings } = useSettings();
const [filteredProviders, setFilteredProviders] = useState<IProviderConfig[]>([]);
const [categoryEnabled, setCategoryEnabled] = useState(false);
const [ollamaModels, setOllamaModels] = useState<OllamaModel[]>([]);
const [isLoadingModels, setIsLoadingModels] = useState(false);
const [editingProvider, setEditingProvider] = useState<string | null>(null);
const { toast } = useToast();
// Effect to filter and sort providers
useEffect(() => {
const newFilteredProviders = Object.entries(providers || {})
.filter(([key]) => [...LOCAL_PROVIDERS, 'OpenAILike'].includes(key))
.map(([key, value]) => {
const provider = value as IProviderConfig;
const envKey = providerBaseUrlEnvKeys[key]?.baseUrlKey;
const envUrl = envKey ? (import.meta.env[envKey] as string | undefined) : undefined;
// Set base URL if provided by environment
if (envUrl && !provider.settings.baseUrl) {
updateProviderSettings(key, {
...provider.settings,
baseUrl: envUrl,
});
}
return {
name: key,
settings: {
...provider.settings,
baseUrl: provider.settings.baseUrl || envUrl,
},
staticModels: provider.staticModels || [],
getDynamicModels: provider.getDynamicModels,
getApiKeyLink: provider.getApiKeyLink,
labelForGetApiKey: provider.labelForGetApiKey,
icon: provider.icon,
} as IProviderConfig;
});
// Custom sort function to ensure LMStudio appears before OpenAILike
const sorted = newFilteredProviders.sort((a, b) => {
if (a.name === 'LMStudio') {
return -1;
}
if (b.name === 'LMStudio') {
return 1;
}
if (a.name === 'OpenAILike') {
return 1;
}
if (b.name === 'OpenAILike') {
return -1;
}
return a.name.localeCompare(b.name);
});
setFilteredProviders(sorted);
}, [providers, updateProviderSettings]);
// Add effect to update category toggle state based on provider states
useEffect(() => {
const newCategoryState = filteredProviders.every((p) => p.settings.enabled);
setCategoryEnabled(newCategoryState);
}, [filteredProviders]);
// Fetch Ollama models when enabled
useEffect(() => {
const ollamaProvider = filteredProviders.find((p) => p.name === 'Ollama');
if (ollamaProvider?.settings.enabled) {
fetchOllamaModels();
}
}, [filteredProviders]);
const fetchOllamaModels = async () => {
try {
setIsLoadingModels(true);
const response = await fetch('http://127.0.0.1:11434/api/tags');
const data = (await response.json()) as { models: OllamaModel[] };
setOllamaModels(
data.models.map((model) => ({
...model,
status: 'idle' as const,
})),
);
} catch (error) {
console.error('Error fetching Ollama models:', error);
} finally {
setIsLoadingModels(false);
}
};
const updateOllamaModel = async (modelName: string): Promise<boolean> => {
try {
const response = await fetch(`${OLLAMA_API_URL}/api/pull`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name: modelName }),
});
if (!response.ok) {
throw new Error(`Failed to update ${modelName}`);
}
const reader = response.body?.getReader();
if (!reader) {
throw new Error('No response reader available');
}
while (true) {
const { done, value } = await reader.read();
if (done) {
break;
}
const text = new TextDecoder().decode(value);
const lines = text.split('\n').filter(Boolean);
for (const line of lines) {
const rawData = JSON.parse(line);
if (!isOllamaPullResponse(rawData)) {
console.error('Invalid response format:', rawData);
continue;
}
setOllamaModels((current) =>
current.map((m) =>
m.name === modelName
? {
...m,
progress: {
current: rawData.completed || 0,
total: rawData.total || 0,
status: rawData.status,
},
newDigest: rawData.digest,
}
: m,
),
);
}
}
const updatedResponse = await fetch('http://127.0.0.1:11434/api/tags');
const updatedData = (await updatedResponse.json()) as { models: OllamaModel[] };
const updatedModel = updatedData.models.find((m) => m.name === modelName);
return updatedModel !== undefined;
} catch (error) {
console.error(`Error updating ${modelName}:`, error);
return false;
}
};
const handleToggleCategory = useCallback(
async (enabled: boolean) => {
filteredProviders.forEach((provider) => {
updateProviderSettings(provider.name, { ...provider.settings, enabled });
});
toast(enabled ? 'All local providers enabled' : 'All local providers disabled');
},
[filteredProviders, updateProviderSettings],
);
const handleToggleProvider = (provider: IProviderConfig, enabled: boolean) => {
updateProviderSettings(provider.name, {
...provider.settings,
enabled,
});
if (enabled) {
logStore.logProvider(`Provider ${provider.name} enabled`, { provider: provider.name });
toast(`${provider.name} enabled`);
} else {
logStore.logProvider(`Provider ${provider.name} disabled`, { provider: provider.name });
toast(`${provider.name} disabled`);
}
};
const handleUpdateBaseUrl = (provider: IProviderConfig, newBaseUrl: string) => {
updateProviderSettings(provider.name, {
...provider.settings,
baseUrl: newBaseUrl,
});
toast(`${provider.name} base URL updated`);
setEditingProvider(null);
};
const handleUpdateOllamaModel = async (modelName: string) => {
const updateSuccess = await updateOllamaModel(modelName);
if (updateSuccess) {
toast(`Updated ${modelName}`);
} else {
toast(`Failed to update ${modelName}`);
}
};
const handleDeleteOllamaModel = async (modelName: string) => {
try {
const response = await fetch(`${OLLAMA_API_URL}/api/delete`, {
method: 'DELETE',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ name: modelName }),
});
if (!response.ok) {
throw new Error(`Failed to delete ${modelName}`);
}
setOllamaModels((current) => current.filter((m) => m.name !== modelName));
toast(`Deleted ${modelName}`);
} catch (err) {
const errorMessage = err instanceof Error ? err.message : 'Unknown error occurred';
console.error(`Error deleting ${modelName}:`, errorMessage);
toast(`Failed to delete ${modelName}`);
}
};
// Update model details display
const ModelDetails = ({ model }: { model: OllamaModel }) => (
<div className="flex items-center gap-3 text-xs text-bolt-elements-textSecondary">
<div className="flex items-center gap-1">
<div className="i-ph:code text-purple-500" />
<span>{model.digest.substring(0, 7)}</span>
</div>
{model.details && (
<>
<div className="flex items-center gap-1">
<div className="i-ph:database text-purple-500" />
<span>{model.details.parameter_size}</span>
</div>
<div className="flex items-center gap-1">
<div className="i-ph:cube text-purple-500" />
<span>{model.details.quantization_level}</span>
</div>
</>
)}
</div>
);
// Update model actions to not use Tooltip
const ModelActions = ({
model,
onUpdate,
onDelete,
}: {
model: OllamaModel;
onUpdate: () => void;
onDelete: () => void;
}) => (
<div className="flex items-center gap-2">
<motion.button
onClick={onUpdate}
disabled={model.status === 'updating'}
className={classNames(
'rounded-lg p-2',
'bg-purple-500/10 text-purple-500',
'hover:bg-purple-500/20',
'transition-all duration-200',
{ 'opacity-50 cursor-not-allowed': model.status === 'updating' },
)}
whileHover={{ scale: 1.05 }}
whileTap={{ scale: 0.95 }}
title="Update model"
>
{model.status === 'updating' ? (
<div className="flex items-center gap-2">
<div className="i-ph:spinner-gap-bold animate-spin w-4 h-4" />
<span className="text-sm">Updating...</span>
</div>
) : (
<div className="i-ph:arrows-clockwise text-lg" />
)}
</motion.button>
<motion.button
onClick={onDelete}
disabled={model.status === 'updating'}
className={classNames(
'rounded-lg p-2',
'bg-red-500/10 text-red-500',
'hover:bg-red-500/20',
'transition-all duration-200',
{ 'opacity-50 cursor-not-allowed': model.status === 'updating' },
)}
whileHover={{ scale: 1.05 }}
whileTap={{ scale: 0.95 }}
title="Delete model"
>
<div className="i-ph:trash text-lg" />
</motion.button>
</div>
);
return (
<div
className={classNames(
'rounded-lg bg-bolt-elements-background text-bolt-elements-textPrimary shadow-sm p-4',
'hover:bg-bolt-elements-background-depth-2',
'transition-all duration-200',
)}
role="region"
aria-label="Local Providers Configuration"
>
<motion.div
className="space-y-6"
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ duration: 0.3 }}
>
{/* Header section */}
<div className="flex items-center justify-between gap-4 border-b border-bolt-elements-borderColor pb-4">
<div className="flex items-center gap-3">
<motion.div
className={classNames(
'w-10 h-10 flex items-center justify-center rounded-xl',
'bg-purple-500/10 text-purple-500',
)}
whileHover={{ scale: 1.05 }}
>
<BiChip className="w-6 h-6" />
</motion.div>
<div>
<div className="flex items-center gap-2">
<h2 className="text-lg font-semibold text-bolt-elements-textPrimary">Local AI Models</h2>
</div>
<p className="text-sm text-bolt-elements-textSecondary">Configure and manage your local AI providers</p>
</div>
</div>
<div className="flex items-center gap-2">
<span className="text-sm text-bolt-elements-textSecondary">Enable All</span>
<Switch
checked={categoryEnabled}
onCheckedChange={handleToggleCategory}
aria-label="Toggle all local providers"
/>
</div>
</div>
{/* Ollama Section */}
{filteredProviders
.filter((provider) => provider.name === 'Ollama')
.map((provider) => (
<motion.div
key={provider.name}
className={classNames(
'bg-bolt-elements-background-depth-2 rounded-xl',
'hover:bg-bolt-elements-background-depth-3',
'transition-all duration-200 p-5',
'relative overflow-hidden group',
)}
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
whileHover={{ scale: 1.01 }}
>
{/* Provider Header */}
<div className="flex items-start justify-between gap-4">
<div className="flex items-start gap-4">
<motion.div
className={classNames(
'w-12 h-12 flex items-center justify-center rounded-xl',
'bg-bolt-elements-background-depth-3',
provider.settings.enabled ? 'text-purple-500' : 'text-bolt-elements-textSecondary',
)}
whileHover={{ scale: 1.1, rotate: 5 }}
>
{React.createElement(PROVIDER_ICONS[provider.name as ProviderName] || BsRobot, {
className: 'w-7 h-7',
'aria-label': `${provider.name} icon`,
})}
</motion.div>
<div>
<div className="flex items-center gap-2">
<h3 className="text-md font-semibold text-bolt-elements-textPrimary">{provider.name}</h3>
<span className="px-2 py-0.5 text-xs rounded-full bg-green-500/10 text-green-500">Local</span>
</div>
<p className="text-sm text-bolt-elements-textSecondary mt-1">
{PROVIDER_DESCRIPTIONS[provider.name as ProviderName]}
</p>
</div>
</div>
<Switch
checked={provider.settings.enabled}
onCheckedChange={(checked) => handleToggleProvider(provider, checked)}
aria-label={`Toggle ${provider.name} provider`}
/>
</div>
{/* URL Configuration Section */}
<AnimatePresence>
{provider.settings.enabled && (
<motion.div
initial={{ opacity: 0, height: 0 }}
animate={{ opacity: 1, height: 'auto' }}
exit={{ opacity: 0, height: 0 }}
className="mt-4"
>
<div className="flex flex-col gap-2">
<label className="text-sm text-bolt-elements-textSecondary">API Endpoint</label>
{editingProvider === provider.name ? (
<input
type="text"
defaultValue={provider.settings.baseUrl || OLLAMA_API_URL}
placeholder="Enter Ollama base URL"
className={classNames(
'w-full px-3 py-2 rounded-lg text-sm',
'bg-bolt-elements-background-depth-3 border border-bolt-elements-borderColor',
'text-bolt-elements-textPrimary placeholder-bolt-elements-textTertiary',
'focus:outline-none focus:ring-2 focus:ring-purple-500/30',
'transition-all duration-200',
)}
onKeyDown={(e) => {
if (e.key === 'Enter') {
handleUpdateBaseUrl(provider, e.currentTarget.value);
} else if (e.key === 'Escape') {
setEditingProvider(null);
}
}}
onBlur={(e) => handleUpdateBaseUrl(provider, e.target.value)}
autoFocus
/>
) : (
<div
onClick={() => setEditingProvider(provider.name)}
className={classNames(
'w-full px-3 py-2 rounded-lg text-sm cursor-pointer',
'bg-bolt-elements-background-depth-3 border border-bolt-elements-borderColor',
'hover:border-purple-500/30 hover:bg-bolt-elements-background-depth-4',
'transition-all duration-200',
)}
>
<div className="flex items-center gap-2 text-bolt-elements-textSecondary">
<div className="i-ph:link text-sm" />
<span>{provider.settings.baseUrl || OLLAMA_API_URL}</span>
</div>
</div>
)}
</div>
</motion.div>
)}
</AnimatePresence>
{/* Ollama Models Section */}
{provider.settings.enabled && (
<motion.div initial={{ opacity: 0 }} animate={{ opacity: 1 }} className="mt-6 space-y-4">
<div className="flex items-center justify-between">
<div className="flex items-center gap-2">
<div className="i-ph:cube-duotone text-purple-500" />
<h4 className="text-sm font-medium text-bolt-elements-textPrimary">Installed Models</h4>
</div>
{isLoadingModels ? (
<div className="flex items-center gap-2">
<div className="i-ph:spinner-gap-bold animate-spin w-4 h-4" />
<span className="text-sm text-bolt-elements-textSecondary">Loading models...</span>
</div>
) : (
<span className="text-sm text-bolt-elements-textSecondary">
{ollamaModels.length} models available
</span>
)}
</div>
<div className="space-y-3">
{isLoadingModels ? (
<div className="space-y-3">
{Array.from({ length: 3 }).map((_, i) => (
<div
key={i}
className="h-20 w-full bg-bolt-elements-background-depth-3 rounded-lg animate-pulse"
/>
))}
</div>
) : ollamaModels.length === 0 ? (
<div className="text-center py-8 text-bolt-elements-textSecondary">
<div className="i-ph:cube-transparent text-4xl mx-auto mb-2" />
<p>No models installed yet</p>
<p className="text-sm text-bolt-elements-textTertiary px-1">
Browse models at{' '}
<a
href="https://ollama.com/library"
target="_blank"
rel="noopener noreferrer"
className="text-purple-500 hover:underline inline-flex items-center gap-0.5 text-base font-medium"
>
ollama.com/library
<div className="i-ph:arrow-square-out text-xs" />
</a>{' '}
and copy model names to install
</p>
</div>
) : (
ollamaModels.map((model) => (
<motion.div
key={model.name}
className={classNames(
'p-4 rounded-xl',
'bg-bolt-elements-background-depth-3',
'hover:bg-bolt-elements-background-depth-4',
'transition-all duration-200',
)}
whileHover={{ scale: 1.01 }}
>
<div className="flex items-center justify-between">
<div className="space-y-2">
<div className="flex items-center gap-2">
<h5 className="text-sm font-medium text-bolt-elements-textPrimary">{model.name}</h5>
<ModelStatusBadge status={model.status} />
</div>
<ModelDetails model={model} />
</div>
<ModelActions
model={model}
onUpdate={() => handleUpdateOllamaModel(model.name)}
onDelete={() => {
if (window.confirm(`Are you sure you want to delete ${model.name}?`)) {
handleDeleteOllamaModel(model.name);
}
}}
/>
</div>
{model.progress && (
<div className="mt-3">
<Progress
value={Math.round((model.progress.current / model.progress.total) * 100)}
className="h-1"
/>
<div className="flex justify-between mt-1 text-xs text-bolt-elements-textSecondary">
<span>{model.progress.status}</span>
<span>{Math.round((model.progress.current / model.progress.total) * 100)}%</span>
</div>
</div>
)}
</motion.div>
))
)}
</div>
{/* Model Installation Section */}
<OllamaModelInstaller onModelInstalled={fetchOllamaModels} />
</motion.div>
)}
</motion.div>
))}
{/* Other Providers Section */}
<div className="border-t border-bolt-elements-borderColor pt-6 mt-8">
<h3 className="text-lg font-semibold text-bolt-elements-textPrimary mb-4">Other Local Providers</h3>
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
{filteredProviders
.filter((provider) => provider.name !== 'Ollama')
.map((provider, index) => (
<motion.div
key={provider.name}
className={classNames(
'bg-bolt-elements-background-depth-2 rounded-xl',
'hover:bg-bolt-elements-background-depth-3',
'transition-all duration-200 p-5',
'relative overflow-hidden group',
)}
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ delay: index * 0.1 }}
whileHover={{ scale: 1.01 }}
>
{/* Provider Header */}
<div className="flex items-start justify-between gap-4">
<div className="flex items-start gap-4">
<motion.div
className={classNames(
'w-12 h-12 flex items-center justify-center rounded-xl',
'bg-bolt-elements-background-depth-3',
provider.settings.enabled ? 'text-purple-500' : 'text-bolt-elements-textSecondary',
)}
whileHover={{ scale: 1.1, rotate: 5 }}
>
{React.createElement(PROVIDER_ICONS[provider.name as ProviderName] || BsRobot, {
className: 'w-7 h-7',
'aria-label': `${provider.name} icon`,
})}
</motion.div>
<div>
<div className="flex items-center gap-2">
<h3 className="text-md font-semibold text-bolt-elements-textPrimary">{provider.name}</h3>
<div className="flex gap-1">
<span className="px-2 py-0.5 text-xs rounded-full bg-green-500/10 text-green-500">
Local
</span>
{URL_CONFIGURABLE_PROVIDERS.includes(provider.name) && (
<span className="px-2 py-0.5 text-xs rounded-full bg-purple-500/10 text-purple-500">
Configurable
</span>
)}
</div>
</div>
<p className="text-sm text-bolt-elements-textSecondary mt-1">
{PROVIDER_DESCRIPTIONS[provider.name as ProviderName]}
</p>
</div>
</div>
<Switch
checked={provider.settings.enabled}
onCheckedChange={(checked) => handleToggleProvider(provider, checked)}
aria-label={`Toggle ${provider.name} provider`}
/>
</div>
{/* URL Configuration Section */}
<AnimatePresence>
{provider.settings.enabled && URL_CONFIGURABLE_PROVIDERS.includes(provider.name) && (
<motion.div
initial={{ opacity: 0, height: 0 }}
animate={{ opacity: 1, height: 'auto' }}
exit={{ opacity: 0, height: 0 }}
className="mt-4"
>
<div className="flex flex-col gap-2">
<label className="text-sm text-bolt-elements-textSecondary">API Endpoint</label>
{editingProvider === provider.name ? (
<input
type="text"
defaultValue={provider.settings.baseUrl}
placeholder={`Enter ${provider.name} base URL`}
className={classNames(
'w-full px-3 py-2 rounded-lg text-sm',
'bg-bolt-elements-background-depth-3 border border-bolt-elements-borderColor',
'text-bolt-elements-textPrimary placeholder-bolt-elements-textTertiary',
'focus:outline-none focus:ring-2 focus:ring-purple-500/30',
'transition-all duration-200',
)}
onKeyDown={(e) => {
if (e.key === 'Enter') {
handleUpdateBaseUrl(provider, e.currentTarget.value);
} else if (e.key === 'Escape') {
setEditingProvider(null);
}
}}
onBlur={(e) => handleUpdateBaseUrl(provider, e.target.value)}
autoFocus
/>
) : (
<div
onClick={() => setEditingProvider(provider.name)}
className={classNames(
'w-full px-3 py-2 rounded-lg text-sm cursor-pointer',
'bg-bolt-elements-background-depth-3 border border-bolt-elements-borderColor',
'hover:border-purple-500/30 hover:bg-bolt-elements-background-depth-4',
'transition-all duration-200',
)}
>
<div className="flex items-center gap-2 text-bolt-elements-textSecondary">
<div className="i-ph:link text-sm" />
<span>{provider.settings.baseUrl || 'Click to set base URL'}</span>
</div>
</div>
)}
</div>
</motion.div>
)}
</AnimatePresence>
</motion.div>
))}
</div>
</div>
</motion.div>
</div>
);
}
// Helper component for model status badge
function ModelStatusBadge({ status }: { status?: string }) {
if (!status || status === 'idle') {
return null;
}
const statusConfig = {
updating: { bg: 'bg-yellow-500/10', text: 'text-yellow-500', label: 'Updating' },
updated: { bg: 'bg-green-500/10', text: 'text-green-500', label: 'Updated' },
error: { bg: 'bg-red-500/10', text: 'text-red-500', label: 'Error' },
};
const config = statusConfig[status as keyof typeof statusConfig];
if (!config) {
return null;
}
return (
<span className={classNames('px-2 py-0.5 rounded-full text-xs font-medium', config.bg, config.text)}>
{config.label}
</span>
);
}

View File

@@ -0,0 +1,603 @@
import React, { useState, useEffect } from 'react';
import { motion } from 'framer-motion';
import { classNames } from '~/utils/classNames';
import { Progress } from '~/components/ui/Progress';
import { useToast } from '~/components/ui/use-toast';
import { useSettings } from '~/lib/hooks/useSettings';
interface OllamaModelInstallerProps {
onModelInstalled: () => void;
}
interface InstallProgress {
status: string;
progress: number;
downloadedSize?: string;
totalSize?: string;
speed?: string;
}
interface ModelInfo {
name: string;
desc: string;
size: string;
tags: string[];
installedVersion?: string;
latestVersion?: string;
needsUpdate?: boolean;
status?: 'idle' | 'installing' | 'updating' | 'updated' | 'error';
details?: {
family: string;
parameter_size: string;
quantization_level: string;
};
}
const POPULAR_MODELS: ModelInfo[] = [
{
name: 'deepseek-coder:6.7b',
desc: "DeepSeek's code generation model",
size: '4.1GB',
tags: ['coding', 'popular'],
},
{
name: 'llama2:7b',
desc: "Meta's Llama 2 (7B parameters)",
size: '3.8GB',
tags: ['general', 'popular'],
},
{
name: 'mistral:7b',
desc: "Mistral's 7B model",
size: '4.1GB',
tags: ['general', 'popular'],
},
{
name: 'gemma:7b',
desc: "Google's Gemma model",
size: '4.0GB',
tags: ['general', 'new'],
},
{
name: 'codellama:7b',
desc: "Meta's Code Llama model",
size: '4.1GB',
tags: ['coding', 'popular'],
},
{
name: 'neural-chat:7b',
desc: "Intel's Neural Chat model",
size: '4.1GB',
tags: ['chat', 'popular'],
},
{
name: 'phi:latest',
desc: "Microsoft's Phi-2 model",
size: '2.7GB',
tags: ['small', 'fast'],
},
{
name: 'qwen:7b',
desc: "Alibaba's Qwen model",
size: '4.1GB',
tags: ['general'],
},
{
name: 'solar:10.7b',
desc: "Upstage's Solar model",
size: '6.1GB',
tags: ['large', 'powerful'],
},
{
name: 'openchat:7b',
desc: 'Open-source chat model',
size: '4.1GB',
tags: ['chat', 'popular'],
},
{
name: 'dolphin-phi:2.7b',
desc: 'Lightweight chat model',
size: '1.6GB',
tags: ['small', 'fast'],
},
{
name: 'stable-code:3b',
desc: 'Lightweight coding model',
size: '1.8GB',
tags: ['coding', 'small'],
},
];
function formatBytes(bytes: number): string {
if (bytes === 0) {
return '0 B';
}
const k = 1024;
const sizes = ['B', 'KB', 'MB', 'GB'];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return `${parseFloat((bytes / Math.pow(k, i)).toFixed(1))} ${sizes[i]}`;
}
function formatSpeed(bytesPerSecond: number): string {
return `${formatBytes(bytesPerSecond)}/s`;
}
// Add Ollama Icon SVG component
function OllamaIcon({ className }: { className?: string }) {
return (
<svg viewBox="0 0 1024 1024" className={className} fill="currentColor">
<path d="M684.3 322.2H339.8c-9.5.1-17.7 6.8-19.6 16.1-8.2 41.4-12.4 83.5-12.4 125.7 0 42.2 4.2 84.3 12.4 125.7 1.9 9.3 10.1 16 19.6 16.1h344.5c9.5-.1 17.7-6.8 19.6-16.1 8.2-41.4 12.4-83.5 12.4-125.7 0-42.2-4.2-84.3-12.4-125.7-1.9-9.3-10.1-16-19.6-16.1zM512 640c-176.7 0-320-143.3-320-320S335.3 0 512 0s320 143.3 320 320-143.3 320-320 320z" />
</svg>
);
}
export default function OllamaModelInstaller({ onModelInstalled }: OllamaModelInstallerProps) {
const [modelString, setModelString] = useState('');
const [searchQuery, setSearchQuery] = useState('');
const [isInstalling, setIsInstalling] = useState(false);
const [isChecking, setIsChecking] = useState(false);
const [installProgress, setInstallProgress] = useState<InstallProgress | null>(null);
const [selectedTags, setSelectedTags] = useState<string[]>([]);
const [models, setModels] = useState<ModelInfo[]>(POPULAR_MODELS);
const { toast } = useToast();
const { providers } = useSettings();
// Get base URL from provider settings
const baseUrl = providers?.Ollama?.settings?.baseUrl || 'http://127.0.0.1:11434';
// Function to check installed models and their versions
const checkInstalledModels = async () => {
try {
const response = await fetch(`${baseUrl}/api/tags`, {
method: 'GET',
});
if (!response.ok) {
throw new Error('Failed to fetch installed models');
}
const data = (await response.json()) as { models: Array<{ name: string; digest: string; latest: string }> };
const installedModels = data.models || [];
// Update models with installed versions
setModels((prevModels) =>
prevModels.map((model) => {
const installed = installedModels.find((m) => m.name.toLowerCase() === model.name.toLowerCase());
if (installed) {
return {
...model,
installedVersion: installed.digest.substring(0, 8),
needsUpdate: installed.digest !== installed.latest,
latestVersion: installed.latest?.substring(0, 8),
};
}
return model;
}),
);
} catch (error) {
console.error('Error checking installed models:', error);
}
};
// Check installed models on mount and after installation
useEffect(() => {
checkInstalledModels();
}, [baseUrl]);
const handleCheckUpdates = async () => {
setIsChecking(true);
try {
await checkInstalledModels();
toast('Model versions checked');
} catch (err) {
console.error('Failed to check model versions:', err);
toast('Failed to check model versions');
} finally {
setIsChecking(false);
}
};
const filteredModels = models.filter((model) => {
const matchesSearch =
searchQuery === '' ||
model.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
model.desc.toLowerCase().includes(searchQuery.toLowerCase());
const matchesTags = selectedTags.length === 0 || selectedTags.some((tag) => model.tags.includes(tag));
return matchesSearch && matchesTags;
});
const handleInstallModel = async (modelToInstall: string) => {
if (!modelToInstall) {
return;
}
try {
setIsInstalling(true);
setInstallProgress({
status: 'Starting download...',
progress: 0,
downloadedSize: '0 B',
totalSize: 'Calculating...',
speed: '0 B/s',
});
setModelString('');
setSearchQuery('');
const response = await fetch(`${baseUrl}/api/pull`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ name: modelToInstall }),
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const reader = response.body?.getReader();
if (!reader) {
throw new Error('Failed to get response reader');
}
let lastTime = Date.now();
let lastBytes = 0;
while (true) {
const { done, value } = await reader.read();
if (done) {
break;
}
const text = new TextDecoder().decode(value);
const lines = text.split('\n').filter(Boolean);
for (const line of lines) {
try {
const data = JSON.parse(line);
if ('status' in data) {
const currentTime = Date.now();
const timeDiff = (currentTime - lastTime) / 1000; // Convert to seconds
const bytesDiff = (data.completed || 0) - lastBytes;
const speed = bytesDiff / timeDiff;
setInstallProgress({
status: data.status,
progress: data.completed && data.total ? (data.completed / data.total) * 100 : 0,
downloadedSize: formatBytes(data.completed || 0),
totalSize: data.total ? formatBytes(data.total) : 'Calculating...',
speed: formatSpeed(speed),
});
lastTime = currentTime;
lastBytes = data.completed || 0;
}
} catch (err) {
console.error('Error parsing progress:', err);
}
}
}
toast('Successfully installed ' + modelToInstall + '. The model list will refresh automatically.');
// Ensure we call onModelInstalled after successful installation
setTimeout(() => {
onModelInstalled();
}, 1000);
} catch (err) {
const errorMessage = err instanceof Error ? err.message : 'Unknown error occurred';
console.error(`Error installing ${modelToInstall}:`, errorMessage);
toast(`Failed to install ${modelToInstall}. ${errorMessage}`);
} finally {
setIsInstalling(false);
setInstallProgress(null);
}
};
const handleUpdateModel = async (modelToUpdate: string) => {
try {
setModels((prev) => prev.map((m) => (m.name === modelToUpdate ? { ...m, status: 'updating' } : m)));
const response = await fetch(`${baseUrl}/api/pull`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ name: modelToUpdate }),
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const reader = response.body?.getReader();
if (!reader) {
throw new Error('Failed to get response reader');
}
let lastTime = Date.now();
let lastBytes = 0;
while (true) {
const { done, value } = await reader.read();
if (done) {
break;
}
const text = new TextDecoder().decode(value);
const lines = text.split('\n').filter(Boolean);
for (const line of lines) {
try {
const data = JSON.parse(line);
if ('status' in data) {
const currentTime = Date.now();
const timeDiff = (currentTime - lastTime) / 1000;
const bytesDiff = (data.completed || 0) - lastBytes;
const speed = bytesDiff / timeDiff;
setInstallProgress({
status: data.status,
progress: data.completed && data.total ? (data.completed / data.total) * 100 : 0,
downloadedSize: formatBytes(data.completed || 0),
totalSize: data.total ? formatBytes(data.total) : 'Calculating...',
speed: formatSpeed(speed),
});
lastTime = currentTime;
lastBytes = data.completed || 0;
}
} catch (err) {
console.error('Error parsing progress:', err);
}
}
}
toast('Successfully updated ' + modelToUpdate);
// Refresh model list after update
await checkInstalledModels();
} catch (err) {
const errorMessage = err instanceof Error ? err.message : 'Unknown error occurred';
console.error(`Error updating ${modelToUpdate}:`, errorMessage);
toast(`Failed to update ${modelToUpdate}. ${errorMessage}`);
setModels((prev) => prev.map((m) => (m.name === modelToUpdate ? { ...m, status: 'error' } : m)));
} finally {
setInstallProgress(null);
}
};
const allTags = Array.from(new Set(POPULAR_MODELS.flatMap((model) => model.tags)));
return (
<div className="space-y-6">
<div className="flex items-center justify-between pt-6">
<div className="flex items-center gap-3">
<OllamaIcon className="w-8 h-8 text-purple-500" />
<div>
<h3 className="text-lg font-semibold text-bolt-elements-textPrimary">Ollama Models</h3>
<p className="text-sm text-bolt-elements-textSecondary mt-1">Install and manage your Ollama models</p>
</div>
</div>
<motion.button
onClick={handleCheckUpdates}
disabled={isChecking}
className={classNames(
'px-4 py-2 rounded-lg',
'bg-purple-500/10 text-purple-500',
'hover:bg-purple-500/20',
'transition-all duration-200',
'flex items-center gap-2',
)}
whileHover={{ scale: 1.02 }}
whileTap={{ scale: 0.98 }}
>
{isChecking ? (
<div className="i-ph:spinner-gap-bold animate-spin" />
) : (
<div className="i-ph:arrows-clockwise" />
)}
Check Updates
</motion.button>
</div>
<div className="flex gap-4">
<div className="flex-1">
<div className="space-y-1">
<input
type="text"
className={classNames(
'w-full px-4 py-3 rounded-xl',
'bg-bolt-elements-background-depth-2 border border-bolt-elements-borderColor',
'text-bolt-elements-textPrimary placeholder-bolt-elements-textTertiary',
'focus:outline-none focus:ring-2 focus:ring-purple-500/30',
'transition-all duration-200',
)}
placeholder="Search models or enter custom model name..."
value={searchQuery || modelString}
onChange={(e) => {
const value = e.target.value;
setSearchQuery(value);
setModelString(value);
}}
disabled={isInstalling}
/>
<p className="text-sm text-bolt-elements-textSecondary px-1">
Browse models at{' '}
<a
href="https://ollama.com/library"
target="_blank"
rel="noopener noreferrer"
className="text-purple-500 hover:underline inline-flex items-center gap-1 text-base font-medium"
>
ollama.com/library
<div className="i-ph:arrow-square-out text-sm" />
</a>{' '}
and copy model names to install
</p>
</div>
</div>
<motion.button
onClick={() => handleInstallModel(modelString)}
disabled={!modelString || isInstalling}
className={classNames(
'rounded-lg px-4 py-2',
'bg-purple-500 text-white text-sm',
'hover:bg-purple-600',
'transition-all duration-200',
'flex items-center gap-2',
{ 'opacity-50 cursor-not-allowed': !modelString || isInstalling },
)}
whileHover={{ scale: 1.02 }}
whileTap={{ scale: 0.98 }}
>
{isInstalling ? (
<div className="flex items-center gap-2">
<div className="i-ph:spinner-gap-bold animate-spin w-4 h-4" />
<span>Installing...</span>
</div>
) : (
<div className="flex items-center gap-2">
<OllamaIcon className="w-4 h-4" />
<span>Install Model</span>
</div>
)}
</motion.button>
</div>
<div className="flex flex-wrap gap-2">
{allTags.map((tag) => (
<button
key={tag}
onClick={() => {
setSelectedTags((prev) => (prev.includes(tag) ? prev.filter((t) => t !== tag) : [...prev, tag]));
}}
className={classNames(
'px-3 py-1 rounded-full text-xs font-medium transition-all duration-200',
selectedTags.includes(tag)
? 'bg-purple-500 text-white'
: 'bg-bolt-elements-background-depth-3 text-bolt-elements-textSecondary hover:bg-bolt-elements-background-depth-4',
)}
>
{tag}
</button>
))}
</div>
<div className="grid grid-cols-1 gap-2">
{filteredModels.map((model) => (
<motion.div
key={model.name}
className={classNames(
'flex items-start gap-2 p-3 rounded-lg',
'bg-bolt-elements-background-depth-3',
'hover:bg-bolt-elements-background-depth-4',
'transition-all duration-200',
'relative group',
)}
>
<OllamaIcon className="w-5 h-5 text-purple-500 mt-0.5 flex-shrink-0" />
<div className="flex-1 space-y-1.5">
<div className="flex items-start justify-between">
<div>
<p className="text-bolt-elements-textPrimary font-mono text-sm">{model.name}</p>
<p className="text-xs text-bolt-elements-textSecondary mt-0.5">{model.desc}</p>
</div>
<div className="text-right">
<span className="text-xs text-bolt-elements-textTertiary">{model.size}</span>
{model.installedVersion && (
<div className="mt-0.5 flex flex-col items-end gap-0.5">
<span className="text-xs text-bolt-elements-textTertiary">v{model.installedVersion}</span>
{model.needsUpdate && model.latestVersion && (
<span className="text-xs text-purple-500">v{model.latestVersion} available</span>
)}
</div>
)}
</div>
</div>
<div className="flex items-center justify-between">
<div className="flex flex-wrap gap-1">
{model.tags.map((tag) => (
<span
key={tag}
className="px-1.5 py-0.5 rounded-full text-[10px] bg-bolt-elements-background-depth-4 text-bolt-elements-textTertiary"
>
{tag}
</span>
))}
</div>
<div className="flex gap-2">
{model.installedVersion ? (
model.needsUpdate ? (
<motion.button
onClick={() => handleUpdateModel(model.name)}
className={classNames(
'px-2 py-0.5 rounded-lg text-xs',
'bg-purple-500 text-white',
'hover:bg-purple-600',
'transition-all duration-200',
'flex items-center gap-1',
)}
whileHover={{ scale: 1.02 }}
whileTap={{ scale: 0.98 }}
>
<div className="i-ph:arrows-clockwise text-xs" />
Update
</motion.button>
) : (
<span className="px-2 py-0.5 rounded-lg text-xs text-green-500 bg-green-500/10">Up to date</span>
)
) : (
<motion.button
onClick={() => handleInstallModel(model.name)}
className={classNames(
'px-2 py-0.5 rounded-lg text-xs',
'bg-purple-500 text-white',
'hover:bg-purple-600',
'transition-all duration-200',
'flex items-center gap-1',
)}
whileHover={{ scale: 1.02 }}
whileTap={{ scale: 0.98 }}
>
<div className="i-ph:download text-xs" />
Install
</motion.button>
)}
</div>
</div>
</div>
</motion.div>
))}
</div>
{installProgress && (
<motion.div initial={{ opacity: 0, y: 10 }} animate={{ opacity: 1, y: 0 }} className="space-y-2">
<div className="flex justify-between text-sm">
<span className="text-bolt-elements-textSecondary">{installProgress.status}</span>
<div className="flex items-center gap-4">
<span className="text-bolt-elements-textTertiary">
{installProgress.downloadedSize} / {installProgress.totalSize}
</span>
<span className="text-bolt-elements-textTertiary">{installProgress.speed}</span>
<span className="text-bolt-elements-textSecondary">{Math.round(installProgress.progress)}%</span>
</div>
</div>
<Progress value={installProgress.progress} className="h-1" />
</motion.div>
)}
</div>
);
}

View File

@@ -0,0 +1,135 @@
import { useState, useEffect } from 'react';
import type { ServiceStatus } from './types';
import { ProviderStatusCheckerFactory } from './provider-factory';
export default function ServiceStatusTab() {
const [serviceStatuses, setServiceStatuses] = useState<ServiceStatus[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
const checkAllProviders = async () => {
try {
setLoading(true);
setError(null);
const providers = ProviderStatusCheckerFactory.getProviderNames();
const statuses: ServiceStatus[] = [];
for (const provider of providers) {
try {
const checker = ProviderStatusCheckerFactory.getChecker(provider);
const result = await checker.checkStatus();
statuses.push({
provider,
...result,
lastChecked: new Date().toISOString(),
});
} catch (err) {
console.error(`Error checking ${provider} status:`, err);
statuses.push({
provider,
status: 'degraded',
message: 'Unable to check service status',
incidents: ['Error checking service status'],
lastChecked: new Date().toISOString(),
});
}
}
setServiceStatuses(statuses);
} catch (err) {
console.error('Error checking provider statuses:', err);
setError('Failed to check service statuses');
} finally {
setLoading(false);
}
};
checkAllProviders();
// Set up periodic checks every 5 minutes
const interval = setInterval(checkAllProviders, 5 * 60 * 1000);
return () => clearInterval(interval);
}, []);
const getStatusColor = (status: ServiceStatus['status']) => {
switch (status) {
case 'operational':
return 'text-green-500 dark:text-green-400';
case 'degraded':
return 'text-yellow-500 dark:text-yellow-400';
case 'down':
return 'text-red-500 dark:text-red-400';
default:
return 'text-gray-500 dark:text-gray-400';
}
};
const getStatusIcon = (status: ServiceStatus['status']) => {
switch (status) {
case 'operational':
return 'i-ph:check-circle';
case 'degraded':
return 'i-ph:warning';
case 'down':
return 'i-ph:x-circle';
default:
return 'i-ph:question';
}
};
if (loading) {
return (
<div className="flex items-center justify-center h-full">
<div className="animate-spin i-ph:circle-notch w-8 h-8 text-purple-500" />
</div>
);
}
if (error) {
return (
<div className="flex flex-col items-center justify-center h-full text-red-500 dark:text-red-400">
<div className="i-ph:warning w-8 h-8 mb-2" />
<p>{error}</p>
</div>
);
}
return (
<div className="space-y-6">
<div className="grid grid-cols-1 gap-4">
{serviceStatuses.map((service) => (
<div
key={service.provider}
className="p-4 bg-white dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700"
>
<div className="flex items-center justify-between mb-2">
<h3 className="text-lg font-semibold text-gray-900 dark:text-white">{service.provider}</h3>
<div className={`flex items-center ${getStatusColor(service.status)}`}>
<div className={`${getStatusIcon(service.status)} w-5 h-5 mr-2`} />
<span className="capitalize">{service.status}</span>
</div>
</div>
<p className="text-gray-600 dark:text-gray-300 mb-2">{service.message}</p>
{service.incidents && service.incidents.length > 0 && (
<div className="mt-2">
<h4 className="text-sm font-semibold text-gray-700 dark:text-gray-300 mb-1">Recent Incidents:</h4>
<ul className="text-sm text-gray-600 dark:text-gray-400 space-y-1">
{service.incidents.map((incident, index) => (
<li key={index}>{incident}</li>
))}
</ul>
</div>
)}
<div className="mt-2 text-xs text-gray-500 dark:text-gray-400">
Last checked: {new Date(service.lastChecked).toLocaleString()}
</div>
</div>
))}
</div>
</div>
);
}

View File

@@ -0,0 +1,121 @@
import type { ProviderConfig, StatusCheckResult, ApiResponse } from './types';
export abstract class BaseProviderChecker {
protected config: ProviderConfig;
constructor(config: ProviderConfig) {
this.config = config;
}
protected async checkApiEndpoint(
url: string,
headers?: Record<string, string>,
testModel?: string,
): Promise<{ ok: boolean; status: number | string; message?: string; responseTime: number }> {
try {
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), 10000);
const startTime = performance.now();
// Add common headers
const processedHeaders = {
'Content-Type': 'application/json',
...headers,
};
const response = await fetch(url, {
method: 'GET',
headers: processedHeaders,
signal: controller.signal,
});
const endTime = performance.now();
const responseTime = endTime - startTime;
clearTimeout(timeoutId);
const data = (await response.json()) as ApiResponse;
if (!response.ok) {
let errorMessage = `API returned status: ${response.status}`;
if (data.error?.message) {
errorMessage = data.error.message;
} else if (data.message) {
errorMessage = data.message;
}
return {
ok: false,
status: response.status,
message: errorMessage,
responseTime,
};
}
// Different providers have different model list formats
let models: string[] = [];
if (Array.isArray(data)) {
models = data.map((model: { id?: string; name?: string }) => model.id || model.name || '');
} else if (data.data && Array.isArray(data.data)) {
models = data.data.map((model) => model.id || model.name || '');
} else if (data.models && Array.isArray(data.models)) {
models = data.models.map((model) => model.id || model.name || '');
} else if (data.model) {
models = [data.model];
}
if (!testModel || models.length > 0) {
return {
ok: true,
status: response.status,
responseTime,
message: 'API key is valid',
};
}
if (testModel && !models.includes(testModel)) {
return {
ok: true,
status: 'model_not_found',
message: `API key is valid (test model ${testModel} not found in ${models.length} available models)`,
responseTime,
};
}
return {
ok: true,
status: response.status,
message: 'API key is valid',
responseTime,
};
} catch (error) {
console.error(`Error checking API endpoint ${url}:`, error);
return {
ok: false,
status: error instanceof Error ? error.message : 'Unknown error',
message: error instanceof Error ? `Connection failed: ${error.message}` : 'Connection failed',
responseTime: 0,
};
}
}
protected async checkEndpoint(url: string): Promise<'reachable' | 'unreachable'> {
try {
const response = await fetch(url, {
mode: 'no-cors',
headers: {
Accept: 'text/html',
},
});
return response.type === 'opaque' ? 'reachable' : 'unreachable';
} catch (error) {
console.error(`Error checking ${url}:`, error);
return 'unreachable';
}
}
abstract checkStatus(): Promise<StatusCheckResult>;
}

View File

@@ -0,0 +1,154 @@
import type { ProviderName, ProviderConfig, StatusCheckResult } from './types';
import { BaseProviderChecker } from './base-provider';
import { AmazonBedrockStatusChecker } from './providers/amazon-bedrock';
import { CohereStatusChecker } from './providers/cohere';
import { DeepseekStatusChecker } from './providers/deepseek';
import { GoogleStatusChecker } from './providers/google';
import { GroqStatusChecker } from './providers/groq';
import { HuggingFaceStatusChecker } from './providers/huggingface';
import { HyperbolicStatusChecker } from './providers/hyperbolic';
import { MistralStatusChecker } from './providers/mistral';
import { OpenRouterStatusChecker } from './providers/openrouter';
import { PerplexityStatusChecker } from './providers/perplexity';
import { TogetherStatusChecker } from './providers/together';
import { XAIStatusChecker } from './providers/xai';
export class ProviderStatusCheckerFactory {
private static _providerConfigs: Record<ProviderName, ProviderConfig> = {
AmazonBedrock: {
statusUrl: 'https://health.aws.amazon.com/health/status',
apiUrl: 'https://bedrock.us-east-1.amazonaws.com/models',
headers: {},
testModel: 'anthropic.claude-3-sonnet-20240229-v1:0',
},
Cohere: {
statusUrl: 'https://status.cohere.com/',
apiUrl: 'https://api.cohere.ai/v1/models',
headers: {},
testModel: 'command',
},
Deepseek: {
statusUrl: 'https://status.deepseek.com/',
apiUrl: 'https://api.deepseek.com/v1/models',
headers: {},
testModel: 'deepseek-chat',
},
Google: {
statusUrl: 'https://status.cloud.google.com/',
apiUrl: 'https://generativelanguage.googleapis.com/v1/models',
headers: {},
testModel: 'gemini-pro',
},
Groq: {
statusUrl: 'https://groqstatus.com/',
apiUrl: 'https://api.groq.com/v1/models',
headers: {},
testModel: 'mixtral-8x7b-32768',
},
HuggingFace: {
statusUrl: 'https://status.huggingface.co/',
apiUrl: 'https://api-inference.huggingface.co/models',
headers: {},
testModel: 'mistralai/Mixtral-8x7B-Instruct-v0.1',
},
Hyperbolic: {
statusUrl: 'https://status.hyperbolic.ai/',
apiUrl: 'https://api.hyperbolic.ai/v1/models',
headers: {},
testModel: 'hyperbolic-1',
},
Mistral: {
statusUrl: 'https://status.mistral.ai/',
apiUrl: 'https://api.mistral.ai/v1/models',
headers: {},
testModel: 'mistral-tiny',
},
OpenRouter: {
statusUrl: 'https://status.openrouter.ai/',
apiUrl: 'https://openrouter.ai/api/v1/models',
headers: {},
testModel: 'anthropic/claude-3-sonnet',
},
Perplexity: {
statusUrl: 'https://status.perplexity.com/',
apiUrl: 'https://api.perplexity.ai/v1/models',
headers: {},
testModel: 'pplx-7b-chat',
},
Together: {
statusUrl: 'https://status.together.ai/',
apiUrl: 'https://api.together.xyz/v1/models',
headers: {},
testModel: 'mistralai/Mixtral-8x7B-Instruct-v0.1',
},
XAI: {
statusUrl: 'https://status.x.ai/',
apiUrl: 'https://api.x.ai/v1/models',
headers: {},
testModel: 'grok-1',
},
};
static getChecker(provider: ProviderName): BaseProviderChecker {
const config = this._providerConfigs[provider];
if (!config) {
throw new Error(`No configuration found for provider: ${provider}`);
}
switch (provider) {
case 'AmazonBedrock':
return new AmazonBedrockStatusChecker(config);
case 'Cohere':
return new CohereStatusChecker(config);
case 'Deepseek':
return new DeepseekStatusChecker(config);
case 'Google':
return new GoogleStatusChecker(config);
case 'Groq':
return new GroqStatusChecker(config);
case 'HuggingFace':
return new HuggingFaceStatusChecker(config);
case 'Hyperbolic':
return new HyperbolicStatusChecker(config);
case 'Mistral':
return new MistralStatusChecker(config);
case 'OpenRouter':
return new OpenRouterStatusChecker(config);
case 'Perplexity':
return new PerplexityStatusChecker(config);
case 'Together':
return new TogetherStatusChecker(config);
case 'XAI':
return new XAIStatusChecker(config);
default:
return new (class extends BaseProviderChecker {
async checkStatus(): Promise<StatusCheckResult> {
const endpointStatus = await this.checkEndpoint(this.config.statusUrl);
const apiStatus = await this.checkEndpoint(this.config.apiUrl);
return {
status: endpointStatus === 'reachable' && apiStatus === 'reachable' ? 'operational' : 'degraded',
message: `Status page: ${endpointStatus}, API: ${apiStatus}`,
incidents: ['Note: Limited status information due to CORS restrictions'],
};
}
})(config);
}
}
static getProviderNames(): ProviderName[] {
return Object.keys(this._providerConfigs) as ProviderName[];
}
static getProviderConfig(provider: ProviderName): ProviderConfig {
const config = this._providerConfigs[provider];
if (!config) {
throw new Error(`Unknown provider: ${provider}`);
}
return config;
}
}

View File

@@ -0,0 +1,76 @@
import { BaseProviderChecker } from '~/components/@settings/tabs/providers/service-status/base-provider';
import type { StatusCheckResult } from '~/components/@settings/tabs/providers/service-status/types';
export class AmazonBedrockStatusChecker extends BaseProviderChecker {
async checkStatus(): Promise<StatusCheckResult> {
try {
// Check AWS health status page
const statusPageResponse = await fetch('https://health.aws.amazon.com/health/status');
const text = await statusPageResponse.text();
// Check for Bedrock and general AWS status
const hasBedrockIssues =
text.includes('Amazon Bedrock') &&
(text.includes('Service is experiencing elevated error rates') ||
text.includes('Service disruption') ||
text.includes('Degraded Service'));
const hasGeneralIssues = text.includes('Service disruption') || text.includes('Multiple services affected');
// Extract incidents
const incidents: string[] = [];
const incidentMatches = text.matchAll(/(\d{4}-\d{2}-\d{2})\s+(.*?)\s+Impact:(.*?)(?=\n|$)/g);
for (const match of incidentMatches) {
const [, date, title, impact] = match;
if (title.includes('Bedrock') || title.includes('AWS')) {
incidents.push(`${date}: ${title.trim()} - Impact: ${impact.trim()}`);
}
}
let status: StatusCheckResult['status'] = 'operational';
let message = 'All services operational';
if (hasBedrockIssues) {
status = 'degraded';
message = 'Amazon Bedrock service issues reported';
} else if (hasGeneralIssues) {
status = 'degraded';
message = 'AWS experiencing general issues';
}
// If status page check fails, fallback to endpoint check
if (!statusPageResponse.ok) {
const endpointStatus = await this.checkEndpoint('https://health.aws.amazon.com/health/status');
const apiEndpoint = 'https://bedrock.us-east-1.amazonaws.com/models';
const apiStatus = await this.checkEndpoint(apiEndpoint);
return {
status: endpointStatus === 'reachable' && apiStatus === 'reachable' ? 'operational' : 'degraded',
message: `Status page: ${endpointStatus}, API: ${apiStatus}`,
incidents: ['Note: Limited status information due to CORS restrictions'],
};
}
return {
status,
message,
incidents: incidents.slice(0, 5),
};
} catch (error) {
console.error('Error checking Amazon Bedrock status:', error);
// Fallback to basic endpoint check
const endpointStatus = await this.checkEndpoint('https://health.aws.amazon.com/health/status');
const apiEndpoint = 'https://bedrock.us-east-1.amazonaws.com/models';
const apiStatus = await this.checkEndpoint(apiEndpoint);
return {
status: endpointStatus === 'reachable' && apiStatus === 'reachable' ? 'operational' : 'degraded',
message: `Status page: ${endpointStatus}, API: ${apiStatus}`,
incidents: ['Note: Limited status information due to CORS restrictions'],
};
}
}
}

View File

@@ -0,0 +1,80 @@
import { BaseProviderChecker } from '~/components/@settings/tabs/providers/service-status/base-provider';
import type { StatusCheckResult } from '~/components/@settings/tabs/providers/service-status/types';
export class AnthropicStatusChecker extends BaseProviderChecker {
async checkStatus(): Promise<StatusCheckResult> {
try {
// Check status page
const statusPageResponse = await fetch('https://status.anthropic.com/');
const text = await statusPageResponse.text();
// Check for specific Anthropic status indicators
const isOperational = text.includes('All Systems Operational');
const hasDegradedPerformance = text.includes('Degraded Performance');
const hasPartialOutage = text.includes('Partial Outage');
const hasMajorOutage = text.includes('Major Outage');
// Extract incidents
const incidents: string[] = [];
const incidentSection = text.match(/Past Incidents(.*?)(?=\n\n)/s);
if (incidentSection) {
const incidentLines = incidentSection[1]
.split('\n')
.map((line) => line.trim())
.filter((line) => line && line.includes('202')); // Only get dated incidents
incidents.push(...incidentLines.slice(0, 5));
}
let status: StatusCheckResult['status'] = 'operational';
let message = 'All systems operational';
if (hasMajorOutage) {
status = 'down';
message = 'Major service outage';
} else if (hasPartialOutage) {
status = 'down';
message = 'Partial service outage';
} else if (hasDegradedPerformance) {
status = 'degraded';
message = 'Service experiencing degraded performance';
} else if (!isOperational) {
status = 'degraded';
message = 'Service status unknown';
}
// If status page check fails, fallback to endpoint check
if (!statusPageResponse.ok) {
const endpointStatus = await this.checkEndpoint('https://status.anthropic.com/');
const apiEndpoint = 'https://api.anthropic.com/v1/messages';
const apiStatus = await this.checkEndpoint(apiEndpoint);
return {
status: endpointStatus === 'reachable' && apiStatus === 'reachable' ? 'operational' : 'degraded',
message: `Status page: ${endpointStatus}, API: ${apiStatus}`,
incidents: ['Note: Limited status information due to CORS restrictions'],
};
}
return {
status,
message,
incidents,
};
} catch (error) {
console.error('Error checking Anthropic status:', error);
// Fallback to basic endpoint check
const endpointStatus = await this.checkEndpoint('https://status.anthropic.com/');
const apiEndpoint = 'https://api.anthropic.com/v1/messages';
const apiStatus = await this.checkEndpoint(apiEndpoint);
return {
status: endpointStatus === 'reachable' && apiStatus === 'reachable' ? 'operational' : 'degraded',
message: `Status page: ${endpointStatus}, API: ${apiStatus}`,
incidents: ['Note: Limited status information due to CORS restrictions'],
};
}
}
}

View File

@@ -0,0 +1,91 @@
import { BaseProviderChecker } from '~/components/@settings/tabs/providers/service-status/base-provider';
import type { StatusCheckResult } from '~/components/@settings/tabs/providers/service-status/types';
export class CohereStatusChecker extends BaseProviderChecker {
async checkStatus(): Promise<StatusCheckResult> {
try {
// Check status page
const statusPageResponse = await fetch('https://status.cohere.com/');
const text = await statusPageResponse.text();
// Check for specific Cohere status indicators
const isOperational = text.includes('All Systems Operational');
const hasIncidents = text.includes('Active Incidents');
const hasDegradation = text.includes('Degraded Performance');
const hasOutage = text.includes('Service Outage');
// Extract incidents
const incidents: string[] = [];
const incidentSection = text.match(/Past Incidents(.*?)(?=\n\n)/s);
if (incidentSection) {
const incidentLines = incidentSection[1]
.split('\n')
.map((line) => line.trim())
.filter((line) => line && line.includes('202')); // Only get dated incidents
incidents.push(...incidentLines.slice(0, 5));
}
// Check specific services
const services = {
api: {
operational: text.includes('API Service') && text.includes('Operational'),
degraded: text.includes('API Service') && text.includes('Degraded Performance'),
outage: text.includes('API Service') && text.includes('Service Outage'),
},
generation: {
operational: text.includes('Generation Service') && text.includes('Operational'),
degraded: text.includes('Generation Service') && text.includes('Degraded Performance'),
outage: text.includes('Generation Service') && text.includes('Service Outage'),
},
};
let status: StatusCheckResult['status'] = 'operational';
let message = 'All systems operational';
if (services.api.outage || services.generation.outage || hasOutage) {
status = 'down';
message = 'Service outage detected';
} else if (services.api.degraded || services.generation.degraded || hasDegradation || hasIncidents) {
status = 'degraded';
message = 'Service experiencing issues';
} else if (!isOperational) {
status = 'degraded';
message = 'Service status unknown';
}
// If status page check fails, fallback to endpoint check
if (!statusPageResponse.ok) {
const endpointStatus = await this.checkEndpoint('https://status.cohere.com/');
const apiEndpoint = 'https://api.cohere.ai/v1/models';
const apiStatus = await this.checkEndpoint(apiEndpoint);
return {
status: endpointStatus === 'reachable' && apiStatus === 'reachable' ? 'operational' : 'degraded',
message: `Status page: ${endpointStatus}, API: ${apiStatus}`,
incidents: ['Note: Limited status information due to CORS restrictions'],
};
}
return {
status,
message,
incidents,
};
} catch (error) {
console.error('Error checking Cohere status:', error);
// Fallback to basic endpoint check
const endpointStatus = await this.checkEndpoint('https://status.cohere.com/');
const apiEndpoint = 'https://api.cohere.ai/v1/models';
const apiStatus = await this.checkEndpoint(apiEndpoint);
return {
status: endpointStatus === 'reachable' && apiStatus === 'reachable' ? 'operational' : 'degraded',
message: `Status page: ${endpointStatus}, API: ${apiStatus}`,
incidents: ['Note: Limited status information due to CORS restrictions'],
};
}
}
}

View File

@@ -0,0 +1,40 @@
import { BaseProviderChecker } from '~/components/@settings/tabs/providers/service-status/base-provider';
import type { StatusCheckResult } from '~/components/@settings/tabs/providers/service-status/types';
export class DeepseekStatusChecker extends BaseProviderChecker {
async checkStatus(): Promise<StatusCheckResult> {
try {
/*
* Check status page - Note: Deepseek doesn't have a public status page yet
* so we'll check their API endpoint directly
*/
const apiEndpoint = 'https://api.deepseek.com/v1/models';
const apiStatus = await this.checkEndpoint(apiEndpoint);
// Check their website as a secondary indicator
const websiteStatus = await this.checkEndpoint('https://deepseek.com');
let status: StatusCheckResult['status'] = 'operational';
let message = 'All systems operational';
if (apiStatus !== 'reachable' || websiteStatus !== 'reachable') {
status = apiStatus !== 'reachable' ? 'down' : 'degraded';
message = apiStatus !== 'reachable' ? 'API appears to be down' : 'Service may be experiencing issues';
}
return {
status,
message,
incidents: [], // No public incident tracking available yet
};
} catch (error) {
console.error('Error checking Deepseek status:', error);
return {
status: 'degraded',
message: 'Unable to determine service status',
incidents: ['Note: Limited status information available'],
};
}
}
}

View File

@@ -0,0 +1,77 @@
import { BaseProviderChecker } from '~/components/@settings/tabs/providers/service-status/base-provider';
import type { StatusCheckResult } from '~/components/@settings/tabs/providers/service-status/types';
export class GoogleStatusChecker extends BaseProviderChecker {
async checkStatus(): Promise<StatusCheckResult> {
try {
// Check status page
const statusPageResponse = await fetch('https://status.cloud.google.com/');
const text = await statusPageResponse.text();
// Check for Vertex AI and general cloud status
const hasVertexAIIssues =
text.includes('Vertex AI') &&
(text.includes('Incident') ||
text.includes('Disruption') ||
text.includes('Outage') ||
text.includes('degraded'));
const hasGeneralIssues = text.includes('Major Incidents') || text.includes('Service Disruption');
// Extract incidents
const incidents: string[] = [];
const incidentMatches = text.matchAll(/(\d{4}-\d{2}-\d{2})\s+(.*?)\s+Impact:(.*?)(?=\n|$)/g);
for (const match of incidentMatches) {
const [, date, title, impact] = match;
if (title.includes('Vertex AI') || title.includes('Cloud')) {
incidents.push(`${date}: ${title.trim()} - Impact: ${impact.trim()}`);
}
}
let status: StatusCheckResult['status'] = 'operational';
let message = 'All services operational';
if (hasVertexAIIssues) {
status = 'degraded';
message = 'Vertex AI service issues reported';
} else if (hasGeneralIssues) {
status = 'degraded';
message = 'Google Cloud experiencing issues';
}
// If status page check fails, fallback to endpoint check
if (!statusPageResponse.ok) {
const endpointStatus = await this.checkEndpoint('https://status.cloud.google.com/');
const apiEndpoint = 'https://generativelanguage.googleapis.com/v1/models';
const apiStatus = await this.checkEndpoint(apiEndpoint);
return {
status: endpointStatus === 'reachable' && apiStatus === 'reachable' ? 'operational' : 'degraded',
message: `Status page: ${endpointStatus}, API: ${apiStatus}`,
incidents: ['Note: Limited status information due to CORS restrictions'],
};
}
return {
status,
message,
incidents: incidents.slice(0, 5),
};
} catch (error) {
console.error('Error checking Google status:', error);
// Fallback to basic endpoint check
const endpointStatus = await this.checkEndpoint('https://status.cloud.google.com/');
const apiEndpoint = 'https://generativelanguage.googleapis.com/v1/models';
const apiStatus = await this.checkEndpoint(apiEndpoint);
return {
status: endpointStatus === 'reachable' && apiStatus === 'reachable' ? 'operational' : 'degraded',
message: `Status page: ${endpointStatus}, API: ${apiStatus}`,
incidents: ['Note: Limited status information due to CORS restrictions'],
};
}
}
}

View File

@@ -0,0 +1,72 @@
import { BaseProviderChecker } from '~/components/@settings/tabs/providers/service-status/base-provider';
import type { StatusCheckResult } from '~/components/@settings/tabs/providers/service-status/types';
export class GroqStatusChecker extends BaseProviderChecker {
async checkStatus(): Promise<StatusCheckResult> {
try {
// Check status page
const statusPageResponse = await fetch('https://groqstatus.com/');
const text = await statusPageResponse.text();
const isOperational = text.includes('All Systems Operational');
const hasIncidents = text.includes('Active Incidents');
const hasDegradation = text.includes('Degraded Performance');
const hasOutage = text.includes('Service Outage');
// Extract incidents
const incidents: string[] = [];
const incidentMatches = text.matchAll(/(\d{4}-\d{2}-\d{2})\s+(.*?)\s+Status:(.*?)(?=\n|$)/g);
for (const match of incidentMatches) {
const [, date, title, status] = match;
incidents.push(`${date}: ${title.trim()} - ${status.trim()}`);
}
let status: StatusCheckResult['status'] = 'operational';
let message = 'All systems operational';
if (hasOutage) {
status = 'down';
message = 'Service outage detected';
} else if (hasDegradation || hasIncidents) {
status = 'degraded';
message = 'Service experiencing issues';
} else if (!isOperational) {
status = 'degraded';
message = 'Service status unknown';
}
// If status page check fails, fallback to endpoint check
if (!statusPageResponse.ok) {
const endpointStatus = await this.checkEndpoint('https://groqstatus.com/');
const apiEndpoint = 'https://api.groq.com/v1/models';
const apiStatus = await this.checkEndpoint(apiEndpoint);
return {
status: endpointStatus === 'reachable' && apiStatus === 'reachable' ? 'operational' : 'degraded',
message: `Status page: ${endpointStatus}, API: ${apiStatus}`,
incidents: ['Note: Limited status information due to CORS restrictions'],
};
}
return {
status,
message,
incidents: incidents.slice(0, 5),
};
} catch (error) {
console.error('Error checking Groq status:', error);
// Fallback to basic endpoint check
const endpointStatus = await this.checkEndpoint('https://groqstatus.com/');
const apiEndpoint = 'https://api.groq.com/v1/models';
const apiStatus = await this.checkEndpoint(apiEndpoint);
return {
status: endpointStatus === 'reachable' && apiStatus === 'reachable' ? 'operational' : 'degraded',
message: `Status page: ${endpointStatus}, API: ${apiStatus}`,
incidents: ['Note: Limited status information due to CORS restrictions'],
};
}
}
}

View File

@@ -0,0 +1,98 @@
import { BaseProviderChecker } from '~/components/@settings/tabs/providers/service-status/base-provider';
import type { StatusCheckResult } from '~/components/@settings/tabs/providers/service-status/types';
export class HuggingFaceStatusChecker extends BaseProviderChecker {
async checkStatus(): Promise<StatusCheckResult> {
try {
// Check status page
const statusPageResponse = await fetch('https://status.huggingface.co/');
const text = await statusPageResponse.text();
// Check for "All services are online" message
const allServicesOnline = text.includes('All services are online');
// Get last update time
const lastUpdateMatch = text.match(/Last updated on (.*?)(EST|PST|GMT)/);
const lastUpdate = lastUpdateMatch ? `${lastUpdateMatch[1]}${lastUpdateMatch[2]}` : '';
// Check individual services and their uptime percentages
const services = {
'Huggingface Hub': {
operational: text.includes('Huggingface Hub') && text.includes('Operational'),
uptime: text.match(/Huggingface Hub[\s\S]*?(\d+\.\d+)%\s*uptime/)?.[1],
},
'Git Hosting and Serving': {
operational: text.includes('Git Hosting and Serving') && text.includes('Operational'),
uptime: text.match(/Git Hosting and Serving[\s\S]*?(\d+\.\d+)%\s*uptime/)?.[1],
},
'Inference API': {
operational: text.includes('Inference API') && text.includes('Operational'),
uptime: text.match(/Inference API[\s\S]*?(\d+\.\d+)%\s*uptime/)?.[1],
},
'HF Endpoints': {
operational: text.includes('HF Endpoints') && text.includes('Operational'),
uptime: text.match(/HF Endpoints[\s\S]*?(\d+\.\d+)%\s*uptime/)?.[1],
},
Spaces: {
operational: text.includes('Spaces') && text.includes('Operational'),
uptime: text.match(/Spaces[\s\S]*?(\d+\.\d+)%\s*uptime/)?.[1],
},
};
// Create service status messages with uptime
const serviceMessages = Object.entries(services).map(([name, info]) => {
if (info.uptime) {
return `${name}: ${info.uptime}% uptime`;
}
return `${name}: ${info.operational ? 'Operational' : 'Issues detected'}`;
});
// Determine overall status
let status: StatusCheckResult['status'] = 'operational';
let message = allServicesOnline
? `All services are online (Last updated on ${lastUpdate})`
: 'Checking individual services';
// Only mark as degraded if we explicitly detect issues
const hasIssues = Object.values(services).some((service) => !service.operational);
if (hasIssues) {
status = 'degraded';
message = `Service issues detected (Last updated on ${lastUpdate})`;
}
// If status page check fails, fallback to endpoint check
if (!statusPageResponse.ok) {
const endpointStatus = await this.checkEndpoint('https://status.huggingface.co/');
const apiEndpoint = 'https://api-inference.huggingface.co/models';
const apiStatus = await this.checkEndpoint(apiEndpoint);
return {
status: endpointStatus === 'reachable' && apiStatus === 'reachable' ? 'operational' : 'degraded',
message: `Status page: ${endpointStatus}, API: ${apiStatus}`,
incidents: ['Note: Limited status information due to CORS restrictions'],
};
}
return {
status,
message,
incidents: serviceMessages,
};
} catch (error) {
console.error('Error checking HuggingFace status:', error);
// Fallback to basic endpoint check
const endpointStatus = await this.checkEndpoint('https://status.huggingface.co/');
const apiEndpoint = 'https://api-inference.huggingface.co/models';
const apiStatus = await this.checkEndpoint(apiEndpoint);
return {
status: endpointStatus === 'reachable' && apiStatus === 'reachable' ? 'operational' : 'degraded',
message: `Status page: ${endpointStatus}, API: ${apiStatus}`,
incidents: ['Note: Limited status information due to CORS restrictions'],
};
}
}
}

View File

@@ -0,0 +1,40 @@
import { BaseProviderChecker } from '~/components/@settings/tabs/providers/service-status/base-provider';
import type { StatusCheckResult } from '~/components/@settings/tabs/providers/service-status/types';
export class HyperbolicStatusChecker extends BaseProviderChecker {
async checkStatus(): Promise<StatusCheckResult> {
try {
/*
* Check API endpoint directly since Hyperbolic is a newer provider
* and may not have a public status page yet
*/
const apiEndpoint = 'https://api.hyperbolic.ai/v1/models';
const apiStatus = await this.checkEndpoint(apiEndpoint);
// Check their website as a secondary indicator
const websiteStatus = await this.checkEndpoint('https://hyperbolic.ai');
let status: StatusCheckResult['status'] = 'operational';
let message = 'All systems operational';
if (apiStatus !== 'reachable' || websiteStatus !== 'reachable') {
status = apiStatus !== 'reachable' ? 'down' : 'degraded';
message = apiStatus !== 'reachable' ? 'API appears to be down' : 'Service may be experiencing issues';
}
return {
status,
message,
incidents: [], // No public incident tracking available yet
};
} catch (error) {
console.error('Error checking Hyperbolic status:', error);
return {
status: 'degraded',
message: 'Unable to determine service status',
incidents: ['Note: Limited status information available'],
};
}
}
}

View File

@@ -0,0 +1,76 @@
import { BaseProviderChecker } from '~/components/@settings/tabs/providers/service-status/base-provider';
import type { StatusCheckResult } from '~/components/@settings/tabs/providers/service-status/types';
export class MistralStatusChecker extends BaseProviderChecker {
async checkStatus(): Promise<StatusCheckResult> {
try {
// Check status page
const statusPageResponse = await fetch('https://status.mistral.ai/');
const text = await statusPageResponse.text();
const isOperational = text.includes('All Systems Operational');
const hasIncidents = text.includes('Active Incidents');
const hasDegradation = text.includes('Degraded Performance');
const hasOutage = text.includes('Service Outage');
// Extract incidents
const incidents: string[] = [];
const incidentSection = text.match(/Recent Events(.*?)(?=\n\n)/s);
if (incidentSection) {
const incidentLines = incidentSection[1]
.split('\n')
.map((line) => line.trim())
.filter((line) => line && !line.includes('No incidents'));
incidents.push(...incidentLines.slice(0, 5));
}
let status: StatusCheckResult['status'] = 'operational';
let message = 'All systems operational';
if (hasOutage) {
status = 'down';
message = 'Service outage detected';
} else if (hasDegradation || hasIncidents) {
status = 'degraded';
message = 'Service experiencing issues';
} else if (!isOperational) {
status = 'degraded';
message = 'Service status unknown';
}
// If status page check fails, fallback to endpoint check
if (!statusPageResponse.ok) {
const endpointStatus = await this.checkEndpoint('https://status.mistral.ai/');
const apiEndpoint = 'https://api.mistral.ai/v1/models';
const apiStatus = await this.checkEndpoint(apiEndpoint);
return {
status: endpointStatus === 'reachable' && apiStatus === 'reachable' ? 'operational' : 'degraded',
message: `Status page: ${endpointStatus}, API: ${apiStatus}`,
incidents: ['Note: Limited status information due to CORS restrictions'],
};
}
return {
status,
message,
incidents,
};
} catch (error) {
console.error('Error checking Mistral status:', error);
// Fallback to basic endpoint check
const endpointStatus = await this.checkEndpoint('https://status.mistral.ai/');
const apiEndpoint = 'https://api.mistral.ai/v1/models';
const apiStatus = await this.checkEndpoint(apiEndpoint);
return {
status: endpointStatus === 'reachable' && apiStatus === 'reachable' ? 'operational' : 'degraded',
message: `Status page: ${endpointStatus}, API: ${apiStatus}`,
incidents: ['Note: Limited status information due to CORS restrictions'],
};
}
}
}

View File

@@ -0,0 +1,99 @@
import { BaseProviderChecker } from '~/components/@settings/tabs/providers/service-status/base-provider';
import type { StatusCheckResult } from '~/components/@settings/tabs/providers/service-status/types';
export class OpenAIStatusChecker extends BaseProviderChecker {
async checkStatus(): Promise<StatusCheckResult> {
try {
// Check status page
const statusPageResponse = await fetch('https://status.openai.com/');
const text = await statusPageResponse.text();
// Check individual services
const services = {
api: {
operational: text.includes('API ? Operational'),
degraded: text.includes('API ? Degraded Performance'),
outage: text.includes('API ? Major Outage') || text.includes('API ? Partial Outage'),
},
chat: {
operational: text.includes('ChatGPT ? Operational'),
degraded: text.includes('ChatGPT ? Degraded Performance'),
outage: text.includes('ChatGPT ? Major Outage') || text.includes('ChatGPT ? Partial Outage'),
},
};
// Extract recent incidents
const incidents: string[] = [];
const incidentMatches = text.match(/Past Incidents(.*?)(?=\w+ \d+, \d{4})/s);
if (incidentMatches) {
const recentIncidents = incidentMatches[1]
.split('\n')
.map((line) => line.trim())
.filter((line) => line && line.includes('202')); // Get only dated incidents
incidents.push(...recentIncidents.slice(0, 5));
}
// Determine overall status
let status: StatusCheckResult['status'] = 'operational';
const messages: string[] = [];
if (services.api.outage || services.chat.outage) {
status = 'down';
if (services.api.outage) {
messages.push('API: Major Outage');
}
if (services.chat.outage) {
messages.push('ChatGPT: Major Outage');
}
} else if (services.api.degraded || services.chat.degraded) {
status = 'degraded';
if (services.api.degraded) {
messages.push('API: Degraded Performance');
}
if (services.chat.degraded) {
messages.push('ChatGPT: Degraded Performance');
}
} else if (services.api.operational) {
messages.push('API: Operational');
}
// If status page check fails, fallback to endpoint check
if (!statusPageResponse.ok) {
const endpointStatus = await this.checkEndpoint('https://status.openai.com/');
const apiEndpoint = 'https://api.openai.com/v1/models';
const apiStatus = await this.checkEndpoint(apiEndpoint);
return {
status: endpointStatus === 'reachable' && apiStatus === 'reachable' ? 'operational' : 'degraded',
message: `Status page: ${endpointStatus}, API: ${apiStatus}`,
incidents: ['Note: Limited status information due to CORS restrictions'],
};
}
return {
status,
message: messages.join(', ') || 'Status unknown',
incidents,
};
} catch (error) {
console.error('Error checking OpenAI status:', error);
// Fallback to basic endpoint check
const endpointStatus = await this.checkEndpoint('https://status.openai.com/');
const apiEndpoint = 'https://api.openai.com/v1/models';
const apiStatus = await this.checkEndpoint(apiEndpoint);
return {
status: endpointStatus === 'reachable' && apiStatus === 'reachable' ? 'operational' : 'degraded',
message: `Status page: ${endpointStatus}, API: ${apiStatus}`,
incidents: ['Note: Limited status information due to CORS restrictions'],
};
}
}
}

View File

@@ -0,0 +1,91 @@
import { BaseProviderChecker } from '~/components/@settings/tabs/providers/service-status/base-provider';
import type { StatusCheckResult } from '~/components/@settings/tabs/providers/service-status/types';
export class OpenRouterStatusChecker extends BaseProviderChecker {
async checkStatus(): Promise<StatusCheckResult> {
try {
// Check status page
const statusPageResponse = await fetch('https://status.openrouter.ai/');
const text = await statusPageResponse.text();
// Check for specific OpenRouter status indicators
const isOperational = text.includes('All Systems Operational');
const hasIncidents = text.includes('Active Incidents');
const hasDegradation = text.includes('Degraded Performance');
const hasOutage = text.includes('Service Outage');
// Extract incidents
const incidents: string[] = [];
const incidentSection = text.match(/Past Incidents(.*?)(?=\n\n)/s);
if (incidentSection) {
const incidentLines = incidentSection[1]
.split('\n')
.map((line) => line.trim())
.filter((line) => line && line.includes('202')); // Only get dated incidents
incidents.push(...incidentLines.slice(0, 5));
}
// Check specific services
const services = {
api: {
operational: text.includes('API Service') && text.includes('Operational'),
degraded: text.includes('API Service') && text.includes('Degraded Performance'),
outage: text.includes('API Service') && text.includes('Service Outage'),
},
routing: {
operational: text.includes('Routing Service') && text.includes('Operational'),
degraded: text.includes('Routing Service') && text.includes('Degraded Performance'),
outage: text.includes('Routing Service') && text.includes('Service Outage'),
},
};
let status: StatusCheckResult['status'] = 'operational';
let message = 'All systems operational';
if (services.api.outage || services.routing.outage || hasOutage) {
status = 'down';
message = 'Service outage detected';
} else if (services.api.degraded || services.routing.degraded || hasDegradation || hasIncidents) {
status = 'degraded';
message = 'Service experiencing issues';
} else if (!isOperational) {
status = 'degraded';
message = 'Service status unknown';
}
// If status page check fails, fallback to endpoint check
if (!statusPageResponse.ok) {
const endpointStatus = await this.checkEndpoint('https://status.openrouter.ai/');
const apiEndpoint = 'https://openrouter.ai/api/v1/models';
const apiStatus = await this.checkEndpoint(apiEndpoint);
return {
status: endpointStatus === 'reachable' && apiStatus === 'reachable' ? 'operational' : 'degraded',
message: `Status page: ${endpointStatus}, API: ${apiStatus}`,
incidents: ['Note: Limited status information due to CORS restrictions'],
};
}
return {
status,
message,
incidents,
};
} catch (error) {
console.error('Error checking OpenRouter status:', error);
// Fallback to basic endpoint check
const endpointStatus = await this.checkEndpoint('https://status.openrouter.ai/');
const apiEndpoint = 'https://openrouter.ai/api/v1/models';
const apiStatus = await this.checkEndpoint(apiEndpoint);
return {
status: endpointStatus === 'reachable' && apiStatus === 'reachable' ? 'operational' : 'degraded',
message: `Status page: ${endpointStatus}, API: ${apiStatus}`,
incidents: ['Note: Limited status information due to CORS restrictions'],
};
}
}
}

View File

@@ -0,0 +1,91 @@
import { BaseProviderChecker } from '~/components/@settings/tabs/providers/service-status/base-provider';
import type { StatusCheckResult } from '~/components/@settings/tabs/providers/service-status/types';
export class PerplexityStatusChecker extends BaseProviderChecker {
async checkStatus(): Promise<StatusCheckResult> {
try {
// Check status page
const statusPageResponse = await fetch('https://status.perplexity.ai/');
const text = await statusPageResponse.text();
// Check for specific Perplexity status indicators
const isOperational = text.includes('All Systems Operational');
const hasIncidents = text.includes('Active Incidents');
const hasDegradation = text.includes('Degraded Performance');
const hasOutage = text.includes('Service Outage');
// Extract incidents
const incidents: string[] = [];
const incidentSection = text.match(/Past Incidents(.*?)(?=\n\n)/s);
if (incidentSection) {
const incidentLines = incidentSection[1]
.split('\n')
.map((line) => line.trim())
.filter((line) => line && line.includes('202')); // Only get dated incidents
incidents.push(...incidentLines.slice(0, 5));
}
// Check specific services
const services = {
api: {
operational: text.includes('API Service') && text.includes('Operational'),
degraded: text.includes('API Service') && text.includes('Degraded Performance'),
outage: text.includes('API Service') && text.includes('Service Outage'),
},
inference: {
operational: text.includes('Inference Service') && text.includes('Operational'),
degraded: text.includes('Inference Service') && text.includes('Degraded Performance'),
outage: text.includes('Inference Service') && text.includes('Service Outage'),
},
};
let status: StatusCheckResult['status'] = 'operational';
let message = 'All systems operational';
if (services.api.outage || services.inference.outage || hasOutage) {
status = 'down';
message = 'Service outage detected';
} else if (services.api.degraded || services.inference.degraded || hasDegradation || hasIncidents) {
status = 'degraded';
message = 'Service experiencing issues';
} else if (!isOperational) {
status = 'degraded';
message = 'Service status unknown';
}
// If status page check fails, fallback to endpoint check
if (!statusPageResponse.ok) {
const endpointStatus = await this.checkEndpoint('https://status.perplexity.ai/');
const apiEndpoint = 'https://api.perplexity.ai/v1/models';
const apiStatus = await this.checkEndpoint(apiEndpoint);
return {
status: endpointStatus === 'reachable' && apiStatus === 'reachable' ? 'operational' : 'degraded',
message: `Status page: ${endpointStatus}, API: ${apiStatus}`,
incidents: ['Note: Limited status information due to CORS restrictions'],
};
}
return {
status,
message,
incidents,
};
} catch (error) {
console.error('Error checking Perplexity status:', error);
// Fallback to basic endpoint check
const endpointStatus = await this.checkEndpoint('https://status.perplexity.ai/');
const apiEndpoint = 'https://api.perplexity.ai/v1/models';
const apiStatus = await this.checkEndpoint(apiEndpoint);
return {
status: endpointStatus === 'reachable' && apiStatus === 'reachable' ? 'operational' : 'degraded',
message: `Status page: ${endpointStatus}, API: ${apiStatus}`,
incidents: ['Note: Limited status information due to CORS restrictions'],
};
}
}
}

View File

@@ -0,0 +1,91 @@
import { BaseProviderChecker } from '~/components/@settings/tabs/providers/service-status/base-provider';
import type { StatusCheckResult } from '~/components/@settings/tabs/providers/service-status/types';
export class TogetherStatusChecker extends BaseProviderChecker {
async checkStatus(): Promise<StatusCheckResult> {
try {
// Check status page
const statusPageResponse = await fetch('https://status.together.ai/');
const text = await statusPageResponse.text();
// Check for specific Together status indicators
const isOperational = text.includes('All Systems Operational');
const hasIncidents = text.includes('Active Incidents');
const hasDegradation = text.includes('Degraded Performance');
const hasOutage = text.includes('Service Outage');
// Extract incidents
const incidents: string[] = [];
const incidentSection = text.match(/Past Incidents(.*?)(?=\n\n)/s);
if (incidentSection) {
const incidentLines = incidentSection[1]
.split('\n')
.map((line) => line.trim())
.filter((line) => line && line.includes('202')); // Only get dated incidents
incidents.push(...incidentLines.slice(0, 5));
}
// Check specific services
const services = {
api: {
operational: text.includes('API Service') && text.includes('Operational'),
degraded: text.includes('API Service') && text.includes('Degraded Performance'),
outage: text.includes('API Service') && text.includes('Service Outage'),
},
inference: {
operational: text.includes('Inference Service') && text.includes('Operational'),
degraded: text.includes('Inference Service') && text.includes('Degraded Performance'),
outage: text.includes('Inference Service') && text.includes('Service Outage'),
},
};
let status: StatusCheckResult['status'] = 'operational';
let message = 'All systems operational';
if (services.api.outage || services.inference.outage || hasOutage) {
status = 'down';
message = 'Service outage detected';
} else if (services.api.degraded || services.inference.degraded || hasDegradation || hasIncidents) {
status = 'degraded';
message = 'Service experiencing issues';
} else if (!isOperational) {
status = 'degraded';
message = 'Service status unknown';
}
// If status page check fails, fallback to endpoint check
if (!statusPageResponse.ok) {
const endpointStatus = await this.checkEndpoint('https://status.together.ai/');
const apiEndpoint = 'https://api.together.ai/v1/models';
const apiStatus = await this.checkEndpoint(apiEndpoint);
return {
status: endpointStatus === 'reachable' && apiStatus === 'reachable' ? 'operational' : 'degraded',
message: `Status page: ${endpointStatus}, API: ${apiStatus}`,
incidents: ['Note: Limited status information due to CORS restrictions'],
};
}
return {
status,
message,
incidents,
};
} catch (error) {
console.error('Error checking Together status:', error);
// Fallback to basic endpoint check
const endpointStatus = await this.checkEndpoint('https://status.together.ai/');
const apiEndpoint = 'https://api.together.ai/v1/models';
const apiStatus = await this.checkEndpoint(apiEndpoint);
return {
status: endpointStatus === 'reachable' && apiStatus === 'reachable' ? 'operational' : 'degraded',
message: `Status page: ${endpointStatus}, API: ${apiStatus}`,
incidents: ['Note: Limited status information due to CORS restrictions'],
};
}
}
}

View File

@@ -0,0 +1,40 @@
import { BaseProviderChecker } from '~/components/@settings/tabs/providers/service-status/base-provider';
import type { StatusCheckResult } from '~/components/@settings/tabs/providers/service-status/types';
export class XAIStatusChecker extends BaseProviderChecker {
async checkStatus(): Promise<StatusCheckResult> {
try {
/*
* Check API endpoint directly since XAI is a newer provider
* and may not have a public status page yet
*/
const apiEndpoint = 'https://api.xai.com/v1/models';
const apiStatus = await this.checkEndpoint(apiEndpoint);
// Check their website as a secondary indicator
const websiteStatus = await this.checkEndpoint('https://x.ai');
let status: StatusCheckResult['status'] = 'operational';
let message = 'All systems operational';
if (apiStatus !== 'reachable' || websiteStatus !== 'reachable') {
status = apiStatus !== 'reachable' ? 'down' : 'degraded';
message = apiStatus !== 'reachable' ? 'API appears to be down' : 'Service may be experiencing issues';
}
return {
status,
message,
incidents: [], // No public incident tracking available yet
};
} catch (error) {
console.error('Error checking XAI status:', error);
return {
status: 'degraded',
message: 'Unable to determine service status',
incidents: ['Note: Limited status information available'],
};
}
}
}

View File

@@ -0,0 +1,55 @@
import type { IconType } from 'react-icons';
export type ProviderName =
| 'AmazonBedrock'
| 'Cohere'
| 'Deepseek'
| 'Google'
| 'Groq'
| 'HuggingFace'
| 'Hyperbolic'
| 'Mistral'
| 'OpenRouter'
| 'Perplexity'
| 'Together'
| 'XAI';
export type ServiceStatus = {
provider: ProviderName;
status: 'operational' | 'degraded' | 'down';
lastChecked: string;
statusUrl?: string;
icon?: IconType;
message?: string;
responseTime?: number;
incidents?: string[];
};
export interface ProviderConfig {
statusUrl: string;
apiUrl: string;
headers: Record<string, string>;
testModel: string;
}
export type ApiResponse = {
error?: {
message: string;
};
message?: string;
model?: string;
models?: Array<{
id?: string;
name?: string;
}>;
data?: Array<{
id?: string;
name?: string;
}>;
};
export type StatusCheckResult = {
status: 'operational' | 'degraded' | 'down';
message: string;
incidents: string[];
};

View File

@@ -0,0 +1,886 @@
import React, { useEffect, useState, useCallback } from 'react';
import { motion } from 'framer-motion';
import { classNames } from '~/utils/classNames';
import { TbActivityHeartbeat } from 'react-icons/tb';
import { BsCheckCircleFill, BsXCircleFill, BsExclamationCircleFill } from 'react-icons/bs';
import { SiAmazon, SiGoogle, SiHuggingface, SiPerplexity, SiOpenai } from 'react-icons/si';
import { BsRobot, BsCloud } from 'react-icons/bs';
import { TbBrain } from 'react-icons/tb';
import { BiChip, BiCodeBlock } from 'react-icons/bi';
import { FaCloud, FaBrain } from 'react-icons/fa';
import type { IconType } from 'react-icons';
import { useSettings } from '~/lib/hooks/useSettings';
import { useToast } from '~/components/ui/use-toast';
// Types
type ProviderName =
| 'AmazonBedrock'
| 'Anthropic'
| 'Cohere'
| 'Deepseek'
| 'Google'
| 'Groq'
| 'HuggingFace'
| 'Mistral'
| 'OpenAI'
| 'OpenRouter'
| 'Perplexity'
| 'Together'
| 'XAI';
type ServiceStatus = {
provider: ProviderName;
status: 'operational' | 'degraded' | 'down';
lastChecked: string;
statusUrl?: string;
icon?: IconType;
message?: string;
responseTime?: number;
incidents?: string[];
};
type ProviderConfig = {
statusUrl: string;
apiUrl: string;
headers: Record<string, string>;
testModel: string;
};
// Types for API responses
type ApiResponse = {
error?: {
message: string;
};
message?: string;
model?: string;
models?: Array<{
id?: string;
name?: string;
}>;
data?: Array<{
id?: string;
name?: string;
}>;
};
// Constants
const PROVIDER_STATUS_URLS: Record<ProviderName, ProviderConfig> = {
OpenAI: {
statusUrl: 'https://status.openai.com/',
apiUrl: 'https://api.openai.com/v1/models',
headers: {
Authorization: 'Bearer $OPENAI_API_KEY',
},
testModel: 'gpt-3.5-turbo',
},
Anthropic: {
statusUrl: 'https://status.anthropic.com/',
apiUrl: 'https://api.anthropic.com/v1/messages',
headers: {
'x-api-key': '$ANTHROPIC_API_KEY',
'anthropic-version': '2024-02-29',
},
testModel: 'claude-3-sonnet-20240229',
},
Cohere: {
statusUrl: 'https://status.cohere.com/',
apiUrl: 'https://api.cohere.ai/v1/models',
headers: {
Authorization: 'Bearer $COHERE_API_KEY',
},
testModel: 'command',
},
Google: {
statusUrl: 'https://status.cloud.google.com/',
apiUrl: 'https://generativelanguage.googleapis.com/v1/models',
headers: {
'x-goog-api-key': '$GOOGLE_API_KEY',
},
testModel: 'gemini-pro',
},
HuggingFace: {
statusUrl: 'https://status.huggingface.co/',
apiUrl: 'https://api-inference.huggingface.co/models',
headers: {
Authorization: 'Bearer $HUGGINGFACE_API_KEY',
},
testModel: 'mistralai/Mixtral-8x7B-Instruct-v0.1',
},
Mistral: {
statusUrl: 'https://status.mistral.ai/',
apiUrl: 'https://api.mistral.ai/v1/models',
headers: {
Authorization: 'Bearer $MISTRAL_API_KEY',
},
testModel: 'mistral-tiny',
},
Perplexity: {
statusUrl: 'https://status.perplexity.com/',
apiUrl: 'https://api.perplexity.ai/v1/models',
headers: {
Authorization: 'Bearer $PERPLEXITY_API_KEY',
},
testModel: 'pplx-7b-chat',
},
Together: {
statusUrl: 'https://status.together.ai/',
apiUrl: 'https://api.together.xyz/v1/models',
headers: {
Authorization: 'Bearer $TOGETHER_API_KEY',
},
testModel: 'mistralai/Mixtral-8x7B-Instruct-v0.1',
},
AmazonBedrock: {
statusUrl: 'https://health.aws.amazon.com/health/status',
apiUrl: 'https://bedrock.us-east-1.amazonaws.com/models',
headers: {
Authorization: 'Bearer $AWS_BEDROCK_CONFIG',
},
testModel: 'anthropic.claude-3-sonnet-20240229-v1:0',
},
Groq: {
statusUrl: 'https://groqstatus.com/',
apiUrl: 'https://api.groq.com/v1/models',
headers: {
Authorization: 'Bearer $GROQ_API_KEY',
},
testModel: 'mixtral-8x7b-32768',
},
OpenRouter: {
statusUrl: 'https://status.openrouter.ai/',
apiUrl: 'https://openrouter.ai/api/v1/models',
headers: {
Authorization: 'Bearer $OPEN_ROUTER_API_KEY',
},
testModel: 'anthropic/claude-3-sonnet',
},
XAI: {
statusUrl: 'https://status.x.ai/',
apiUrl: 'https://api.x.ai/v1/models',
headers: {
Authorization: 'Bearer $XAI_API_KEY',
},
testModel: 'grok-1',
},
Deepseek: {
statusUrl: 'https://status.deepseek.com/',
apiUrl: 'https://api.deepseek.com/v1/models',
headers: {
Authorization: 'Bearer $DEEPSEEK_API_KEY',
},
testModel: 'deepseek-chat',
},
};
const PROVIDER_ICONS: Record<ProviderName, IconType> = {
AmazonBedrock: SiAmazon,
Anthropic: FaBrain,
Cohere: BiChip,
Google: SiGoogle,
Groq: BsCloud,
HuggingFace: SiHuggingface,
Mistral: TbBrain,
OpenAI: SiOpenai,
OpenRouter: FaCloud,
Perplexity: SiPerplexity,
Together: BsCloud,
XAI: BsRobot,
Deepseek: BiCodeBlock,
};
const ServiceStatusTab = () => {
const [serviceStatuses, setServiceStatuses] = useState<ServiceStatus[]>([]);
const [loading, setLoading] = useState(true);
const [lastRefresh, setLastRefresh] = useState<Date>(new Date());
const [testApiKey, setTestApiKey] = useState<string>('');
const [testProvider, setTestProvider] = useState<ProviderName | ''>('');
const [testingStatus, setTestingStatus] = useState<'idle' | 'testing' | 'success' | 'error'>('idle');
const settings = useSettings();
const { success, error } = useToast();
// Function to get the API key for a provider from environment variables
const getApiKey = useCallback(
(provider: ProviderName): string | null => {
if (!settings.providers) {
return null;
}
// Map provider names to environment variable names
const envKeyMap: Record<ProviderName, string> = {
OpenAI: 'OPENAI_API_KEY',
Anthropic: 'ANTHROPIC_API_KEY',
Cohere: 'COHERE_API_KEY',
Google: 'GOOGLE_GENERATIVE_AI_API_KEY',
HuggingFace: 'HuggingFace_API_KEY',
Mistral: 'MISTRAL_API_KEY',
Perplexity: 'PERPLEXITY_API_KEY',
Together: 'TOGETHER_API_KEY',
AmazonBedrock: 'AWS_BEDROCK_CONFIG',
Groq: 'GROQ_API_KEY',
OpenRouter: 'OPEN_ROUTER_API_KEY',
XAI: 'XAI_API_KEY',
Deepseek: 'DEEPSEEK_API_KEY',
};
const envKey = envKeyMap[provider];
if (!envKey) {
return null;
}
// Get the API key from environment variables
const apiKey = (import.meta.env[envKey] as string) || null;
// Special handling for providers with base URLs
if (provider === 'Together' && apiKey) {
const baseUrl = import.meta.env.TOGETHER_API_BASE_URL;
if (!baseUrl) {
return null;
}
}
return apiKey;
},
[settings.providers],
);
// Update provider configurations based on available API keys
const getProviderConfig = useCallback((provider: ProviderName): ProviderConfig | null => {
const config = PROVIDER_STATUS_URLS[provider];
if (!config) {
return null;
}
// Handle special cases for providers with base URLs
let updatedConfig = { ...config };
const togetherBaseUrl = import.meta.env.TOGETHER_API_BASE_URL;
if (provider === 'Together' && togetherBaseUrl) {
updatedConfig = {
...config,
apiUrl: `${togetherBaseUrl}/models`,
};
}
return updatedConfig;
}, []);
// Function to check if an API endpoint is accessible with model verification
const checkApiEndpoint = useCallback(
async (
url: string,
headers?: Record<string, string>,
testModel?: string,
): Promise<{ ok: boolean; status: number | string; message?: string; responseTime: number }> => {
try {
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), 10000);
const startTime = performance.now();
// Add common headers
const processedHeaders = {
'Content-Type': 'application/json',
...headers,
};
// First check if the API is accessible
const response = await fetch(url, {
method: 'GET',
headers: processedHeaders,
signal: controller.signal,
});
const endTime = performance.now();
const responseTime = endTime - startTime;
clearTimeout(timeoutId);
// Get response data
const data = (await response.json()) as ApiResponse;
// Special handling for different provider responses
if (!response.ok) {
let errorMessage = `API returned status: ${response.status}`;
// Handle provider-specific error messages
if (data.error?.message) {
errorMessage = data.error.message;
} else if (data.message) {
errorMessage = data.message;
}
return {
ok: false,
status: response.status,
message: errorMessage,
responseTime,
};
}
// Different providers have different model list formats
let models: string[] = [];
if (Array.isArray(data)) {
models = data.map((model: { id?: string; name?: string }) => model.id || model.name || '');
} else if (data.data && Array.isArray(data.data)) {
models = data.data.map((model) => model.id || model.name || '');
} else if (data.models && Array.isArray(data.models)) {
models = data.models.map((model) => model.id || model.name || '');
} else if (data.model) {
// Some providers return single model info
models = [data.model];
}
// For some providers, just having a successful response is enough
if (!testModel || models.length > 0) {
return {
ok: true,
status: response.status,
responseTime,
message: 'API key is valid',
};
}
// If a specific model was requested, verify it exists
if (testModel && !models.includes(testModel)) {
return {
ok: true, // Still mark as ok since API works
status: 'model_not_found',
message: `API key is valid (test model ${testModel} not found in ${models.length} available models)`,
responseTime,
};
}
return {
ok: true,
status: response.status,
message: 'API key is valid',
responseTime,
};
} catch (error) {
console.error(`Error checking API endpoint ${url}:`, error);
return {
ok: false,
status: error instanceof Error ? error.message : 'Unknown error',
message: error instanceof Error ? `Connection failed: ${error.message}` : 'Connection failed',
responseTime: 0,
};
}
},
[getApiKey],
);
// Function to fetch real status from provider status pages
const fetchPublicStatus = useCallback(
async (
provider: ProviderName,
): Promise<{
status: ServiceStatus['status'];
message?: string;
incidents?: string[];
}> => {
try {
// Due to CORS restrictions, we can only check if the endpoints are reachable
const checkEndpoint = async (url: string) => {
try {
const response = await fetch(url, {
mode: 'no-cors',
headers: {
Accept: 'text/html',
},
});
// With no-cors, we can only know if the request succeeded
return response.type === 'opaque' ? 'reachable' : 'unreachable';
} catch (error) {
console.error(`Error checking ${url}:`, error);
return 'unreachable';
}
};
switch (provider) {
case 'HuggingFace': {
const endpointStatus = await checkEndpoint('https://status.huggingface.co/');
// Check API endpoint as fallback
const apiEndpoint = 'https://api-inference.huggingface.co/models';
const apiStatus = await checkEndpoint(apiEndpoint);
return {
status: endpointStatus === 'reachable' && apiStatus === 'reachable' ? 'operational' : 'degraded',
message: `Status page: ${endpointStatus}, API: ${apiStatus}`,
incidents: ['Note: Limited status information due to CORS restrictions'],
};
}
case 'OpenAI': {
const endpointStatus = await checkEndpoint('https://status.openai.com/');
const apiEndpoint = 'https://api.openai.com/v1/models';
const apiStatus = await checkEndpoint(apiEndpoint);
return {
status: endpointStatus === 'reachable' && apiStatus === 'reachable' ? 'operational' : 'degraded',
message: `Status page: ${endpointStatus}, API: ${apiStatus}`,
incidents: ['Note: Limited status information due to CORS restrictions'],
};
}
case 'Google': {
const endpointStatus = await checkEndpoint('https://status.cloud.google.com/');
const apiEndpoint = 'https://generativelanguage.googleapis.com/v1/models';
const apiStatus = await checkEndpoint(apiEndpoint);
return {
status: endpointStatus === 'reachable' && apiStatus === 'reachable' ? 'operational' : 'degraded',
message: `Status page: ${endpointStatus}, API: ${apiStatus}`,
incidents: ['Note: Limited status information due to CORS restrictions'],
};
}
// Similar pattern for other providers...
default:
return {
status: 'operational',
message: 'Basic reachability check only',
incidents: ['Note: Limited status information due to CORS restrictions'],
};
}
} catch (error) {
console.error(`Error fetching status for ${provider}:`, error);
return {
status: 'degraded',
message: 'Unable to fetch status due to CORS restrictions',
incidents: ['Error: Unable to check service status'],
};
}
},
[],
);
// Function to fetch status for a provider with retries
const fetchProviderStatus = useCallback(
async (provider: ProviderName, config: ProviderConfig): Promise<ServiceStatus> => {
const MAX_RETRIES = 2;
const RETRY_DELAY = 2000; // 2 seconds
const attemptCheck = async (attempt: number): Promise<ServiceStatus> => {
try {
// First check the public status page if available
const hasPublicStatus = [
'Anthropic',
'OpenAI',
'Google',
'HuggingFace',
'Mistral',
'Groq',
'Perplexity',
'Together',
].includes(provider);
if (hasPublicStatus) {
const publicStatus = await fetchPublicStatus(provider);
return {
provider,
status: publicStatus.status,
lastChecked: new Date().toISOString(),
statusUrl: config.statusUrl,
icon: PROVIDER_ICONS[provider],
message: publicStatus.message,
incidents: publicStatus.incidents,
};
}
// For other providers, we'll show status but mark API check as separate
const apiKey = getApiKey(provider);
const providerConfig = getProviderConfig(provider);
if (!apiKey || !providerConfig) {
return {
provider,
status: 'operational',
lastChecked: new Date().toISOString(),
statusUrl: config.statusUrl,
icon: PROVIDER_ICONS[provider],
message: !apiKey
? 'Status operational (API key needed for usage)'
: 'Status operational (configuration needed for usage)',
incidents: [],
};
}
// If we have API access, let's verify that too
const { ok, status, message, responseTime } = await checkApiEndpoint(
providerConfig.apiUrl,
providerConfig.headers,
providerConfig.testModel,
);
if (!ok && attempt < MAX_RETRIES) {
await new Promise((resolve) => setTimeout(resolve, RETRY_DELAY));
return attemptCheck(attempt + 1);
}
return {
provider,
status: ok ? 'operational' : 'degraded',
lastChecked: new Date().toISOString(),
statusUrl: providerConfig.statusUrl,
icon: PROVIDER_ICONS[provider],
message: ok ? 'Service and API operational' : `Service operational (API: ${message || status})`,
responseTime,
incidents: [],
};
} catch (error) {
console.error(`Error fetching status for ${provider} (attempt ${attempt}):`, error);
if (attempt < MAX_RETRIES) {
await new Promise((resolve) => setTimeout(resolve, RETRY_DELAY));
return attemptCheck(attempt + 1);
}
return {
provider,
status: 'degraded',
lastChecked: new Date().toISOString(),
statusUrl: config.statusUrl,
icon: PROVIDER_ICONS[provider],
message: 'Service operational (Status check error)',
responseTime: 0,
incidents: [],
};
}
};
return attemptCheck(1);
},
[checkApiEndpoint, getApiKey, getProviderConfig, fetchPublicStatus],
);
// Memoize the fetchAllStatuses function
const fetchAllStatuses = useCallback(async () => {
try {
setLoading(true);
const statuses = await Promise.all(
Object.entries(PROVIDER_STATUS_URLS).map(([provider, config]) =>
fetchProviderStatus(provider as ProviderName, config),
),
);
setServiceStatuses(statuses.sort((a, b) => a.provider.localeCompare(b.provider)));
setLastRefresh(new Date());
success('Service statuses updated successfully');
} catch (err) {
console.error('Error fetching all statuses:', err);
error('Failed to update service statuses');
} finally {
setLoading(false);
}
}, [fetchProviderStatus, success, error]);
useEffect(() => {
fetchAllStatuses();
// Refresh status every 2 minutes
const interval = setInterval(fetchAllStatuses, 2 * 60 * 1000);
return () => clearInterval(interval);
}, [fetchAllStatuses]);
// Function to test an API key
const testApiKeyForProvider = useCallback(
async (provider: ProviderName, apiKey: string) => {
try {
setTestingStatus('testing');
const config = PROVIDER_STATUS_URLS[provider];
if (!config) {
throw new Error('Provider configuration not found');
}
const headers = { ...config.headers };
// Replace the placeholder API key with the test key
Object.keys(headers).forEach((key) => {
if (headers[key].startsWith('$')) {
headers[key] = headers[key].replace(/\$.*/, apiKey);
}
});
// Special handling for certain providers
switch (provider) {
case 'Anthropic':
headers['anthropic-version'] = '2024-02-29';
break;
case 'OpenAI':
if (!headers.Authorization?.startsWith('Bearer ')) {
headers.Authorization = `Bearer ${apiKey}`;
}
break;
case 'Google': {
// Google uses the API key directly in the URL
const googleUrl = `${config.apiUrl}?key=${apiKey}`;
const result = await checkApiEndpoint(googleUrl, {}, config.testModel);
if (result.ok) {
setTestingStatus('success');
success('API key is valid!');
} else {
setTestingStatus('error');
error(`API key test failed: ${result.message}`);
}
return;
}
}
const { ok, message } = await checkApiEndpoint(config.apiUrl, headers, config.testModel);
if (ok) {
setTestingStatus('success');
success('API key is valid!');
} else {
setTestingStatus('error');
error(`API key test failed: ${message}`);
}
} catch (err: unknown) {
setTestingStatus('error');
error('Failed to test API key: ' + (err instanceof Error ? err.message : 'Unknown error'));
} finally {
// Reset testing status after a delay
setTimeout(() => setTestingStatus('idle'), 3000);
}
},
[checkApiEndpoint, success, error],
);
const getStatusColor = (status: ServiceStatus['status']) => {
switch (status) {
case 'operational':
return 'text-green-500';
case 'degraded':
return 'text-yellow-500';
case 'down':
return 'text-red-500';
default:
return 'text-gray-500';
}
};
const getStatusIcon = (status: ServiceStatus['status']) => {
switch (status) {
case 'operational':
return <BsCheckCircleFill className="w-4 h-4" />;
case 'degraded':
return <BsExclamationCircleFill className="w-4 h-4" />;
case 'down':
return <BsXCircleFill className="w-4 h-4" />;
default:
return <BsXCircleFill className="w-4 h-4" />;
}
};
return (
<div className="space-y-6">
<motion.div
className="space-y-4"
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ duration: 0.3 }}
>
<div className="flex items-center justify-between gap-2 mt-8 mb-4">
<div className="flex items-center gap-2">
<div
className={classNames(
'w-8 h-8 flex items-center justify-center rounded-lg',
'bg-bolt-elements-background-depth-3',
'text-purple-500',
)}
>
<TbActivityHeartbeat className="w-5 h-5" />
</div>
<div>
<h4 className="text-md font-medium text-bolt-elements-textPrimary">Service Status</h4>
<p className="text-sm text-bolt-elements-textSecondary">
Monitor and test the operational status of cloud LLM providers
</p>
</div>
</div>
<div className="flex items-center gap-2">
<span className="text-sm text-bolt-elements-textSecondary">
Last updated: {lastRefresh.toLocaleTimeString()}
</span>
<button
onClick={() => fetchAllStatuses()}
className={classNames(
'px-3 py-1.5 rounded-lg text-sm',
'bg-bolt-elements-background-depth-3 hover:bg-bolt-elements-background-depth-4',
'text-bolt-elements-textPrimary',
'transition-all duration-200',
'flex items-center gap-2',
loading ? 'opacity-50 cursor-not-allowed' : '',
)}
disabled={loading}
>
<div className={`i-ph:arrows-clockwise w-4 h-4 ${loading ? 'animate-spin' : ''}`} />
<span>{loading ? 'Refreshing...' : 'Refresh'}</span>
</button>
</div>
</div>
{/* API Key Test Section */}
<div className="p-4 bg-bolt-elements-background-depth-2 rounded-lg">
<h5 className="text-sm font-medium text-bolt-elements-textPrimary mb-2">Test API Key</h5>
<div className="flex gap-2">
<select
value={testProvider}
onChange={(e) => setTestProvider(e.target.value as ProviderName)}
className={classNames(
'flex-1 px-3 py-1.5 rounded-lg text-sm max-w-[200px]',
'bg-bolt-elements-background-depth-3 border border-bolt-elements-borderColor',
'text-bolt-elements-textPrimary',
'focus:outline-none focus:ring-2 focus:ring-purple-500/30',
)}
>
<option value="">Select Provider</option>
{Object.keys(PROVIDER_STATUS_URLS).map((provider) => (
<option key={provider} value={provider}>
{provider}
</option>
))}
</select>
<input
type="password"
value={testApiKey}
onChange={(e) => setTestApiKey(e.target.value)}
placeholder="Enter API key to test"
className={classNames(
'flex-1 px-3 py-1.5 rounded-lg text-sm',
'bg-bolt-elements-background-depth-3 border border-bolt-elements-borderColor',
'text-bolt-elements-textPrimary placeholder-bolt-elements-textTertiary',
'focus:outline-none focus:ring-2 focus:ring-purple-500/30',
)}
/>
<button
onClick={() =>
testProvider && testApiKey && testApiKeyForProvider(testProvider as ProviderName, testApiKey)
}
disabled={!testProvider || !testApiKey || testingStatus === 'testing'}
className={classNames(
'px-4 py-1.5 rounded-lg text-sm',
'bg-purple-500 hover:bg-purple-600',
'text-white',
'transition-all duration-200',
'flex items-center gap-2',
!testProvider || !testApiKey || testingStatus === 'testing' ? 'opacity-50 cursor-not-allowed' : '',
)}
>
{testingStatus === 'testing' ? (
<>
<div className="i-ph:spinner-gap w-4 h-4 animate-spin" />
<span>Testing...</span>
</>
) : (
<>
<div className="i-ph:key w-4 h-4" />
<span>Test Key</span>
</>
)}
</button>
</div>
</div>
{/* Status Grid */}
{loading && serviceStatuses.length === 0 ? (
<div className="text-center py-8 text-bolt-elements-textSecondary">Loading service statuses...</div>
) : (
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
{serviceStatuses.map((service, index) => (
<motion.div
key={service.provider}
className={classNames(
'bg-bolt-elements-background-depth-2',
'hover:bg-bolt-elements-background-depth-3',
'transition-all duration-200',
'relative overflow-hidden rounded-lg',
)}
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ delay: index * 0.1 }}
whileHover={{ scale: 1.02 }}
>
<div
className={classNames('block p-4', service.statusUrl ? 'cursor-pointer' : '')}
onClick={() => service.statusUrl && window.open(service.statusUrl, '_blank')}
>
<div className="flex items-center justify-between gap-4">
<div className="flex items-center gap-3">
{service.icon && (
<div
className={classNames(
'w-8 h-8 flex items-center justify-center rounded-lg',
'bg-bolt-elements-background-depth-3',
getStatusColor(service.status),
)}
>
{React.createElement(service.icon, {
className: 'w-5 h-5',
})}
</div>
)}
<div>
<h4 className="text-sm font-medium text-bolt-elements-textPrimary">{service.provider}</h4>
<div className="space-y-1">
<p className="text-xs text-bolt-elements-textSecondary">
Last checked: {new Date(service.lastChecked).toLocaleTimeString()}
</p>
{service.responseTime && (
<p className="text-xs text-bolt-elements-textTertiary">
Response time: {Math.round(service.responseTime)}ms
</p>
)}
{service.message && (
<p className="text-xs text-bolt-elements-textTertiary">{service.message}</p>
)}
</div>
</div>
</div>
<div className={classNames('flex items-center gap-2', getStatusColor(service.status))}>
<span className="text-sm capitalize">{service.status}</span>
{getStatusIcon(service.status)}
</div>
</div>
{service.incidents && service.incidents.length > 0 && (
<div className="mt-2 border-t border-bolt-elements-borderColor pt-2">
<p className="text-xs font-medium text-bolt-elements-textSecondary mb-1">Recent Incidents:</p>
<ul className="text-xs text-bolt-elements-textTertiary space-y-1">
{service.incidents.map((incident, i) => (
<li key={i}>{incident}</li>
))}
</ul>
</div>
)}
</div>
</motion.div>
))}
</div>
)}
</motion.div>
</div>
);
};
// Add tab metadata
ServiceStatusTab.tabMetadata = {
icon: 'i-ph:activity-bold',
description: 'Monitor and test LLM provider service status',
category: 'services',
};
export default ServiceStatusTab;

View File

@@ -0,0 +1,215 @@
import React, { useState, useEffect } from 'react';
import { motion } from 'framer-motion';
import { toast } from 'react-toastify';
import { classNames } from '~/utils/classNames';
import { Switch } from '~/components/ui/Switch';
import type { UserProfile } from '~/components/@settings/core/types';
import { isMac } from '~/utils/os';
// Helper to get modifier key symbols/text
const getModifierSymbol = (modifier: string): string => {
switch (modifier) {
case 'meta':
return isMac ? '⌘' : 'Win';
case 'alt':
return isMac ? '⌥' : 'Alt';
case 'shift':
return '⇧';
default:
return modifier;
}
};
export default function SettingsTab() {
const [currentTimezone, setCurrentTimezone] = useState('');
const [settings, setSettings] = useState<UserProfile>(() => {
const saved = localStorage.getItem('bolt_user_profile');
return saved
? JSON.parse(saved)
: {
notifications: true,
language: 'en',
timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
};
});
useEffect(() => {
setCurrentTimezone(Intl.DateTimeFormat().resolvedOptions().timeZone);
}, []);
// Save settings automatically when they change
useEffect(() => {
try {
// Get existing profile data
const existingProfile = JSON.parse(localStorage.getItem('bolt_user_profile') || '{}');
// Merge with new settings
const updatedProfile = {
...existingProfile,
notifications: settings.notifications,
language: settings.language,
timezone: settings.timezone,
};
localStorage.setItem('bolt_user_profile', JSON.stringify(updatedProfile));
toast.success('Settings updated');
} catch (error) {
console.error('Error saving settings:', error);
toast.error('Failed to update settings');
}
}, [settings]);
return (
<div className="space-y-4">
{/* Language & Notifications */}
<motion.div
className="bg-white dark:bg-[#0A0A0A] rounded-lg shadow-sm dark:shadow-none p-4 space-y-4"
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ delay: 0.1 }}
>
<div className="flex items-center gap-2 mb-4">
<div className="i-ph:palette-fill w-4 h-4 text-purple-500" />
<span className="text-sm font-medium text-bolt-elements-textPrimary">Preferences</span>
</div>
<div>
<div className="flex items-center gap-2 mb-2">
<div className="i-ph:translate-fill w-4 h-4 text-bolt-elements-textSecondary" />
<label className="block text-sm text-bolt-elements-textSecondary">Language</label>
</div>
<select
value={settings.language}
onChange={(e) => setSettings((prev) => ({ ...prev, language: e.target.value }))}
className={classNames(
'w-full px-3 py-2 rounded-lg text-sm',
'bg-[#FAFAFA] dark:bg-[#0A0A0A]',
'border border-[#E5E5E5] dark:border-[#1A1A1A]',
'text-bolt-elements-textPrimary',
'focus:outline-none focus:ring-2 focus:ring-purple-500/30',
'transition-all duration-200',
)}
>
<option value="en">English</option>
<option value="es">Español</option>
<option value="fr">Français</option>
<option value="de">Deutsch</option>
<option value="it">Italiano</option>
<option value="pt">Português</option>
<option value="ru">Русский</option>
<option value="zh"></option>
<option value="ja"></option>
<option value="ko"></option>
</select>
</div>
<div>
<div className="flex items-center gap-2 mb-2">
<div className="i-ph:bell-fill w-4 h-4 text-bolt-elements-textSecondary" />
<label className="block text-sm text-bolt-elements-textSecondary">Notifications</label>
</div>
<div className="flex items-center justify-between">
<span className="text-sm text-bolt-elements-textSecondary">
{settings.notifications ? 'Notifications are enabled' : 'Notifications are disabled'}
</span>
<Switch
checked={settings.notifications}
onCheckedChange={(checked) => {
// Update local state
setSettings((prev) => ({ ...prev, notifications: checked }));
// Update localStorage immediately
const existingProfile = JSON.parse(localStorage.getItem('bolt_user_profile') || '{}');
const updatedProfile = {
...existingProfile,
notifications: checked,
};
localStorage.setItem('bolt_user_profile', JSON.stringify(updatedProfile));
// Dispatch storage event for other components
window.dispatchEvent(
new StorageEvent('storage', {
key: 'bolt_user_profile',
newValue: JSON.stringify(updatedProfile),
}),
);
toast.success(`Notifications ${checked ? 'enabled' : 'disabled'}`);
}}
/>
</div>
</div>
</motion.div>
{/* Timezone */}
<motion.div
className="bg-white dark:bg-[#0A0A0A] rounded-lg shadow-sm dark:shadow-none p-4"
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ delay: 0.2 }}
>
<div className="flex items-center gap-2 mb-4">
<div className="i-ph:clock-fill w-4 h-4 text-purple-500" />
<span className="text-sm font-medium text-bolt-elements-textPrimary">Time Settings</span>
</div>
<div>
<div className="flex items-center gap-2 mb-2">
<div className="i-ph:globe-fill w-4 h-4 text-bolt-elements-textSecondary" />
<label className="block text-sm text-bolt-elements-textSecondary">Timezone</label>
</div>
<select
value={settings.timezone}
onChange={(e) => setSettings((prev) => ({ ...prev, timezone: e.target.value }))}
className={classNames(
'w-full px-3 py-2 rounded-lg text-sm',
'bg-[#FAFAFA] dark:bg-[#0A0A0A]',
'border border-[#E5E5E5] dark:border-[#1A1A1A]',
'text-bolt-elements-textPrimary',
'focus:outline-none focus:ring-2 focus:ring-purple-500/30',
'transition-all duration-200',
)}
>
<option value={currentTimezone}>{currentTimezone}</option>
</select>
</div>
</motion.div>
{/* Simplified Keyboard Shortcuts */}
<motion.div
className="bg-white dark:bg-[#0A0A0A] rounded-lg shadow-sm dark:shadow-none p-4"
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ delay: 0.3 }}
>
<div className="flex items-center gap-2 mb-4">
<div className="i-ph:keyboard-fill w-4 h-4 text-purple-500" />
<span className="text-sm font-medium text-bolt-elements-textPrimary">Keyboard Shortcuts</span>
</div>
<div className="space-y-2">
<div className="flex items-center justify-between p-2 rounded-lg bg-[#FAFAFA] dark:bg-[#1A1A1A]">
<div className="flex flex-col">
<span className="text-sm text-bolt-elements-textPrimary">Toggle Theme</span>
<span className="text-xs text-bolt-elements-textSecondary">Switch between light and dark mode</span>
</div>
<div className="flex items-center gap-1">
<kbd className="px-2 py-1 text-xs font-semibold text-bolt-elements-textSecondary bg-white dark:bg-[#0A0A0A] border border-[#E5E5E5] dark:border-[#1A1A1A] rounded shadow-sm">
{getModifierSymbol('meta')}
</kbd>
<kbd className="px-2 py-1 text-xs font-semibold text-bolt-elements-textSecondary bg-white dark:bg-[#0A0A0A] border border-[#E5E5E5] dark:border-[#1A1A1A] rounded shadow-sm">
{getModifierSymbol('alt')}
</kbd>
<kbd className="px-2 py-1 text-xs font-semibold text-bolt-elements-textSecondary bg-white dark:bg-[#0A0A0A] border border-[#E5E5E5] dark:border-[#1A1A1A] rounded shadow-sm">
{getModifierSymbol('shift')}
</kbd>
<kbd className="px-2 py-1 text-xs font-semibold text-bolt-elements-textSecondary bg-white dark:bg-[#0A0A0A] border border-[#E5E5E5] dark:border-[#1A1A1A] rounded shadow-sm">
D
</kbd>
</div>
</div>
</div>
</motion.div>
</div>
);
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,628 @@
import React, { useState, useEffect } from 'react';
import { motion } from 'framer-motion';
import { useSettings } from '~/lib/hooks/useSettings';
import { logStore } from '~/lib/stores/logs';
import { toast } from 'react-toastify';
import { Dialog, DialogRoot, DialogTitle, DialogDescription, DialogButton } from '~/components/ui/Dialog';
import { classNames } from '~/utils/classNames';
import { Markdown } from '~/components/chat/Markdown';
interface UpdateProgress {
stage: 'fetch' | 'pull' | 'install' | 'build' | 'complete';
message: string;
progress?: number;
error?: string;
details?: {
changedFiles?: string[];
additions?: number;
deletions?: number;
commitMessages?: string[];
totalSize?: string;
currentCommit?: string;
remoteCommit?: string;
updateReady?: boolean;
changelog?: string;
compareUrl?: string;
};
}
interface UpdateSettings {
autoUpdate: boolean;
notifyInApp: boolean;
checkInterval: number;
}
const ProgressBar = ({ progress }: { progress: number }) => (
<div className="w-full h-2 bg-gray-200 rounded-full overflow-hidden">
<motion.div
className="h-full bg-blue-500"
initial={{ width: 0 }}
animate={{ width: `${progress}%` }}
transition={{ duration: 0.3 }}
/>
</div>
);
const UpdateProgressDisplay = ({ progress }: { progress: UpdateProgress }) => (
<div className="mt-4 space-y-2">
<div className="flex justify-between items-center">
<span className="text-sm font-medium">{progress.message}</span>
<span className="text-sm text-gray-500">{progress.progress}%</span>
</div>
<ProgressBar progress={progress.progress || 0} />
{progress.details && (
<div className="mt-2 text-sm text-gray-600">
{progress.details.changedFiles && progress.details.changedFiles.length > 0 && (
<div className="mt-4">
<div className="font-medium mb-2">Changed Files:</div>
<div className="space-y-2">
{/* Group files by type */}
{['Modified', 'Added', 'Deleted'].map((type) => {
const filesOfType = progress.details?.changedFiles?.filter((file) => file.startsWith(type)) || [];
if (filesOfType.length === 0) {
return null;
}
return (
<div key={type} className="space-y-1">
<div
className={classNames('text-sm font-medium', {
'text-blue-500': type === 'Modified',
'text-green-500': type === 'Added',
'text-red-500': type === 'Deleted',
})}
>
{type} ({filesOfType.length})
</div>
<div className="pl-4 space-y-1">
{filesOfType.map((file, index) => {
const fileName = file.split(': ')[1];
return (
<div key={index} className="text-sm text-bolt-elements-textSecondary flex items-center gap-2">
<div
className={classNames('w-4 h-4', {
'i-ph:pencil-simple': type === 'Modified',
'i-ph:plus': type === 'Added',
'i-ph:trash': type === 'Deleted',
'text-blue-500': type === 'Modified',
'text-green-500': type === 'Added',
'text-red-500': type === 'Deleted',
})}
/>
<span className="font-mono text-xs">{fileName}</span>
</div>
);
})}
</div>
</div>
);
})}
</div>
</div>
)}
{progress.details.totalSize && <div className="mt-1">Total size: {progress.details.totalSize}</div>}
{progress.details.additions !== undefined && progress.details.deletions !== undefined && (
<div className="mt-1">
Changes: <span className="text-green-600">+{progress.details.additions}</span>{' '}
<span className="text-red-600">-{progress.details.deletions}</span>
</div>
)}
{progress.details.currentCommit && progress.details.remoteCommit && (
<div className="mt-1">
Updating from {progress.details.currentCommit} to {progress.details.remoteCommit}
</div>
)}
</div>
)}
</div>
);
const UpdateTab = () => {
const { isLatestBranch } = useSettings();
const [isChecking, setIsChecking] = useState(false);
const [error, setError] = useState<string | null>(null);
const [updateSettings, setUpdateSettings] = useState<UpdateSettings>(() => {
const stored = localStorage.getItem('update_settings');
return stored
? JSON.parse(stored)
: {
autoUpdate: false,
notifyInApp: true,
checkInterval: 24,
};
});
const [showUpdateDialog, setShowUpdateDialog] = useState(false);
const [updateProgress, setUpdateProgress] = useState<UpdateProgress | null>(null);
useEffect(() => {
localStorage.setItem('update_settings', JSON.stringify(updateSettings));
}, [updateSettings]);
const checkForUpdates = async () => {
console.log('Starting update check...');
setIsChecking(true);
setError(null);
setUpdateProgress(null);
try {
const branchToCheck = isLatestBranch ? 'main' : 'stable';
// Start the update check with streaming progress
const response = await fetch('/api/update', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
branch: branchToCheck,
autoUpdate: updateSettings.autoUpdate,
}),
});
if (!response.ok) {
throw new Error(`Update check failed: ${response.statusText}`);
}
const reader = response.body?.getReader();
if (!reader) {
throw new Error('No response stream available');
}
// Read the stream
while (true) {
const { done, value } = await reader.read();
if (done) {
break;
}
// Convert the chunk to text and parse the JSON
const chunk = new TextDecoder().decode(value);
const lines = chunk.split('\n').filter(Boolean);
for (const line of lines) {
try {
const progress = JSON.parse(line) as UpdateProgress;
setUpdateProgress(progress);
if (progress.error) {
setError(progress.error);
}
// If we're done, update the UI accordingly
if (progress.stage === 'complete') {
setIsChecking(false);
if (!progress.error) {
// Update check completed
toast.success('Update check completed');
// Show update dialog only if there are changes and auto-update is disabled
if (progress.details?.changedFiles?.length && progress.details.updateReady) {
setShowUpdateDialog(true);
}
}
}
} catch (e) {
console.error('Error parsing progress update:', e);
}
}
}
} catch (error) {
setError(error instanceof Error ? error.message : 'Unknown error occurred');
logStore.logWarning('Update Check Failed', {
type: 'update',
message: error instanceof Error ? error.message : 'Unknown error occurred',
});
} finally {
setIsChecking(false);
}
};
const handleUpdate = async () => {
setShowUpdateDialog(false);
try {
const branchToCheck = isLatestBranch ? 'main' : 'stable';
// Start the update with autoUpdate set to true to force the update
const response = await fetch('/api/update', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
branch: branchToCheck,
autoUpdate: true,
}),
});
if (!response.ok) {
throw new Error(`Update failed: ${response.statusText}`);
}
// Handle the update progress stream
const reader = response.body?.getReader();
if (!reader) {
throw new Error('No response stream available');
}
while (true) {
const { done, value } = await reader.read();
if (done) {
break;
}
const chunk = new TextDecoder().decode(value);
const lines = chunk.split('\n').filter(Boolean);
for (const line of lines) {
try {
const progress = JSON.parse(line) as UpdateProgress;
setUpdateProgress(progress);
if (progress.error) {
setError(progress.error);
toast.error('Update failed');
}
if (progress.stage === 'complete' && !progress.error) {
toast.success('Update completed successfully');
}
} catch (e) {
console.error('Error parsing update progress:', e);
}
}
}
} catch (error) {
setError(error instanceof Error ? error.message : 'Unknown error occurred');
toast.error('Update failed');
}
};
return (
<div className="flex flex-col gap-6">
<motion.div
className="flex items-center gap-3"
initial={{ opacity: 0, y: -20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ duration: 0.3 }}
>
<div className="i-ph:arrow-circle-up text-xl text-purple-500" />
<div>
<h3 className="text-lg font-medium text-bolt-elements-textPrimary">Updates</h3>
<p className="text-sm text-bolt-elements-textSecondary">Check for and manage application updates</p>
</div>
</motion.div>
{/* Update Settings Card */}
<motion.div
className="p-6 rounded-xl bg-white dark:bg-[#0A0A0A] border border-[#E5E5E5] dark:border-[#1A1A1A]"
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ duration: 0.3, delay: 0.1 }}
>
<div className="flex items-center gap-3 mb-6">
<div className="i-ph:gear text-purple-500 w-5 h-5" />
<h3 className="text-lg font-medium text-bolt-elements-textPrimary">Update Settings</h3>
</div>
<div className="space-y-4">
<div className="flex items-center justify-between">
<div>
<span className="text-sm text-bolt-elements-textPrimary">Automatic Updates</span>
<p className="text-xs text-bolt-elements-textSecondary">
Automatically check and apply updates when available
</p>
</div>
<button
onClick={() => setUpdateSettings((prev) => ({ ...prev, autoUpdate: !prev.autoUpdate }))}
className={classNames(
'relative inline-flex h-6 w-11 items-center rounded-full transition-colors',
updateSettings.autoUpdate ? 'bg-purple-500' : 'bg-gray-200 dark:bg-gray-700',
)}
>
<span
className={classNames(
'inline-block h-4 w-4 transform rounded-full bg-white transition-transform',
updateSettings.autoUpdate ? 'translate-x-6' : 'translate-x-1',
)}
/>
</button>
</div>
<div className="flex items-center justify-between">
<div>
<span className="text-sm text-bolt-elements-textPrimary">In-App Notifications</span>
<p className="text-xs text-bolt-elements-textSecondary">Show notifications when updates are available</p>
</div>
<button
onClick={() => setUpdateSettings((prev) => ({ ...prev, notifyInApp: !prev.notifyInApp }))}
className={classNames(
'relative inline-flex h-6 w-11 items-center rounded-full transition-colors',
updateSettings.notifyInApp ? 'bg-purple-500' : 'bg-gray-200 dark:bg-gray-700',
)}
>
<span
className={classNames(
'inline-block h-4 w-4 transform rounded-full bg-white transition-transform',
updateSettings.notifyInApp ? 'translate-x-6' : 'translate-x-1',
)}
/>
</button>
</div>
<div className="flex items-center justify-between">
<div>
<span className="text-sm text-bolt-elements-textPrimary">Check Interval</span>
<p className="text-xs text-bolt-elements-textSecondary">How often to check for updates</p>
</div>
<select
value={updateSettings.checkInterval}
onChange={(e) => setUpdateSettings((prev) => ({ ...prev, checkInterval: Number(e.target.value) }))}
className={classNames(
'px-3 py-2 rounded-lg text-sm',
'bg-[#F5F5F5] dark:bg-[#1A1A1A]',
'border border-[#E5E5E5] dark:border-[#1A1A1A]',
'text-bolt-elements-textPrimary',
'hover:bg-[#E5E5E5] dark:hover:bg-[#2A2A2A]',
'transition-colors duration-200',
)}
>
<option value="6">6 hours</option>
<option value="12">12 hours</option>
<option value="24">24 hours</option>
<option value="48">48 hours</option>
</select>
</div>
</div>
</motion.div>
{/* Update Status Card */}
<motion.div
className="p-6 rounded-xl bg-white dark:bg-[#0A0A0A] border border-[#E5E5E5] dark:border-[#1A1A1A]"
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ duration: 0.3, delay: 0.2 }}
>
<div className="flex items-center justify-between mb-6">
<div className="flex items-center gap-3">
<div className="i-ph:arrows-clockwise text-purple-500 w-5 h-5" />
<h3 className="text-lg font-medium text-bolt-elements-textPrimary">Update Status</h3>
</div>
<div className="flex items-center gap-2">
{updateProgress?.details?.updateReady && !updateSettings.autoUpdate && (
<button
onClick={handleUpdate}
className={classNames(
'flex items-center gap-2 px-4 py-2 rounded-lg text-sm',
'bg-purple-500 text-white',
'hover:bg-purple-600',
'transition-colors duration-200',
)}
>
<div className="i-ph:arrow-circle-up w-4 h-4" />
Update Now
</button>
)}
<button
onClick={() => {
setError(null);
checkForUpdates();
}}
className={classNames(
'flex items-center gap-2 px-4 py-2 rounded-lg text-sm',
'bg-[#F5F5F5] dark:bg-[#1A1A1A]',
'hover:bg-purple-500/10 hover:text-purple-500',
'dark:hover:bg-purple-500/20 dark:hover:text-purple-500',
'text-bolt-elements-textPrimary',
'transition-colors duration-200',
'disabled:opacity-50 disabled:cursor-not-allowed',
)}
disabled={isChecking}
>
{isChecking ? (
<div className="flex items-center gap-2">
<motion.div
animate={{ rotate: 360 }}
transition={{ duration: 1, repeat: Infinity, ease: 'linear' }}
className="i-ph:arrows-clockwise w-4 h-4"
/>
Checking...
</div>
) : (
<>
<div className="i-ph:arrows-clockwise w-4 h-4" />
Check for Updates
</>
)}
</button>
</div>
</div>
{/* Show progress information */}
{updateProgress && <UpdateProgressDisplay progress={updateProgress} />}
{error && <div className="mt-4 p-4 bg-red-100 text-red-700 rounded">{error}</div>}
{/* Show update source information */}
{updateProgress?.details?.currentCommit && updateProgress?.details?.remoteCommit && (
<div className="mt-4 text-sm text-bolt-elements-textSecondary">
<div className="flex items-center justify-between">
<div>
<p>
Updates are fetched from: <span className="font-mono">stackblitz-labs/bolt.diy</span> (Slate upstream) (
{isLatestBranch ? 'main' : 'stable'} branch)
</p>
<p className="mt-1">
Current version: <span className="font-mono">{updateProgress.details.currentCommit}</span>
<span className="mx-2"></span>
Latest version: <span className="font-mono">{updateProgress.details.remoteCommit}</span>
</p>
</div>
{updateProgress?.details?.compareUrl && (
<a
href={updateProgress.details.compareUrl}
target="_blank"
rel="noopener noreferrer"
className={classNames(
'flex items-center gap-2 px-4 py-2 rounded-lg text-sm',
'bg-[#F5F5F5] dark:bg-[#1A1A1A]',
'hover:bg-purple-500/10 hover:text-purple-500',
'dark:hover:bg-purple-500/20 dark:hover:text-purple-500',
'text-bolt-elements-textPrimary',
'transition-colors duration-200',
'w-fit',
)}
>
<div className="i-ph:github-logo w-4 h-4" />
View Changes on GitHub
</a>
)}
</div>
{updateProgress?.details?.additions !== undefined && updateProgress?.details?.deletions !== undefined && (
<div className="mt-2 flex items-center gap-2">
<div className="i-ph:git-diff text-purple-500 w-4 h-4" />
Changes: <span className="text-green-600">+{updateProgress.details.additions}</span>{' '}
<span className="text-red-600">-{updateProgress.details.deletions}</span>
</div>
)}
</div>
)}
{/* Add this before the changed files section */}
{updateProgress?.details?.changelog && (
<div className="mb-6">
<div className="flex items-center gap-2 mb-2">
<div className="i-ph:scroll text-purple-500 w-5 h-5" />
<p className="font-medium">Changelog</p>
</div>
<div className="bg-[#F5F5F5] dark:bg-[#1A1A1A] rounded-lg p-4 overflow-auto max-h-[300px]">
<div className="prose dark:prose-invert prose-sm max-w-none">
<Markdown>{updateProgress.details.changelog}</Markdown>
</div>
</div>
</div>
)}
{/* Add this in the update status card, after the commit info */}
{updateProgress?.details?.compareUrl && (
<div className="mt-4">
<a
href={updateProgress.details.compareUrl}
target="_blank"
rel="noopener noreferrer"
className={classNames(
'flex items-center gap-2 px-4 py-2 rounded-lg text-sm',
'bg-[#F5F5F5] dark:bg-[#1A1A1A]',
'hover:bg-purple-500/10 hover:text-purple-500',
'dark:hover:bg-purple-500/20 dark:hover:text-purple-500',
'text-bolt-elements-textPrimary',
'transition-colors duration-200',
'w-fit',
)}
>
<div className="i-ph:github-logo w-4 h-4" />
View Changes on GitHub
</a>
</div>
)}
{updateProgress?.details?.commitMessages && updateProgress.details.commitMessages.length > 0 && (
<div className="mb-6">
<p className="font-medium mb-2">Changes in this Update:</p>
<div className="bg-[#F5F5F5] dark:bg-[#1A1A1A] rounded-lg p-4 overflow-auto max-h-[400px]">
<div className="prose dark:prose-invert prose-sm max-w-none">
{updateProgress.details.commitMessages.map((section, index) => (
<Markdown key={index}>{section}</Markdown>
))}
</div>
</div>
</div>
)}
</motion.div>
{/* Update dialog */}
<DialogRoot open={showUpdateDialog} onOpenChange={setShowUpdateDialog}>
<Dialog>
<DialogTitle>Update Available</DialogTitle>
<DialogDescription>
<div className="mt-4">
<p className="text-sm text-bolt-elements-textSecondary mb-4">
A new version is available from <span className="font-mono">stackblitz-labs/bolt.diy</span> (Slate upstream) (
{isLatestBranch ? 'main' : 'stable'} branch)
</p>
{updateProgress?.details?.compareUrl && (
<div className="mb-6">
<a
href={updateProgress.details.compareUrl}
target="_blank"
rel="noopener noreferrer"
className={classNames(
'flex items-center gap-2 px-4 py-2 rounded-lg text-sm',
'bg-[#F5F5F5] dark:bg-[#1A1A1A]',
'hover:bg-purple-500/10 hover:text-purple-500',
'dark:hover:bg-purple-500/20 dark:hover:text-purple-500',
'text-bolt-elements-textPrimary',
'transition-colors duration-200',
'w-fit',
)}
>
<div className="i-ph:github-logo w-4 h-4" />
View Changes on GitHub
</a>
</div>
)}
{updateProgress?.details?.commitMessages && updateProgress.details.commitMessages.length > 0 && (
<div className="mb-6">
<p className="font-medium mb-2">Commit Messages:</p>
<div className="bg-[#F5F5F5] dark:bg-[#1A1A1A] rounded-lg p-3 space-y-2">
{updateProgress.details.commitMessages.map((msg, index) => (
<div key={index} className="text-sm text-bolt-elements-textSecondary flex items-start gap-2">
<div className="i-ph:git-commit text-purple-500 w-4 h-4 mt-0.5 flex-shrink-0" />
<span>{msg}</span>
</div>
))}
</div>
</div>
)}
{updateProgress?.details?.totalSize && (
<div className="flex items-center gap-4 text-sm text-bolt-elements-textSecondary">
<div className="flex items-center gap-2">
<div className="i-ph:file text-purple-500 w-4 h-4" />
Total size: {updateProgress.details.totalSize}
</div>
{updateProgress?.details?.additions !== undefined &&
updateProgress?.details?.deletions !== undefined && (
<div className="flex items-center gap-2">
<div className="i-ph:git-diff text-purple-500 w-4 h-4" />
Changes: <span className="text-green-600">+{updateProgress.details.additions}</span>{' '}
<span className="text-red-600">-{updateProgress.details.deletions}</span>
</div>
)}
</div>
)}
</div>
</DialogDescription>
<div className="flex justify-end gap-2 mt-6">
<DialogButton type="secondary" onClick={() => setShowUpdateDialog(false)}>
Cancel
</DialogButton>
<DialogButton type="primary" onClick={handleUpdate}>
Update Now
</DialogButton>
</div>
</Dialog>
</DialogRoot>
</div>
);
};
export default UpdateTab;

View File

@@ -0,0 +1,41 @@
import type { Variants } from 'framer-motion';
export const fadeIn: Variants = {
initial: { opacity: 0 },
animate: { opacity: 1 },
exit: { opacity: 0 },
};
export const slideIn: Variants = {
initial: { opacity: 0, y: 20 },
animate: { opacity: 1, y: 0 },
exit: { opacity: 0, y: -20 },
};
export const scaleIn: Variants = {
initial: { opacity: 0, scale: 0.8 },
animate: { opacity: 1, scale: 1 },
exit: { opacity: 0, scale: 0.8 },
};
export const tabAnimation: Variants = {
initial: { opacity: 0, scale: 0.8, y: 20 },
animate: { opacity: 1, scale: 1, y: 0 },
exit: { opacity: 0, scale: 0.8, y: -20 },
};
export const overlayAnimation: Variants = {
initial: { opacity: 0 },
animate: { opacity: 1 },
exit: { opacity: 0 },
};
export const modalAnimation: Variants = {
initial: { opacity: 0, scale: 0.95, y: 20 },
animate: { opacity: 1, scale: 1, y: 0 },
exit: { opacity: 0, scale: 0.95, y: 20 },
};
export const transition = {
duration: 0.2,
};

View File

@@ -0,0 +1,89 @@
import type { TabType, TabVisibilityConfig } from '~/components/@settings/core/types';
import { DEFAULT_TAB_CONFIG } from '~/components/@settings/core/constants';
export const getVisibleTabs = (
tabConfiguration: { userTabs: TabVisibilityConfig[]; developerTabs?: TabVisibilityConfig[] },
isDeveloperMode: boolean,
notificationsEnabled: boolean,
): TabVisibilityConfig[] => {
if (!tabConfiguration?.userTabs || !Array.isArray(tabConfiguration.userTabs)) {
console.warn('Invalid tab configuration, using defaults');
return DEFAULT_TAB_CONFIG as TabVisibilityConfig[];
}
// In developer mode, show ALL tabs without restrictions
if (isDeveloperMode) {
// Combine all unique tabs from both user and developer configurations
const allTabs = new Set([
...DEFAULT_TAB_CONFIG.map((tab) => tab.id),
...tabConfiguration.userTabs.map((tab) => tab.id),
...(tabConfiguration.developerTabs || []).map((tab) => tab.id),
'task-manager' as TabType, // Always include task-manager in developer mode
]);
// Create a complete tab list with all tabs visible
const devTabs = Array.from(allTabs).map((tabId) => {
// Try to find existing configuration for this tab
const existingTab =
tabConfiguration.developerTabs?.find((t) => t.id === tabId) ||
tabConfiguration.userTabs?.find((t) => t.id === tabId) ||
DEFAULT_TAB_CONFIG.find((t) => t.id === tabId);
return {
id: tabId as TabType,
visible: true,
window: 'developer' as const,
order: existingTab?.order || DEFAULT_TAB_CONFIG.findIndex((t) => t.id === tabId),
} as TabVisibilityConfig;
});
return devTabs.sort((a, b) => a.order - b.order);
}
// In user mode, only show visible user tabs
return tabConfiguration.userTabs
.filter((tab) => {
if (!tab || typeof tab.id !== 'string') {
console.warn('Invalid tab entry:', tab);
return false;
}
// Hide notifications tab if notifications are disabled
if (tab.id === 'notifications' && !notificationsEnabled) {
return false;
}
// Always show task-manager in user mode if it's configured as visible
if (tab.id === 'task-manager') {
return tab.visible;
}
// Only show tabs that are explicitly visible and assigned to the user window
return tab.visible && tab.window === 'user';
})
.sort((a, b) => a.order - b.order);
};
export const reorderTabs = (
tabs: TabVisibilityConfig[],
startIndex: number,
endIndex: number,
): TabVisibilityConfig[] => {
const result = Array.from(tabs);
const [removed] = result.splice(startIndex, 1);
result.splice(endIndex, 0, removed);
// Update order property
return result.map((tab, index) => ({
...tab,
order: index,
}));
};
export const resetToDefaultConfig = (isDeveloperMode: boolean): TabVisibilityConfig[] => {
return DEFAULT_TAB_CONFIG.map((tab) => ({
...tab,
visible: isDeveloperMode ? true : tab.window === 'user',
window: isDeveloperMode ? 'developer' : tab.window,
})) as TabVisibilityConfig[];
};

View File

@@ -35,7 +35,11 @@ export const Artifact = memo(({ messageId }: ArtifactProps) => {
const actions = useStore(
computed(artifact.runner.actions, (actions) => {
return Object.values(actions);
// Filter out Supabase actions except for migrations
return Object.values(actions).filter((action) => {
// Exclude actions with type 'supabase' or actions that contain 'supabase' in their content
return action.type !== 'supabase' && !(action.type === 'shell' && action.content?.includes('supabase'));
});
}),
);
@@ -50,77 +54,105 @@ export const Artifact = memo(({ messageId }: ArtifactProps) => {
}
if (actions.length !== 0 && artifact.type === 'bundled') {
const finished = !actions.find((action) => action.status !== 'complete');
const finished = !actions.find(
(action) => action.status !== 'complete' && !(action.type === 'start' && action.status === 'running'),
);
if (allActionFinished !== finished) {
setAllActionFinished(finished);
}
}
}, [actions]);
}, [actions, artifact.type, allActionFinished]);
// Determine the dynamic title based on state for bundled artifacts
const dynamicTitle =
artifact?.type === 'bundled'
? allActionFinished
? artifact.id === 'restored-project-setup'
? 'Project Restored' // Title when restore is complete
: 'Project Created' // Title when initial creation is complete
: artifact.id === 'restored-project-setup'
? 'Restoring Project...' // Title during restore
: 'Creating Project...' // Title during initial creation
: artifact?.title; // Fallback to original title for non-bundled or if artifact is missing
return (
<div className="artifact border border-bolt-elements-borderColor flex flex-col overflow-hidden rounded-lg w-full transition-border duration-150">
<div className="flex">
<button
className="flex items-stretch bg-bolt-elements-artifacts-background hover:bg-bolt-elements-artifacts-backgroundHover w-full overflow-hidden"
onClick={() => {
const showWorkbench = workbenchStore.showWorkbench.get();
workbenchStore.showWorkbench.set(!showWorkbench);
}}
>
{artifact.type == 'bundled' && (
<>
<div className="p-4">
{allActionFinished ? (
<div className={'i-ph:files-light'} style={{ fontSize: '2rem' }}></div>
) : (
<div className={'i-svg-spinners:90-ring-with-bg'} style={{ fontSize: '2rem' }}></div>
)}
<>
<div className="artifact border border-bolt-elements-borderColor flex flex-col overflow-hidden rounded-lg w-full transition-border duration-150">
<div className="flex">
<button
className="flex items-stretch bg-bolt-elements-artifacts-background hover:bg-bolt-elements-artifacts-backgroundHover w-full overflow-hidden"
onClick={() => {
const showWorkbench = workbenchStore.showWorkbench.get();
workbenchStore.showWorkbench.set(!showWorkbench);
}}
>
<div className="px-5 p-3.5 w-full text-left">
<div className="w-full text-bolt-elements-textPrimary font-medium leading-5 text-sm">
{/* Use the dynamic title here */}
{dynamicTitle}
</div>
<div className="bg-bolt-elements-artifacts-borderColor w-[1px]" />
</>
)}
<div className="px-5 p-3.5 w-full text-left">
<div className="w-full text-bolt-elements-textPrimary font-medium leading-5 text-sm">{artifact?.title}</div>
<div className="w-full w-full text-bolt-elements-textSecondary text-xs mt-0.5">Click to open Workbench</div>
<div className="w-full w-full text-bolt-elements-textSecondary text-xs mt-0.5">
Click to open Workbench
</div>
</div>
</button>
{artifact.type !== 'bundled' && <div className="bg-bolt-elements-artifacts-borderColor w-[1px]" />}
<AnimatePresence>
{actions.length && artifact.type !== 'bundled' && (
<motion.button
initial={{ width: 0 }}
animate={{ width: 'auto' }}
exit={{ width: 0 }}
transition={{ duration: 0.15, ease: cubicEasingFn }}
className="bg-bolt-elements-artifacts-background hover:bg-bolt-elements-artifacts-backgroundHover"
onClick={toggleActions}
>
<div className="p-4">
<div className={showActions ? 'i-ph:caret-up-bold' : 'i-ph:caret-down-bold'}></div>
</div>
</motion.button>
)}
</AnimatePresence>
</div>
{artifact.type === 'bundled' && (
<div className="flex items-center gap-1.5 p-5 bg-bolt-elements-actions-background border-t border-bolt-elements-artifacts-borderColor">
<div className={classNames('text-lg', getIconColor(allActionFinished ? 'complete' : 'running'))}>
{allActionFinished ? (
<div className="i-ph:check"></div>
) : (
<div className="i-svg-spinners:90-ring-with-bg"></div>
)}
</div>
<div className="text-bolt-elements-textPrimary font-medium leading-5 text-sm">
{/* This status text remains the same */}
{allActionFinished
? artifact.id === 'restored-project-setup'
? 'Restore files from snapshot'
: 'Initial files created'
: 'Creating initial files'}
</div>
</div>
</button>
<div className="bg-bolt-elements-artifacts-borderColor w-[1px]" />
)}
<AnimatePresence>
{actions.length && artifact.type !== 'bundled' && (
<motion.button
initial={{ width: 0 }}
animate={{ width: 'auto' }}
exit={{ width: 0 }}
transition={{ duration: 0.15, ease: cubicEasingFn }}
className="bg-bolt-elements-artifacts-background hover:bg-bolt-elements-artifacts-backgroundHover"
onClick={toggleActions}
{artifact.type !== 'bundled' && showActions && actions.length > 0 && (
<motion.div
className="actions"
initial={{ height: 0 }}
animate={{ height: 'auto' }}
exit={{ height: '0px' }}
transition={{ duration: 0.15 }}
>
<div className="p-4">
<div className={showActions ? 'i-ph:caret-up-bold' : 'i-ph:caret-down-bold'}></div>
<div className="bg-bolt-elements-artifacts-borderColor h-[1px]" />
<div className="p-5 text-left bg-bolt-elements-actions-background">
<ActionList actions={actions} />
</div>
</motion.button>
</motion.div>
)}
</AnimatePresence>
</div>
<AnimatePresence>
{artifact.type !== 'bundled' && showActions && actions.length > 0 && (
<motion.div
className="actions"
initial={{ height: 0 }}
animate={{ height: 'auto' }}
exit={{ height: '0px' }}
transition={{ duration: 0.15 }}
>
<div className="bg-bolt-elements-artifacts-borderColor h-[1px]" />
<div className="p-5 text-left bg-bolt-elements-actions-background">
<ActionList actions={actions} />
</div>
</motion.div>
)}
</AnimatePresence>
</div>
</>
);
});

View File

@@ -1,16 +1,59 @@
import { memo } from 'react';
import { memo, Fragment } from 'react';
import { Markdown } from './Markdown';
import type { JSONValue } from 'ai';
import Popover from '~/components/ui/Popover';
import { workbenchStore } from '~/lib/stores/workbench';
import { WORK_DIR } from '~/utils/constants';
import WithTooltip from '~/components/ui/Tooltip';
interface AssistantMessageProps {
content: string;
annotations?: JSONValue[];
messageId?: string;
onRewind?: (messageId: string) => void;
onFork?: (messageId: string) => void;
}
export const AssistantMessage = memo(({ content, annotations }: AssistantMessageProps) => {
function openArtifactInWorkbench(filePath: string) {
filePath = normalizedFilePath(filePath);
if (workbenchStore.currentView.get() !== 'code') {
workbenchStore.currentView.set('code');
}
workbenchStore.setSelectedFile(`${WORK_DIR}/${filePath}`);
}
function normalizedFilePath(path: string) {
let normalizedPath = path;
if (normalizedPath.startsWith(WORK_DIR)) {
normalizedPath = path.replace(WORK_DIR, '');
}
if (normalizedPath.startsWith('/')) {
normalizedPath = normalizedPath.slice(1);
}
return normalizedPath;
}
export const AssistantMessage = memo(({ content, annotations, messageId, onRewind, onFork }: AssistantMessageProps) => {
const filteredAnnotations = (annotations?.filter(
(annotation: JSONValue) => annotation && typeof annotation === 'object' && Object.keys(annotation).includes('type'),
) || []) as { type: string; value: any }[];
) || []) as { type: string; value: any } & { [key: string]: any }[];
let chatSummary: string | undefined = undefined;
if (filteredAnnotations.find((annotation) => annotation.type === 'chatSummary')) {
chatSummary = filteredAnnotations.find((annotation) => annotation.type === 'chatSummary')?.summary;
}
let codeContext: string[] | undefined = undefined;
if (filteredAnnotations.find((annotation) => annotation.type === 'codeContext')) {
codeContext = filteredAnnotations.find((annotation) => annotation.type === 'codeContext')?.files;
}
const usage: {
completionTokens: number;
@@ -20,11 +63,78 @@ export const AssistantMessage = memo(({ content, annotations }: AssistantMessage
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 className=" flex gap-2 items-center text-sm text-bolt-elements-textSecondary mb-2">
{(codeContext || chatSummary) && (
<Popover side="right" align="start" trigger={<div className="i-ph:info" />}>
{chatSummary && (
<div className="max-w-chat">
<div className="summary max-h-96 flex flex-col">
<h2 className="border border-bolt-elements-borderColor rounded-md p4">Summary</h2>
<div style={{ zoom: 0.7 }} className="overflow-y-auto m4">
<Markdown>{chatSummary}</Markdown>
</div>
</div>
{codeContext && (
<div className="code-context flex flex-col p4 border border-bolt-elements-borderColor rounded-md">
<h2>Context</h2>
<div className="flex gap-4 mt-4 bolt" style={{ zoom: 0.6 }}>
{codeContext.map((x) => {
const normalized = normalizedFilePath(x);
return (
<Fragment key={normalized}>
<code
className="bg-bolt-elements-artifacts-inlineCode-background text-bolt-elements-artifacts-inlineCode-text px-1.5 py-1 rounded-md text-bolt-elements-item-contentAccent hover:underline cursor-pointer"
onClick={(e) => {
e.preventDefault();
e.stopPropagation();
openArtifactInWorkbench(normalized);
}}
>
{normalized}
</code>
</Fragment>
);
})}
</div>
</div>
)}
</div>
)}
<div className="context"></div>
</Popover>
)}
<div className="flex w-full items-center justify-between">
{usage && (
<div>
Tokens: {usage.totalTokens} (prompt: {usage.promptTokens}, completion: {usage.completionTokens})
</div>
)}
{(onRewind || onFork) && messageId && (
<div className="flex gap-2 flex-col lg:flex-row ml-auto">
{onRewind && (
<WithTooltip tooltip="Revert to this message">
<button
onClick={() => onRewind(messageId)}
key="i-ph:arrow-u-up-left"
className="i-ph:arrow-u-up-left text-xl text-bolt-elements-textSecondary hover:text-bolt-elements-textPrimary transition-colors"
/>
</WithTooltip>
)}
{onFork && (
<WithTooltip tooltip="Fork chat from this message">
<button
onClick={() => onFork(messageId)}
key="i-ph:git-fork"
className="i-ph:git-fork text-xl text-bolt-elements-textSecondary hover:text-bolt-elements-textPrimary transition-colors"
/>
</WithTooltip>
)}
</div>
)}
</div>
</div>
)}
</>
<Markdown html>{content}</Markdown>
</div>
);

View File

@@ -2,7 +2,7 @@
* @ts-nocheck
* Preventing TS checks with files presented in the video for a better presentation.
*/
import type { Message } from 'ai';
import type { JSONValue, Message } from 'ai';
import React, { type RefCallback, useEffect, useState } from 'react';
import { ClientOnly } from 'remix-utils/client-only';
import { Menu } from '~/components/sidebar/Menu.client';
@@ -29,9 +29,20 @@ import type { ProviderInfo } from '~/types/model';
import { ScreenshotStateManager } from './ScreenshotStateManager';
import { toast } from 'react-toastify';
import StarterTemplates from './StarterTemplates';
import type { ActionAlert } from '~/types/actions';
import type { ActionAlert, SupabaseAlert, DeployAlert } from '~/types/actions';
import DeployChatAlert from '~/components/deploy/DeployAlert';
import ChatAlert from './ChatAlert';
import type { ModelInfo } from '~/lib/modules/llm/types';
import ProgressCompilation from './ProgressCompilation';
import type { ProgressAnnotation } from '~/types/context';
import type { ActionRunner } from '~/lib/runtime/action-runner';
import { LOCAL_PROVIDERS } from '~/lib/stores/settings';
import { SupabaseChatAlert } from '~/components/chat/SupabaseAlert';
import { SupabaseConnection } from './SupabaseConnection';
import { ExpoQrModal } from '~/components/workbench/ExpoQrModal';
import { expoUrlAtom } from '~/lib/stores/qrCodeStore';
import { useStore } from '@nanostores/react';
import { StickToBottom, useStickToBottomContext } from '~/lib/hooks';
const TEXTAREA_MIN_HEIGHT = 76;
@@ -42,6 +53,7 @@ interface BaseChatProps {
showChat?: boolean;
chatStarted?: boolean;
isStreaming?: boolean;
onStreamingChange?: (streaming: boolean) => void;
messages?: Message[];
description?: string;
enhancingPrompt?: boolean;
@@ -64,17 +76,22 @@ interface BaseChatProps {
setImageDataList?: (dataList: string[]) => void;
actionAlert?: ActionAlert;
clearAlert?: () => void;
supabaseAlert?: SupabaseAlert;
clearSupabaseAlert?: () => void;
deployAlert?: DeployAlert;
clearDeployAlert?: () => void;
data?: JSONValue[] | undefined;
actionRunner?: ActionRunner;
}
export const BaseChat = React.forwardRef<HTMLDivElement, BaseChatProps>(
(
{
textareaRef,
messageRef,
scrollRef,
showChat = true,
chatStarted = false,
isStreaming = false,
onStreamingChange,
model,
setModel,
provider,
@@ -97,6 +114,12 @@ export const BaseChat = React.forwardRef<HTMLDivElement, BaseChatProps>(
messages,
actionAlert,
clearAlert,
deployAlert,
clearDeployAlert,
supabaseAlert,
clearSupabaseAlert,
data,
actionRunner,
},
ref,
) => {
@@ -108,11 +131,32 @@ export const BaseChat = React.forwardRef<HTMLDivElement, BaseChatProps>(
const [recognition, setRecognition] = useState<SpeechRecognition | null>(null);
const [transcript, setTranscript] = useState('');
const [isModelLoading, setIsModelLoading] = useState<string | undefined>('all');
const [progressAnnotations, setProgressAnnotations] = useState<ProgressAnnotation[]>([]);
const expoUrl = useStore(expoUrlAtom);
const [qrModalOpen, setQrModalOpen] = useState(false);
useEffect(() => {
if (expoUrl) {
setQrModalOpen(true);
}
}, [expoUrl]);
useEffect(() => {
if (data) {
const progressList = data.filter(
(x) => typeof x === 'object' && (x as any).type === 'progress',
) as ProgressAnnotation[];
setProgressAnnotations(progressList);
}
}, [data]);
useEffect(() => {
console.log(transcript);
}, [transcript]);
useEffect(() => {
onStreamingChange?.(isStreaming);
}, [isStreaming, onStreamingChange]);
useEffect(() => {
if (typeof window !== 'undefined' && ('SpeechRecognition' in window || 'webkitSpeechRecognition' in window)) {
const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;
@@ -291,7 +335,7 @@ export const BaseChat = React.forwardRef<HTMLDivElement, BaseChatProps>(
data-chat-visible={showChat}
>
<ClientOnly>{() => <Menu />}</ClientOnly>
<div ref={scrollRef} className="flex flex-col lg:flex-row overflow-y-auto w-full h-full">
<div 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-[16vh] max-w-chat mx-auto text-center px-4 lg:px-0">
@@ -303,29 +347,52 @@ export const BaseChat = React.forwardRef<HTMLDivElement, BaseChatProps>(
</p>
</div>
)}
<div
className={classNames('pt-6 px-2 sm:px-6', {
'h-full flex flex-col': chatStarted,
<StickToBottom
className={classNames('pt-6 px-2 sm:px-6 relative', {
'h-full flex flex-col modern-scrollbar': chatStarted,
})}
resize="smooth"
initial="smooth"
>
<ClientOnly>
{() => {
return chatStarted ? (
<Messages
ref={messageRef}
className="flex flex-col w-full flex-1 max-w-chat pb-6 mx-auto z-1"
messages={messages}
isStreaming={isStreaming}
/>
) : null;
}}
</ClientOnly>
<StickToBottom.Content className="flex flex-col gap-4">
<ClientOnly>
{() => {
return chatStarted ? (
<Messages
className="flex flex-col w-full flex-1 max-w-chat pb-6 mx-auto z-1"
messages={messages}
isStreaming={isStreaming}
/>
) : null;
}}
</ClientOnly>
</StickToBottom.Content>
<div
className={classNames('flex flex-col gap-4 w-full max-w-chat mx-auto z-prompt mb-6', {
className={classNames('my-auto flex flex-col gap-2 w-full max-w-chat mx-auto z-prompt mb-6', {
'sticky bottom-2': chatStarted,
})}
>
<div className="bg-bolt-elements-background-depth-2">
<div className="flex flex-col gap-2">
{deployAlert && (
<DeployChatAlert
alert={deployAlert}
clearAlert={() => clearDeployAlert?.()}
postMessage={(message: string | undefined) => {
sendMessage?.({} as any, message);
clearSupabaseAlert?.();
}}
/>
)}
{supabaseAlert && (
<SupabaseChatAlert
alert={supabaseAlert}
clearAlert={() => clearSupabaseAlert?.()}
postMessage={(message) => {
sendMessage?.({} as any, message);
clearSupabaseAlert?.();
}}
/>
)}
{actionAlert && (
<ChatAlert
alert={actionAlert}
@@ -337,9 +404,11 @@ export const BaseChat = React.forwardRef<HTMLDivElement, BaseChatProps>(
/>
)}
</div>
<ScrollToBottom />
{progressAnnotations && <ProgressCompilation data={progressAnnotations} />}
<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',
'relative 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',
/*
* {
@@ -389,15 +458,17 @@ export const BaseChat = React.forwardRef<HTMLDivElement, BaseChatProps>(
apiKeys={apiKeys}
modelLoading={isModelLoading}
/>
{(providerList || []).length > 0 && provider && (
<APIKeyManager
provider={provider}
apiKey={apiKeys[provider.name] || ''}
setApiKey={(key) => {
onApiKeysChange(provider.name, key);
}}
/>
)}
{(providerList || []).length > 0 &&
provider &&
(!LOCAL_PROVIDERS.includes(provider.name) || 'OpenAILike') && (
<APIKeyManager
provider={provider}
apiKey={apiKeys[provider.name] || ''}
setApiKey={(key) => {
onApiKeysChange(provider.name, key);
}}
/>
)}
</div>
)}
</ClientOnly>
@@ -492,7 +563,7 @@ export const BaseChat = React.forwardRef<HTMLDivElement, BaseChatProps>(
minHeight: TEXTAREA_MIN_HEIGHT,
maxHeight: TEXTAREA_MAX_HEIGHT,
}}
placeholder="How can Bolt help you today?"
placeholder="How can Slate help you today?"
translate="no"
/>
<ClientOnly>
@@ -564,31 +635,43 @@ export const BaseChat = React.forwardRef<HTMLDivElement, BaseChatProps>(
a new line
</div>
) : null}
<SupabaseConnection />
<ExpoQrModal open={qrModalOpen} onClose={() => setQrModalOpen(false)} />
</div>
</div>
</div>
</div>
</div>
<div className="flex flex-col justify-center gap-5">
</StickToBottom>
<div className="flex flex-col justify-center">
{!chatStarted && (
<div className="flex justify-center gap-2">
{ImportButtons(importChat)}
<GitCloneButton importChat={importChat} />
</div>
)}
{!chatStarted &&
ExamplePrompts((event, messageInput) => {
if (isStreaming) {
handleStop?.();
return;
}
<div className="flex flex-col gap-5">
{!chatStarted &&
ExamplePrompts((event, messageInput) => {
if (isStreaming) {
handleStop?.();
return;
}
handleSendMessage?.(event, messageInput);
})}
{!chatStarted && <StarterTemplates />}
handleSendMessage?.(event, messageInput);
})}
{!chatStarted && <StarterTemplates />}
</div>
</div>
</div>
<ClientOnly>{() => <Workbench chatStarted={chatStarted} isStreaming={isStreaming} />}</ClientOnly>
<ClientOnly>
{() => (
<Workbench
actionRunner={actionRunner ?? ({} as ActionRunner)}
chatStarted={chatStarted}
isStreaming={isStreaming}
/>
)}
</ClientOnly>
</div>
</div>
);
@@ -596,3 +679,19 @@ export const BaseChat = React.forwardRef<HTMLDivElement, BaseChatProps>(
return <Tooltip.Provider delayDuration={200}>{baseChat}</Tooltip.Provider>;
},
);
function ScrollToBottom() {
const { isAtBottom, scrollToBottom } = useStickToBottomContext();
return (
!isAtBottom && (
<button
className="absolute z-50 top-[0%] translate-y-[-100%] text-4xl rounded-lg left-[50%] translate-x-[-50%] px-1.5 py-0.5 flex items-center gap-2 bg-bolt-elements-background-depth-3 border border-bolt-elements-borderColor text-bolt-elements-textPrimary text-sm"
onClick={() => scrollToBottom()}
>
Go to last message
<span className="i-ph:arrow-down animate-bounce" />
</button>
)
);
}

View File

@@ -8,7 +8,7 @@ import { useChat } from 'ai/react';
import { useAnimate } from 'framer-motion';
import { memo, useCallback, useEffect, useRef, useState } from 'react';
import { cssTransition, toast, ToastContainer } from 'react-toastify';
import { useMessageParser, usePromptEnhancer, useShortcuts, useSnapScroll } from '~/lib/hooks';
import { useMessageParser, usePromptEnhancer, useShortcuts } from '~/lib/hooks';
import { description, useChatHistory } from '~/lib/persistence';
import { chatStore } from '~/lib/stores/chat';
import { workbenchStore } from '~/lib/stores/workbench';
@@ -23,6 +23,10 @@ import type { ProviderInfo } from '~/types/model';
import { useSearchParams } from '@remix-run/react';
import { createSampler } from '~/utils/sampler';
import { getTemplates, selectStarterTemplate } from '~/utils/selectStarterTemplate';
import { logStore } from '~/lib/stores/logs';
import { streamingState } from '~/lib/stores/streaming';
import { filesToArtifacts } from '~/utils/fileUtils';
import { supabaseConnection } from '~/lib/stores/supabase';
const toastAnimation = cssTransition({
enter: 'animated fadeInRight',
@@ -77,6 +81,7 @@ export function Chat() {
position="bottom-right"
pauseOnFocusLoss
transition={toastAnimation}
autoClose={3000}
/>
</>
);
@@ -114,12 +119,18 @@ export const ChatImpl = memo(
const textareaRef = useRef<HTMLTextAreaElement>(null);
const [chatStarted, setChatStarted] = useState(initialMessages.length > 0);
const [uploadedFiles, setUploadedFiles] = useState<File[]>([]); // Move here
const [imageDataList, setImageDataList] = useState<string[]>([]); // Move here
const [uploadedFiles, setUploadedFiles] = useState<File[]>([]);
const [imageDataList, setImageDataList] = useState<string[]>([]);
const [searchParams, setSearchParams] = useSearchParams();
const [fakeLoading, setFakeLoading] = useState(false);
const files = useStore(workbenchStore.files);
const actionAlert = useStore(workbenchStore.alert);
const deployAlert = useStore(workbenchStore.deployAlert);
const supabaseConn = useStore(supabaseConnection); // Add this line to get Supabase connection
const selectedProject = supabaseConn.stats?.projects?.find(
(project) => project.id === supabaseConn.selectedProjectId,
);
const supabaseAlert = useStore(workbenchStore.supabaseAlert);
const { activeProviders, promptId, autoSelectTemplate, contextOptimizationEnabled } = useSettings();
const [model, setModel] = useState(() => {
@@ -137,36 +148,68 @@ export const ChatImpl = memo(
const [apiKeys, setApiKeys] = useState<Record<string, string>>({});
const { messages, isLoading, input, handleInputChange, setInput, stop, append, setMessages, reload, error } =
useChat({
api: '/api/chat',
body: {
apiKeys,
files,
promptId,
contextOptimization: contextOptimizationEnabled,
const {
messages,
isLoading,
input,
handleInputChange,
setInput,
stop,
append,
setMessages,
reload,
error,
data: chatData,
setData,
} = useChat({
api: '/api/chat',
body: {
apiKeys,
files,
promptId,
contextOptimization: contextOptimizationEnabled,
supabase: {
isConnected: supabaseConn.isConnected,
hasSelectedProject: !!selectedProject,
credentials: {
supabaseUrl: supabaseConn?.credentials?.supabaseUrl,
anonKey: supabaseConn?.credentials?.anonKey,
},
},
sendExtraMessageFields: true,
onError: (e) => {
logger.error('Request failed\n\n', e, error);
toast.error(
'There was an error processing your request: ' + (e.message ? e.message : 'No details were returned'),
);
},
onFinish: (message, response) => {
const usage = response.usage;
},
sendExtraMessageFields: true,
onError: (e) => {
logger.error('Request failed\n\n', e, error);
logStore.logError('Chat request failed', e, {
component: 'Chat',
action: 'request',
error: e.message,
});
toast.error(
'There was an error processing your request: ' + (e.message ? e.message : 'No details were returned'),
);
},
onFinish: (message, response) => {
const usage = response.usage;
setData(undefined);
if (usage) {
console.log('Token usage:', usage);
if (usage) {
console.log('Token usage:', usage);
logStore.logProvider('Chat response completed', {
component: 'Chat',
action: 'response',
model,
provider: provider.name,
usage,
messageLength: message.content.length,
});
}
// You can now use the usage data as needed
}
logger.debug('Finished streaming');
},
initialMessages,
initialInput: Cookies.get(PROMPT_COOKIE_KEY) || '',
});
logger.debug('Finished streaming');
},
initialMessages,
initialInput: Cookies.get(PROMPT_COOKIE_KEY) || '',
});
useEffect(() => {
const prompt = searchParams.get('prompt');
@@ -218,6 +261,13 @@ export const ChatImpl = memo(
stop();
chatStore.setKey('aborted', true);
workbenchStore.abortAllActions();
logStore.logProvider('Chat response aborted', {
component: 'Chat',
action: 'abort',
model,
provider: provider.name,
});
};
useEffect(() => {
@@ -249,33 +299,90 @@ export const ChatImpl = memo(
};
const sendMessage = async (_event: React.UIEvent, messageInput?: string) => {
const _input = messageInput || input;
const messageContent = messageInput || input;
if (_input.length === 0 || isLoading) {
if (!messageContent?.trim()) {
return;
}
/**
* @note (delm) Usually saving files shouldn't take long but it may take longer if there
* many unsaved files. In that case we need to block user input and show an indicator
* of some kind so the user is aware that something is happening. But I consider the
* happy case to be no unsaved files and I would expect users to save their changes
* before they send another message.
*/
await workbenchStore.saveAllFiles();
if (error != null) {
setMessages(messages.slice(0, -1));
if (isLoading) {
abort();
return;
}
const fileModifications = workbenchStore.getFileModifcations();
chatStore.setKey('aborted', false);
// If no locked items, proceed normally with the original message
const finalMessageContent = messageContent;
runAnimation();
if (!chatStarted && messageInput && autoSelectTemplate) {
if (!chatStarted) {
setFakeLoading(true);
if (autoSelectTemplate) {
const { template, title } = await selectStarterTemplate({
message: finalMessageContent,
model,
provider,
});
if (template !== 'blank') {
const temResp = await getTemplates(template, title).catch((e) => {
if (e.message.includes('rate limit')) {
toast.warning('Rate limit exceeded. Skipping starter template\n Continuing with blank template');
} else {
toast.warning('Failed to import starter template\n Continuing with blank template');
}
return null;
});
if (temResp) {
const { assistantMessage, userMessage } = temResp;
setMessages([
{
id: `1-${new Date().getTime()}`,
role: 'user',
content: [
{
type: 'text',
text: `[Model: ${model}]\n\n[Provider: ${provider.name}]\n\n${finalMessageContent}`,
},
...imageDataList.map((imageData) => ({
type: 'image',
image: imageData,
})),
] as any,
},
{
id: `2-${new Date().getTime()}`,
role: 'assistant',
content: assistantMessage,
},
{
id: `3-${new Date().getTime()}`,
role: 'user',
content: `[Model: ${model}]\n\n[Provider: ${provider.name}]\n\n${userMessage}`,
annotations: ['hidden'],
},
]);
reload();
setInput('');
Cookies.remove(PROMPT_COOKIE_KEY);
setUploadedFiles([]);
setImageDataList([]);
resetEnhancer();
textareaRef.current?.blur();
setFakeLoading(false);
return;
}
}
}
// If autoSelectTemplate is disabled or template selection failed, proceed with normal message
setMessages([
{
id: `${new Date().getTime()}`,
@@ -283,135 +390,54 @@ export const ChatImpl = memo(
content: [
{
type: 'text',
text: `[Model: ${model}]\n\n[Provider: ${provider.name}]\n\n${_input}`,
text: `[Model: ${model}]\n\n[Provider: ${provider.name}]\n\n${finalMessageContent}`,
},
...imageDataList.map((imageData) => ({
type: 'image',
image: imageData,
})),
] as any, // Type assertion to bypass compiler check
] as any,
},
]);
reload();
setFakeLoading(false);
setInput('');
Cookies.remove(PROMPT_COOKIE_KEY);
// reload();
setUploadedFiles([]);
setImageDataList([]);
const { template, title } = await selectStarterTemplate({
message: messageInput,
model,
provider,
});
resetEnhancer();
if (template !== 'blank') {
const temResp = await getTemplates(template, title).catch((e) => {
if (e.message.includes('rate limit')) {
toast.warning('Rate limit exceeded. Skipping starter template\n Continuing with blank template');
} else {
toast.warning('Failed to import starter template\n Continuing with blank template');
}
textareaRef.current?.blur();
return null;
});
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;
}
return;
}
if (fileModifications !== undefined) {
/**
* If we have file modifications we append a new user message manually since we have to prefix
* the user input with the file modifications and we don't want the new user input to appear
* in the prompt. Using `append` is almost the same as `handleSubmit` except that we have to
* manually reset the input and we'd have to manually pass in file attachments. However, those
* aren't relevant here.
*/
if (error != null) {
setMessages(messages.slice(0, -1));
}
const modifiedFiles = workbenchStore.getModifiedFiles();
chatStore.setKey('aborted', false);
if (modifiedFiles !== undefined) {
const userUpdateArtifact = filesToArtifacts(modifiedFiles, `${Date.now()}`);
append({
role: 'user',
content: [
{
type: 'text',
text: `[Model: ${model}]\n\n[Provider: ${provider.name}]\n\n${_input}`,
text: `[Model: ${model}]\n\n[Provider: ${provider.name}]\n\n${userUpdateArtifact}${finalMessageContent}`,
},
...imageDataList.map((imageData) => ({
type: 'image',
image: imageData,
})),
] as any, // Type assertion to bypass compiler check
] as any,
});
/**
* After sending a new message we reset all modifications since the model
* should now be aware of all the changes.
*/
workbenchStore.resetAllFileModifications();
} else {
append({
@@ -419,20 +445,19 @@ export const ChatImpl = memo(
content: [
{
type: 'text',
text: `[Model: ${model}]\n\n[Provider: ${provider.name}]\n\n${_input}`,
text: `[Model: ${model}]\n\n[Provider: ${provider.name}]\n\n${finalMessageContent}`,
},
...imageDataList.map((imageData) => ({
type: 'image',
image: imageData,
})),
] as any, // Type assertion to bypass compiler check
] as any,
});
}
setInput('');
Cookies.remove(PROMPT_COOKIE_KEY);
// Add file cleanup here
setUploadedFiles([]);
setImageDataList([]);
@@ -461,8 +486,6 @@ export const ChatImpl = memo(
[],
);
const [messageRef, scrollRef] = useSnapScroll();
useEffect(() => {
const storedApiKeys = Cookies.get('apiKeys');
@@ -489,6 +512,9 @@ export const ChatImpl = memo(
showChat={showChat}
chatStarted={chatStarted}
isStreaming={isLoading || fakeLoading}
onStreamingChange={(streaming) => {
streamingState.set(streaming);
}}
enhancingPrompt={enhancingPrompt}
promptEnhanced={promptEnhanced}
sendMessage={sendMessage}
@@ -497,8 +523,6 @@ export const ChatImpl = memo(
provider={provider}
setProvider={handleProviderChange}
providerList={activeProviders}
messageRef={messageRef}
scrollRef={scrollRef}
handleInputChange={(e) => {
onTextareaChange(e);
debouncedCachePrompt(e);
@@ -535,6 +559,11 @@ export const ChatImpl = memo(
setImageDataList={setImageDataList}
actionAlert={actionAlert}
clearAlert={() => workbenchStore.clearAlert()}
supabaseAlert={supabaseAlert}
clearSupabaseAlert={() => workbenchStore.clearSupabaseAlert()}
deployAlert={deployAlert}
clearDeployAlert={() => workbenchStore.clearDeployAlert()}
data={chatData}
/>
);
},

View File

@@ -24,7 +24,7 @@ export default function ChatAlert({ alert, clearAlert, postMessage }: Props) {
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`}
className={`rounded-lg border border-bolt-elements-borderColor bg-bolt-elements-background-depth-2 p-4 mb-2`}
>
<div className="flex items-start">
{/* Icon */}

View File

@@ -35,18 +35,21 @@ export const CodeBlock = memo(
};
useEffect(() => {
let effectiveLanguage = language;
if (language && !isSpecialLang(language) && !(language in bundledLanguages)) {
logger.warn(`Unsupported language '${language}'`);
logger.warn(`Unsupported language '${language}', falling back to plaintext`);
effectiveLanguage = 'plaintext';
}
logger.trace(`Language = ${language}`);
logger.trace(`Language = ${effectiveLanguage}`);
const processCode = async () => {
setHTML(await codeToHtml(code, { lang: language, theme }));
setHTML(await codeToHtml(code, { lang: effectiveLanguage, theme }));
};
processCode();
}, [code]);
}, [code, language, theme]);
return (
<div className={classNames('relative group text-left', className)}>

View File

@@ -1,6 +1,7 @@
import React from 'react';
const EXAMPLE_PROMPTS = [
{ text: 'Create a mobile app idea generator' },
{ text: 'Build a todo app in React using Tailwind' },
{ text: 'Build a simple blog using Astro' },
{ text: 'Create a cookie consent form using Material UI' },

View File

@@ -12,18 +12,21 @@ const FilePreview: React.FC<FilePreviewProps> = ({ files, imageDataList, onRemov
}
return (
<div className="flex flex-row overflow-x-auto -mt-2">
<div className="flex flex-row overflow-x-auto mx-2 -mt-1 p-2 bg-bolt-elements-background-depth-3 border border-b-none border-bolt-elements-borderColor rounded-lg rounded-b-none">
{files.map((file, index) => (
<div key={file.name + file.size} className="mr-2 relative">
{imageDataList[index] && (
<div className="relative pt-4 pr-4">
<img src={imageDataList[index]} alt={file.name} className="max-h-20" />
<div className="relative">
<img src={imageDataList[index]} alt={file.name} className="max-h-20 rounded-lg" />
<button
onClick={() => onRemove(index)}
className="absolute top-1 right-1 z-10 bg-black rounded-full w-5 h-5 shadow-md hover:bg-gray-900 transition-colors flex items-center justify-center"
className="absolute -top-1 -right-1 z-10 bg-black rounded-full w-5 h-5 shadow-md hover:bg-gray-900 transition-colors flex items-center justify-center"
>
<div className="i-ph:x w-3 h-3 text-gray-200" />
</button>
<div className="absolute bottom-0 w-full h-5 flex items-center px-2 rounded-b-lg text-bolt-elements-textTertiary font-thin text-xs bg-bolt-elements-background-depth-2">
<span className="truncate">{file.name}</span>
</div>
</div>
)}
</div>

View File

@@ -1,124 +1,181 @@
import ignore from 'ignore';
import { useGit } from '~/lib/hooks/useGit';
import type { Message } from 'ai';
import { detectProjectCommands, createCommandsMessage } from '~/utils/projectCommands';
import { detectProjectCommands, createCommandsMessage, escapeBoltTags } from '~/utils/projectCommands';
import { generateId } from '~/utils/fileUtils';
import { useState } from 'react';
import { toast } from 'react-toastify';
import { LoadingOverlay } from '~/components/ui/LoadingOverlay';
import { RepositorySelectionDialog } from '~/components/@settings/tabs/connections/components/RepositorySelectionDialog';
import { classNames } from '~/utils/classNames';
import { Button } from '~/components/ui/Button';
import type { IChatMetadata } from '~/lib/persistence/db';
const IGNORE_PATTERNS = [
'node_modules/**',
'.git/**',
'.github/**',
'.vscode/**',
'**/*.jpg',
'**/*.jpeg',
'**/*.png',
'dist/**',
'build/**',
'.next/**',
'coverage/**',
'.cache/**',
'.vscode/**',
'.idea/**',
'**/*.log',
'**/.DS_Store',
'**/npm-debug.log*',
'**/yarn-debug.log*',
'**/yarn-error.log*',
'**/*lock.json',
// Include this so npm install runs much faster '**/*lock.json',
'**/*lock.yaml',
];
const ig = ignore().add(IGNORE_PATTERNS);
const MAX_FILE_SIZE = 100 * 1024; // 100KB limit per file
const MAX_TOTAL_SIZE = 500 * 1024; // 500KB total limit
interface GitCloneButtonProps {
className?: string;
importChat?: (description: string, messages: Message[]) => Promise<void>;
importChat?: (description: string, messages: Message[], metadata?: IChatMetadata) => Promise<void>;
}
export default function GitCloneButton({ importChat }: GitCloneButtonProps) {
export default function GitCloneButton({ importChat, className }: GitCloneButtonProps) {
const { ready, gitClone } = useGit();
const [loading, setLoading] = useState(false);
const [isDialogOpen, setIsDialogOpen] = useState(false);
const onClick = async (_e: any) => {
const handleClone = async (repoUrl: string) => {
if (!ready) {
return;
}
const repoUrl = prompt('Enter the Git url');
setLoading(true);
if (repoUrl) {
setLoading(true);
try {
const { workdir, data } = await gitClone(repoUrl);
try {
const { workdir, data } = await gitClone(repoUrl);
if (importChat) {
const filePaths = Object.keys(data).filter((filePath) => !ig.ignores(filePath));
const textDecoder = new TextDecoder('utf-8');
if (importChat) {
const filePaths = Object.keys(data).filter((filePath) => !ig.ignores(filePath));
console.log(filePaths);
let totalSize = 0;
const skippedFiles: string[] = [];
const fileContents = [];
const textDecoder = new TextDecoder('utf-8');
for (const filePath of filePaths) {
const { data: content, encoding } = data[filePath];
const fileContents = filePaths
.map((filePath) => {
const { data: content, encoding } = data[filePath];
return {
path: filePath,
content:
encoding === 'utf8' ? content : content instanceof Uint8Array ? textDecoder.decode(content) : '',
};
})
.filter((f) => f.content);
// Skip binary files
if (
content instanceof Uint8Array &&
!filePath.match(/\.(txt|md|astro|mjs|js|jsx|ts|tsx|json|html|css|scss|less|yml|yaml|xml|svg|vue|svelte)$/i)
) {
skippedFiles.push(filePath);
continue;
}
const commands = await detectProjectCommands(fileContents);
const commandsMessage = createCommandsMessage(commands);
try {
const textContent =
encoding === 'utf8' ? content : content instanceof Uint8Array ? textDecoder.decode(content) : '';
if (!textContent) {
continue;
}
// Check file size
const fileSize = new TextEncoder().encode(textContent).length;
if (fileSize > MAX_FILE_SIZE) {
skippedFiles.push(`${filePath} (too large: ${Math.round(fileSize / 1024)}KB)`);
continue;
}
// Check total size
if (totalSize + fileSize > MAX_TOTAL_SIZE) {
skippedFiles.push(`${filePath} (would exceed total size limit)`);
continue;
}
totalSize += fileSize;
fileContents.push({
path: filePath,
content: textContent,
});
} catch (e: any) {
skippedFiles.push(`${filePath} (error: ${e.message})`);
}
}
const commands = await detectProjectCommands(fileContents);
const commandsMessage = createCommandsMessage(commands);
const filesMessage: Message = {
role: 'assistant',
content: `Cloning the repo ${repoUrl} into ${workdir}
${
skippedFiles.length > 0
? `\nSkipped files (${skippedFiles.length}):
${skippedFiles.map((f) => `- ${f}`).join('\n')}`
: ''
}
const filesMessage: Message = {
role: 'assistant',
content: `Cloning the repo ${repoUrl} into ${workdir}
<boltArtifact id="imported-files" title="Git Cloned Files" type="bundled">
${fileContents
.map(
(file) =>
`<boltAction type="file" filePath="${file.path}">
${file.content}
${escapeBoltTags(file.content)}
</boltAction>`,
)
.join('\n')}
</boltArtifact>`,
id: generateId(),
createdAt: new Date(),
};
id: generateId(),
createdAt: new Date(),
};
const messages = [filesMessage];
const messages = [filesMessage];
if (commandsMessage) {
messages.push(commandsMessage);
}
await importChat(`Git Project:${repoUrl.split('/').slice(-1)[0]}`, messages);
if (commandsMessage) {
messages.push(commandsMessage);
}
} catch (error) {
console.error('Error during import:', error);
toast.error('Failed to import repository');
} finally {
setLoading(false);
await importChat(`Git Project:${repoUrl.split('/').slice(-1)[0]}`, messages);
}
} catch (error) {
console.error('Error during import:', error);
toast.error('Failed to import repository');
} finally {
setLoading(false);
}
};
return (
<>
<button
onClick={onClick}
<Button
onClick={() => setIsDialogOpen(true)}
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"
variant="default"
size="lg"
className={classNames(
'gap-2 bg-bolt-elements-background-depth-1',
'text-bolt-elements-textPrimary',
'hover:bg-bolt-elements-background-depth-2',
'border border-bolt-elements-borderColor',
'h-10 px-4 py-2 min-w-[120px] justify-center',
'transition-all duration-200 ease-in-out',
className,
)}
disabled={!ready || loading}
>
<span className="i-ph:git-branch" />
<span className="i-ph:git-branch w-4 h-4" />
Clone a Git Repo
</button>
</Button>
<RepositorySelectionDialog isOpen={isDialogOpen} onClose={() => setIsDialogOpen(false)} onSelect={handleClone} />
{loading && <LoadingOverlay message="Please wait while we clone the repository..." />}
</>
);

View File

@@ -4,6 +4,8 @@ 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
import { Button } from '~/components/ui/Button';
import { classNames } from '~/utils/classNames';
interface ImportFolderButtonProps {
className?: string;
@@ -112,17 +114,28 @@ export const ImportFolderButton: React.FC<ImportFolderButtonProps> = ({ classNam
onChange={handleFileChange}
{...({} as any)}
/>
<button
<Button
onClick={() => {
const input = document.getElementById('folder-import');
input?.click();
}}
className={className}
title="Import Folder"
variant="default"
size="lg"
className={classNames(
'gap-2 bg-bolt-elements-background-depth-1',
'text-bolt-elements-textPrimary',
'hover:bg-bolt-elements-background-depth-2',
'border border-bolt-elements-borderColor',
'h-10 px-4 py-2 min-w-[120px] justify-center',
'transition-all duration-200 ease-in-out',
className,
)}
disabled={isLoading}
>
<div className="i-ph:upload-simple" />
<span className="i-ph:upload-simple w-4 h-4" />
{isLoading ? 'Importing...' : 'Import Folder'}
</button>
</Button>
</>
);
};

View File

@@ -7,6 +7,7 @@ import { Artifact } from './Artifact';
import { CodeBlock } from './CodeBlock';
import styles from './Markdown.module.scss';
import ThoughtBox from './ThoughtBox';
const logger = createScopedLogger('MarkdownComponent');
@@ -32,6 +33,10 @@ export const Markdown = memo(({ children, html = false, limitedMarkdown = false
return <Artifact messageId={messageId} />;
}
if (className?.includes('__boltThought__')) {
return <ThoughtBox title="Thought process">{children}</ThoughtBox>;
}
return (
<div className={className} {...props}>
{children}

View File

@@ -1,5 +1,5 @@
import type { Message } from 'ai';
import React, { Fragment } from 'react';
import { Fragment } from 'react';
import { classNames } from '~/utils/classNames';
import { AssistantMessage } from './AssistantMessage';
import { UserMessage } from './UserMessage';
@@ -7,7 +7,10 @@ import { useLocation } from '@remix-run/react';
import { db, chatId } from '~/lib/persistence/useChatHistory';
import { forkChat } from '~/lib/persistence/db';
import { toast } from 'react-toastify';
import WithTooltip from '~/components/ui/Tooltip';
import { useStore } from '@nanostores/react';
import { profileStore } from '~/lib/stores/profile';
import { forwardRef } from 'react';
import type { ForwardedRef } from 'react';
interface MessagesProps {
id?: string;
@@ -16,100 +19,92 @@ interface MessagesProps {
messages?: Message[];
}
export const Messages = React.forwardRef<HTMLDivElement, MessagesProps>((props: MessagesProps, ref) => {
const { id, isStreaming = false, messages = [] } = props;
const location = useLocation();
export const Messages = forwardRef<HTMLDivElement, MessagesProps>(
(props: MessagesProps, ref: ForwardedRef<HTMLDivElement> | undefined) => {
const { id, isStreaming = false, messages = [] } = props;
const location = useLocation();
const profile = useStore(profileStore);
const handleRewind = (messageId: string) => {
const searchParams = new URLSearchParams(location.search);
searchParams.set('rewindTo', messageId);
window.location.search = searchParams.toString();
};
const handleRewind = (messageId: string) => {
const searchParams = new URLSearchParams(location.search);
searchParams.set('rewindTo', messageId);
window.location.search = searchParams.toString();
};
const handleFork = async (messageId: string) => {
try {
if (!db || !chatId.get()) {
toast.error('Chat persistence is not available');
return;
const handleFork = async (messageId: string) => {
try {
if (!db || !chatId.get()) {
toast.error('Chat persistence is not available');
return;
}
const urlId = await forkChat(db, chatId.get()!, messageId);
window.location.href = `/chat/${urlId}`;
} catch (error) {
toast.error('Failed to fork chat: ' + (error as Error).message);
}
};
const urlId = await forkChat(db, chatId.get()!, messageId);
window.location.href = `/chat/${urlId}`;
} catch (error) {
toast.error('Failed to fork chat: ' + (error as Error).message);
}
};
return (
<div id={id} className={props.className} ref={ref}>
{messages.length > 0
? messages.map((message, index) => {
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');
return (
<div id={id} ref={ref} className={props.className}>
{messages.length > 0
? messages.map((message, index) => {
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} />;
}
if (isHidden) {
return <Fragment key={index} />;
}
return (
<div
key={index}
className={classNames('flex gap-4 p-6 w-full rounded-[calc(0.75rem-1px)]', {
'bg-bolt-elements-messages-background': isUserMessage || !isStreaming || (isStreaming && !isLast),
'bg-gradient-to-b from-bolt-elements-messages-background from-30% to-transparent':
isStreaming && isLast,
'mt-4': !isFirst,
})}
>
{isUserMessage && (
<div className="flex items-center justify-center w-[34px] h-[34px] overflow-hidden bg-white text-gray-600 rounded-full shrink-0 self-start">
<div className="i-ph:user-fill text-xl"></div>
</div>
)}
<div className="grid grid-col-1 w-full">
{isUserMessage ? (
<UserMessage content={content} />
) : (
<AssistantMessage content={content} annotations={message.annotations} />
)}
</div>
{!isUserMessage && (
<div className="flex gap-2 flex-col lg:flex-row">
{messageId && (
<WithTooltip tooltip="Revert to this message">
<button
onClick={() => handleRewind(messageId)}
key="i-ph:arrow-u-up-left"
className={classNames(
'i-ph:arrow-u-up-left',
'text-xl text-bolt-elements-textSecondary hover:text-bolt-elements-textPrimary transition-colors',
)}
return (
<div
key={index}
className={classNames('flex gap-4 p-6 py-5 w-full rounded-[calc(0.75rem-1px)]', {
'bg-bolt-elements-messages-background': isUserMessage || !isStreaming || (isStreaming && !isLast),
'bg-gradient-to-b from-bolt-elements-messages-background from-30% to-transparent':
isStreaming && isLast,
'mt-4': !isFirst,
})}
>
{isUserMessage && (
<div className="flex items-center justify-center w-[40px] h-[40px] overflow-hidden bg-white dark:bg-gray-800 text-gray-600 dark:text-gray-500 rounded-full shrink-0 self-start">
{profile?.avatar ? (
<img
src={profile.avatar}
alt={profile?.username || 'User'}
className="w-full h-full object-cover"
loading="eager"
decoding="sync"
/>
</WithTooltip>
)}
<WithTooltip tooltip="Fork chat from this message">
<button
onClick={() => handleFork(messageId)}
key="i-ph:git-fork"
className={classNames(
'i-ph:git-fork',
'text-xl text-bolt-elements-textSecondary hover:text-bolt-elements-textPrimary transition-colors',
)}
) : (
<div className="i-ph:user-fill text-2xl" />
)}
</div>
)}
<div className="grid grid-col-1 w-full">
{isUserMessage ? (
<UserMessage content={content} />
) : (
<AssistantMessage
content={content}
annotations={message.annotations}
messageId={messageId}
onRewind={handleRewind}
onFork={handleFork}
/>
</WithTooltip>
)}
</div>
)}
</div>
);
})
: null}
{isStreaming && (
<div className="text-center w-full text-bolt-elements-textSecondary i-svg-spinners:3-dots-fade text-4xl mt-4"></div>
)}
</div>
);
});
</div>
);
})
: null}
{isStreaming && (
<div className="text-center w-full text-bolt-elements-item-contentAccent i-svg-spinners:3-dots-fade text-4xl mt-4"></div>
)}
</div>
);
},
);

View File

@@ -1,6 +1,8 @@
import type { ProviderInfo } from '~/types/model';
import { useEffect } from 'react';
import { useEffect, useState, useRef } from 'react';
import type { KeyboardEvent } from 'react';
import type { ModelInfo } from '~/lib/modules/llm/types';
import { classNames } from '~/utils/classNames';
interface ModelSelectorProps {
model?: string;
@@ -22,20 +24,178 @@ export const ModelSelector = ({
providerList,
modelLoading,
}: ModelSelectorProps) => {
// Load enabled providers from cookies
const [modelSearchQuery, setModelSearchQuery] = useState('');
const [isModelDropdownOpen, setIsModelDropdownOpen] = useState(false);
const [focusedModelIndex, setFocusedModelIndex] = useState(-1);
const modelSearchInputRef = useRef<HTMLInputElement>(null);
const modelOptionsRef = useRef<(HTMLDivElement | null)[]>([]);
const modelDropdownRef = useRef<HTMLDivElement>(null);
const [providerSearchQuery, setProviderSearchQuery] = useState('');
const [isProviderDropdownOpen, setIsProviderDropdownOpen] = useState(false);
const [focusedProviderIndex, setFocusedProviderIndex] = useState(-1);
const providerSearchInputRef = useRef<HTMLInputElement>(null);
const providerOptionsRef = useRef<(HTMLDivElement | null)[]>([]);
const providerDropdownRef = useRef<HTMLDivElement>(null);
// Update enabled providers when cookies change
useEffect(() => {
// If current provider is disabled, switch to first enabled provider
if (providerList.length == 0) {
const handleClickOutside = (event: MouseEvent) => {
if (modelDropdownRef.current && !modelDropdownRef.current.contains(event.target as Node)) {
setIsModelDropdownOpen(false);
setModelSearchQuery('');
}
if (providerDropdownRef.current && !providerDropdownRef.current.contains(event.target as Node)) {
setIsProviderDropdownOpen(false);
setProviderSearchQuery('');
}
};
document.addEventListener('mousedown', handleClickOutside);
return () => document.removeEventListener('mousedown', handleClickOutside);
}, []);
const filteredModels = [...modelList]
.filter((e) => e.provider === provider?.name && e.name)
.filter(
(model) =>
model.label.toLowerCase().includes(modelSearchQuery.toLowerCase()) ||
model.name.toLowerCase().includes(modelSearchQuery.toLowerCase()),
);
const filteredProviders = providerList.filter((p) =>
p.name.toLowerCase().includes(providerSearchQuery.toLowerCase()),
);
useEffect(() => {
setFocusedModelIndex(-1);
}, [modelSearchQuery, isModelDropdownOpen]);
useEffect(() => {
setFocusedProviderIndex(-1);
}, [providerSearchQuery, isProviderDropdownOpen]);
useEffect(() => {
if (isModelDropdownOpen && modelSearchInputRef.current) {
modelSearchInputRef.current.focus();
}
}, [isModelDropdownOpen]);
useEffect(() => {
if (isProviderDropdownOpen && providerSearchInputRef.current) {
providerSearchInputRef.current.focus();
}
}, [isProviderDropdownOpen]);
const handleModelKeyDown = (e: KeyboardEvent<HTMLDivElement>) => {
if (!isModelDropdownOpen) {
return;
}
if (provider && !providerList.map((p) => p.name).includes(provider.name)) {
switch (e.key) {
case 'ArrowDown':
e.preventDefault();
setFocusedModelIndex((prev) => (prev + 1 >= filteredModels.length ? 0 : prev + 1));
break;
case 'ArrowUp':
e.preventDefault();
setFocusedModelIndex((prev) => (prev - 1 < 0 ? filteredModels.length - 1 : prev - 1));
break;
case 'Enter':
e.preventDefault();
if (focusedModelIndex >= 0 && focusedModelIndex < filteredModels.length) {
const selectedModel = filteredModels[focusedModelIndex];
setModel?.(selectedModel.name);
setIsModelDropdownOpen(false);
setModelSearchQuery('');
}
break;
case 'Escape':
e.preventDefault();
setIsModelDropdownOpen(false);
setModelSearchQuery('');
break;
case 'Tab':
if (!e.shiftKey && focusedModelIndex === filteredModels.length - 1) {
setIsModelDropdownOpen(false);
}
break;
}
};
const handleProviderKeyDown = (e: KeyboardEvent<HTMLDivElement>) => {
if (!isProviderDropdownOpen) {
return;
}
switch (e.key) {
case 'ArrowDown':
e.preventDefault();
setFocusedProviderIndex((prev) => (prev + 1 >= filteredProviders.length ? 0 : prev + 1));
break;
case 'ArrowUp':
e.preventDefault();
setFocusedProviderIndex((prev) => (prev - 1 < 0 ? filteredProviders.length - 1 : prev - 1));
break;
case 'Enter':
e.preventDefault();
if (focusedProviderIndex >= 0 && focusedProviderIndex < filteredProviders.length) {
const selectedProvider = filteredProviders[focusedProviderIndex];
if (setProvider) {
setProvider(selectedProvider);
const firstModel = modelList.find((m) => m.provider === selectedProvider.name);
if (firstModel && setModel) {
setModel(firstModel.name);
}
}
setIsProviderDropdownOpen(false);
setProviderSearchQuery('');
}
break;
case 'Escape':
e.preventDefault();
setIsProviderDropdownOpen(false);
setProviderSearchQuery('');
break;
case 'Tab':
if (!e.shiftKey && focusedProviderIndex === filteredProviders.length - 1) {
setIsProviderDropdownOpen(false);
}
break;
}
};
useEffect(() => {
if (focusedModelIndex >= 0 && modelOptionsRef.current[focusedModelIndex]) {
modelOptionsRef.current[focusedModelIndex]?.scrollIntoView({ block: 'nearest' });
}
}, [focusedModelIndex]);
useEffect(() => {
if (focusedProviderIndex >= 0 && providerOptionsRef.current[focusedProviderIndex]) {
providerOptionsRef.current[focusedProviderIndex]?.scrollIntoView({ block: 'nearest' });
}
}, [focusedProviderIndex]);
useEffect(() => {
if (providerList.length === 0) {
return;
}
if (provider && !providerList.some((p) => p.name === provider.name)) {
const firstEnabledProvider = providerList[0];
setProvider?.(firstEnabledProvider);
// Also update the model to the first available one for the new provider
const firstModel = modelList.find((m) => m.provider === firstEnabledProvider.name);
if (firstModel) {
@@ -56,51 +216,252 @@ export const ModelSelector = ({
}
return (
<div className="mb-2 flex gap-2 flex-col sm:flex-row">
<select
value={provider?.name ?? ''}
onChange={(e) => {
const newProvider = providerList.find((p: ProviderInfo) => p.name === e.target.value);
<div className="flex gap-2 flex-col sm:flex-row">
{/* Provider Combobox */}
<div className="relative flex w-full" onKeyDown={handleProviderKeyDown} ref={providerDropdownRef}>
<div
className={classNames(
'w-full p-2 rounded-lg border border-bolt-elements-borderColor',
'bg-bolt-elements-prompt-background text-bolt-elements-textPrimary',
'focus-within:outline-none focus-within:ring-2 focus-within:ring-bolt-elements-focus',
'transition-all cursor-pointer',
isProviderDropdownOpen ? 'ring-2 ring-bolt-elements-focus' : undefined,
)}
onClick={() => setIsProviderDropdownOpen(!isProviderDropdownOpen)}
onKeyDown={(e) => {
if (e.key === 'Enter' || e.key === ' ') {
e.preventDefault();
setIsProviderDropdownOpen(!isProviderDropdownOpen);
}
}}
role="combobox"
aria-expanded={isProviderDropdownOpen}
aria-controls="provider-listbox"
aria-haspopup="listbox"
tabIndex={0}
>
<div className="flex items-center justify-between">
<div className="truncate">{provider?.name || 'Select provider'}</div>
<div
className={classNames(
'i-ph:caret-down w-4 h-4 text-bolt-elements-textSecondary opacity-75',
isProviderDropdownOpen ? 'rotate-180' : undefined,
)}
/>
</div>
</div>
if (newProvider && setProvider) {
setProvider(newProvider);
}
{isProviderDropdownOpen && (
<div
className="absolute z-20 w-full mt-1 py-1 rounded-lg border border-bolt-elements-borderColor bg-bolt-elements-background-depth-2 shadow-lg"
role="listbox"
id="provider-listbox"
>
<div className="px-2 pb-2">
<div className="relative">
<input
ref={providerSearchInputRef}
type="text"
value={providerSearchQuery}
onChange={(e) => setProviderSearchQuery(e.target.value)}
placeholder="Search providers..."
className={classNames(
'w-full pl-2 py-1.5 rounded-md text-sm',
'bg-bolt-elements-background-depth-2 border border-bolt-elements-borderColor',
'text-bolt-elements-textPrimary placeholder:text-bolt-elements-textTertiary',
'focus:outline-none focus:ring-2 focus:ring-bolt-elements-focus',
'transition-all',
)}
onClick={(e) => e.stopPropagation()}
role="searchbox"
aria-label="Search providers"
/>
<div className="absolute left-2.5 top-1/2 -translate-y-1/2">
<span className="i-ph:magnifying-glass text-bolt-elements-textTertiary" />
</div>
</div>
</div>
const firstModel = [...modelList].find((m) => m.provider === e.target.value);
<div
className={classNames(
'max-h-60 overflow-y-auto',
'sm:scrollbar-none',
'[&::-webkit-scrollbar]:w-2 [&::-webkit-scrollbar]:h-2',
'[&::-webkit-scrollbar-thumb]:bg-bolt-elements-borderColor',
'[&::-webkit-scrollbar-thumb]:hover:bg-bolt-elements-borderColorHover',
'[&::-webkit-scrollbar-thumb]:rounded-full',
'[&::-webkit-scrollbar-track]:bg-bolt-elements-background-depth-2',
'[&::-webkit-scrollbar-track]:rounded-full',
'sm:[&::-webkit-scrollbar]:w-1.5 sm:[&::-webkit-scrollbar]:h-1.5',
'sm:hover:[&::-webkit-scrollbar-thumb]:bg-bolt-elements-borderColor/50',
'sm:hover:[&::-webkit-scrollbar-thumb:hover]:bg-bolt-elements-borderColor',
'sm:[&::-webkit-scrollbar-track]:bg-transparent',
)}
>
{filteredProviders.length === 0 ? (
<div className="px-3 py-2 text-sm text-bolt-elements-textTertiary">No providers found</div>
) : (
filteredProviders.map((providerOption, index) => (
<div
ref={(el) => (providerOptionsRef.current[index] = el)}
key={providerOption.name}
role="option"
aria-selected={provider?.name === providerOption.name}
className={classNames(
'px-3 py-2 text-sm cursor-pointer',
'hover:bg-bolt-elements-background-depth-3',
'text-bolt-elements-textPrimary',
'outline-none',
provider?.name === providerOption.name || focusedProviderIndex === index
? 'bg-bolt-elements-background-depth-2'
: undefined,
focusedProviderIndex === index ? 'ring-1 ring-inset ring-bolt-elements-focus' : undefined,
)}
onClick={(e) => {
e.stopPropagation();
if (firstModel && setModel) {
setModel(firstModel.name);
}
}}
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"
>
{providerList.map((provider: ProviderInfo) => (
<option key={provider.name} value={provider.name}>
{provider.name}
</option>
))}
</select>
<select
key={provider?.name}
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}
>
{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>
))
if (setProvider) {
setProvider(providerOption);
const firstModel = modelList.find((m) => m.provider === providerOption.name);
if (firstModel && setModel) {
setModel(firstModel.name);
}
}
setIsProviderDropdownOpen(false);
setProviderSearchQuery('');
}}
tabIndex={focusedProviderIndex === index ? 0 : -1}
>
{providerOption.name}
</div>
))
)}
</div>
</div>
)}
</select>
</div>
{/* Model Combobox */}
<div className="relative flex w-full min-w-[70%]" onKeyDown={handleModelKeyDown} ref={modelDropdownRef}>
<div
className={classNames(
'w-full p-2 rounded-lg border border-bolt-elements-borderColor',
'bg-bolt-elements-prompt-background text-bolt-elements-textPrimary',
'focus-within:outline-none focus-within:ring-2 focus-within:ring-bolt-elements-focus',
'transition-all cursor-pointer',
isModelDropdownOpen ? 'ring-2 ring-bolt-elements-focus' : undefined,
)}
onClick={() => setIsModelDropdownOpen(!isModelDropdownOpen)}
onKeyDown={(e) => {
if (e.key === 'Enter' || e.key === ' ') {
e.preventDefault();
setIsModelDropdownOpen(!isModelDropdownOpen);
}
}}
role="combobox"
aria-expanded={isModelDropdownOpen}
aria-controls="model-listbox"
aria-haspopup="listbox"
tabIndex={0}
>
<div className="flex items-center justify-between">
<div className="truncate">{modelList.find((m) => m.name === model)?.label || 'Select model'}</div>
<div
className={classNames(
'i-ph:caret-down w-4 h-4 text-bolt-elements-textSecondary opacity-75',
isModelDropdownOpen ? 'rotate-180' : undefined,
)}
/>
</div>
</div>
{isModelDropdownOpen && (
<div
className="absolute z-10 w-full mt-1 py-1 rounded-lg border border-bolt-elements-borderColor bg-bolt-elements-background-depth-2 shadow-lg"
role="listbox"
id="model-listbox"
>
<div className="px-2 pb-2">
<div className="relative">
<input
ref={modelSearchInputRef}
type="text"
value={modelSearchQuery}
onChange={(e) => setModelSearchQuery(e.target.value)}
placeholder="Search models..."
className={classNames(
'w-full pl-2 py-1.5 rounded-md text-sm',
'bg-bolt-elements-background-depth-2 border border-bolt-elements-borderColor',
'text-bolt-elements-textPrimary placeholder:text-bolt-elements-textTertiary',
'focus:outline-none focus:ring-2 focus:ring-bolt-elements-focus',
'transition-all',
)}
onClick={(e) => e.stopPropagation()}
role="searchbox"
aria-label="Search models"
/>
<div className="absolute left-2.5 top-1/2 -translate-y-1/2">
<span className="i-ph:magnifying-glass text-bolt-elements-textTertiary" />
</div>
</div>
</div>
<div
className={classNames(
'max-h-60 overflow-y-auto',
'sm:scrollbar-none',
'[&::-webkit-scrollbar]:w-2 [&::-webkit-scrollbar]:h-2',
'[&::-webkit-scrollbar-thumb]:bg-bolt-elements-borderColor',
'[&::-webkit-scrollbar-thumb]:hover:bg-bolt-elements-borderColorHover',
'[&::-webkit-scrollbar-thumb]:rounded-full',
'[&::-webkit-scrollbar-track]:bg-bolt-elements-background-depth-2',
'[&::-webkit-scrollbar-track]:rounded-full',
'sm:[&::-webkit-scrollbar]:w-1.5 sm:[&::-webkit-scrollbar]:h-1.5',
'sm:hover:[&::-webkit-scrollbar-thumb]:bg-bolt-elements-borderColor/50',
'sm:hover:[&::-webkit-scrollbar-thumb:hover]:bg-bolt-elements-borderColor',
'sm:[&::-webkit-scrollbar-track]:bg-transparent',
)}
>
{modelLoading === 'all' || modelLoading === provider?.name ? (
<div className="px-3 py-2 text-sm text-bolt-elements-textTertiary">Loading...</div>
) : filteredModels.length === 0 ? (
<div className="px-3 py-2 text-sm text-bolt-elements-textTertiary">No models found</div>
) : (
filteredModels.map((modelOption, index) => (
<div
ref={(el) => (modelOptionsRef.current[index] = el)}
key={index} // Consider using modelOption.name if unique
role="option"
aria-selected={model === modelOption.name}
className={classNames(
'px-3 py-2 text-sm cursor-pointer',
'hover:bg-bolt-elements-background-depth-3',
'text-bolt-elements-textPrimary',
'outline-none',
model === modelOption.name || focusedModelIndex === index
? 'bg-bolt-elements-background-depth-2'
: undefined,
focusedModelIndex === index ? 'ring-1 ring-inset ring-bolt-elements-focus' : undefined,
)}
onClick={(e) => {
e.stopPropagation();
setModel?.(modelOption.name);
setIsModelDropdownOpen(false);
setModelSearchQuery('');
}}
tabIndex={focusedModelIndex === index ? 0 : -1}
>
{modelOption.label}
</div>
))
)}
</div>
</div>
)}
</div>
</div>
);
};

View File

@@ -0,0 +1,51 @@
import { useStore } from '@nanostores/react';
import { netlifyConnection, fetchNetlifyStats } from '~/lib/stores/netlify';
import { chatId } from '~/lib/persistence/useChatHistory';
import * as Tooltip from '@radix-ui/react-tooltip';
import { useEffect } from 'react';
export function NetlifyDeploymentLink() {
const connection = useStore(netlifyConnection);
const currentChatId = useStore(chatId);
useEffect(() => {
if (connection.token && currentChatId) {
fetchNetlifyStats(connection.token);
}
}, [connection.token, currentChatId]);
const deployedSite = connection.stats?.sites?.find((site) => site.name.includes(`bolt-diy-${currentChatId}`));
if (!deployedSite) {
return null;
}
return (
<Tooltip.Provider>
<Tooltip.Root>
<Tooltip.Trigger asChild>
<a
href={deployedSite.url}
target="_blank"
rel="noopener noreferrer"
className="inline-flex items-center justify-center w-8 h-8 rounded hover:bg-bolt-elements-item-backgroundActive text-bolt-elements-textSecondary hover:text-[#00AD9F] z-50"
onClick={(e) => {
e.stopPropagation(); // This is to prevent click from bubbling up
}}
>
<div className="i-ph:link w-4 h-4 hover:text-blue-400" />
</a>
</Tooltip.Trigger>
<Tooltip.Portal>
<Tooltip.Content
className="px-3 py-2 rounded bg-bolt-elements-background-depth-3 text-bolt-elements-textPrimary text-xs z-50"
sideOffset={5}
>
{deployedSite.url}
<Tooltip.Arrow className="fill-bolt-elements-background-depth-3" />
</Tooltip.Content>
</Tooltip.Portal>
</Tooltip.Root>
</Tooltip.Provider>
);
}

View File

@@ -0,0 +1,110 @@
import { AnimatePresence, motion } from 'framer-motion';
import React, { useState } from 'react';
import type { ProgressAnnotation } from '~/types/context';
import { classNames } from '~/utils/classNames';
import { cubicEasingFn } from '~/utils/easings';
export default function ProgressCompilation({ data }: { data?: ProgressAnnotation[] }) {
const [progressList, setProgressList] = React.useState<ProgressAnnotation[]>([]);
const [expanded, setExpanded] = useState(false);
React.useEffect(() => {
if (!data || data.length == 0) {
setProgressList([]);
return;
}
const progressMap = new Map<string, ProgressAnnotation>();
data.forEach((x) => {
const existingProgress = progressMap.get(x.label);
if (existingProgress && existingProgress.status === 'complete') {
return;
}
progressMap.set(x.label, x);
});
const newData = Array.from(progressMap.values());
newData.sort((a, b) => a.order - b.order);
setProgressList(newData);
}, [data]);
if (progressList.length === 0) {
return <></>;
}
return (
<AnimatePresence>
<div
className={classNames(
'bg-bolt-elements-background-depth-2',
'border border-bolt-elements-borderColor',
'shadow-lg rounded-lg relative w-full max-w-chat mx-auto z-prompt',
'p-1',
)}
>
<div
className={classNames(
'bg-bolt-elements-item-backgroundAccent',
'p-1 rounded-lg text-bolt-elements-item-contentAccent',
'flex ',
)}
>
<div className="flex-1">
<AnimatePresence>
{expanded ? (
<motion.div
className="actions"
initial={{ height: 0 }}
animate={{ height: 'auto' }}
exit={{ height: '0px' }}
transition={{ duration: 0.15 }}
>
{progressList.map((x, i) => {
return <ProgressItem key={i} progress={x} />;
})}
</motion.div>
) : (
<ProgressItem progress={progressList.slice(-1)[0]} />
)}
</AnimatePresence>
</div>
<motion.button
initial={{ width: 0 }}
animate={{ width: 'auto' }}
exit={{ width: 0 }}
transition={{ duration: 0.15, ease: cubicEasingFn }}
className=" p-1 rounded-lg bg-bolt-elements-item-backgroundAccent hover:bg-bolt-elements-artifacts-backgroundHover"
onClick={() => setExpanded((v) => !v)}
>
<div className={expanded ? 'i-ph:caret-up-bold' : 'i-ph:caret-down-bold'}></div>
</motion.button>
</div>
</div>
</AnimatePresence>
);
}
const ProgressItem = ({ progress }: { progress: ProgressAnnotation }) => {
return (
<motion.div
className={classNames('flex text-sm gap-3')}
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0 }}
transition={{ duration: 0.15 }}
>
<div className="flex items-center gap-1.5 ">
<div>
{progress.status === 'in-progress' ? (
<div className="i-svg-spinners:90-ring-with-bg"></div>
) : progress.status === 'complete' ? (
<div className="i-ph:check"></div>
) : null}
</div>
{/* {x.label} */}
</div>
{progress.message}
</motion.div>
);
};

View File

@@ -11,10 +11,11 @@ const FrameworkLink: React.FC<FrameworkLinkProps> = ({ template }) => (
href={`/git?url=https://github.com/${template.githubRepo}.git`}
data-state="closed"
data-discover="true"
className="items-center justify-center "
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`}
className={`inline-block ${template.icon} w-8 h-8 text-4xl transition-theme opacity-25 hover:opacity-100 hover:text-purple-500 dark:text-white dark:opacity-50 dark:hover:opacity-100 dark:hover:text-purple-400 transition-all`}
title={template.label}
/>
</a>
);
@@ -24,7 +25,7 @@ const StarterTemplates: React.FC = () => {
<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">
<div className="flex flex-wrap justify-center items-center gap-4 max-w-sm">
{STARTER_TEMPLATES.map((template) => (
<FrameworkLink key={template.name} template={template} />
))}

View File

@@ -0,0 +1,199 @@
import { AnimatePresence, motion } from 'framer-motion';
import type { SupabaseAlert } from '~/types/actions';
import { classNames } from '~/utils/classNames';
import { supabaseConnection } from '~/lib/stores/supabase';
import { useStore } from '@nanostores/react';
import { useState } from 'react';
interface Props {
alert: SupabaseAlert;
clearAlert: () => void;
postMessage: (message: string) => void;
}
export function SupabaseChatAlert({ alert, clearAlert, postMessage }: Props) {
const { content } = alert;
const connection = useStore(supabaseConnection);
const [isExecuting, setIsExecuting] = useState(false);
const [isCollapsed, setIsCollapsed] = useState(true);
// Determine connection state
const isConnected = !!(connection.token && connection.selectedProjectId);
// Set title and description based on connection state
const title = isConnected ? 'Supabase Query' : 'Supabase Connection Required';
const description = isConnected ? 'Execute database query' : 'Supabase connection required';
const message = isConnected
? 'Please review the proposed changes and apply them to your database.'
: 'Please connect to Supabase to continue with this operation.';
const handleConnectClick = () => {
// Dispatch an event to open the Supabase connection dialog
document.dispatchEvent(new CustomEvent('open-supabase-connection'));
};
// Determine if we should show the Connect button or Apply Changes button
const showConnectButton = !isConnected;
const executeSupabaseAction = async (sql: string) => {
if (!connection.token || !connection.selectedProjectId) {
console.error('No Supabase token or project selected');
return;
}
setIsExecuting(true);
try {
const response = await fetch('/api/supabase/query', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${connection.token}`,
},
body: JSON.stringify({
projectId: connection.selectedProjectId,
query: sql,
}),
});
if (!response.ok) {
const errorData = (await response.json()) as any;
throw new Error(`Supabase query failed: ${errorData.error?.message || response.statusText}`);
}
const result = await response.json();
console.log('Supabase query executed successfully:', result);
clearAlert();
} catch (error) {
console.error('Failed to execute Supabase action:', error);
postMessage(
`*Error executing Supabase query please fix and return the query again*\n\`\`\`\n${error instanceof Error ? error.message : String(error)}\n\`\`\`\n`,
);
} finally {
setIsExecuting(false);
}
};
const cleanSqlContent = (content: string) => {
if (!content) {
return '';
}
let cleaned = content.replace(/\/\*[\s\S]*?\*\//g, '');
cleaned = cleaned.replace(/(--).*$/gm, '').replace(/(#).*$/gm, '');
const statements = cleaned
.split(';')
.map((stmt) => stmt.trim())
.filter((stmt) => stmt.length > 0)
.join(';\n\n');
return statements;
};
return (
<AnimatePresence>
<motion.div
initial={{ opacity: 0, y: -20 }}
animate={{ opacity: 1, y: 0 }}
exit={{ opacity: 0, y: -20 }}
transition={{ duration: 0.3 }}
className="max-w-chat rounded-lg border-l-2 border-l-[#098F5F] border border-bolt-elements-borderColor bg-bolt-elements-background-depth-2"
>
{/* Header */}
<div className="p-4 pb-2">
<div className="flex items-center gap-2">
<img height="10" width="18" crossOrigin="anonymous" src="https://cdn.simpleicons.org/supabase" />
<h3 className="text-sm font-medium text-[#3DCB8F]">{title}</h3>
</div>
</div>
{/* SQL Content */}
<div className="px-4">
{!isConnected ? (
<div className="p-3 rounded-md bg-bolt-elements-background-depth-3">
<span className="text-sm text-bolt-elements-textPrimary">
You must first connect to Supabase and select a project.
</span>
</div>
) : (
<>
<div
className="flex items-center p-2 rounded-md bg-bolt-elements-background-depth-3 cursor-pointer"
onClick={() => setIsCollapsed(!isCollapsed)}
>
<div className="i-ph:database text-bolt-elements-textPrimary mr-2"></div>
<span className="text-sm text-bolt-elements-textPrimary flex-grow">
{description || 'Create table and setup auth'}
</span>
<div
className={`i-ph:caret-up text-bolt-elements-textPrimary transition-transform ${isCollapsed ? 'rotate-180' : ''}`}
></div>
</div>
{!isCollapsed && content && (
<div className="mt-2 p-3 bg-bolt-elements-background-depth-4 rounded-md overflow-auto max-h-60 font-mono text-xs text-bolt-elements-textSecondary">
<pre>{cleanSqlContent(content)}</pre>
</div>
)}
</>
)}
</div>
{/* Message and Actions */}
<div className="p-4">
<p className="text-sm text-bolt-elements-textSecondary mb-4">{message}</p>
<div className="flex gap-2">
{showConnectButton ? (
<button
onClick={handleConnectClick}
className={classNames(
`px-3 py-2 rounded-md text-sm font-medium`,
'bg-[#098F5F]',
'hover:bg-[#0aa06c]',
'focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-green-500',
'text-white',
'flex items-center gap-1.5',
)}
>
Connect to Supabase
</button>
) : (
<button
onClick={() => executeSupabaseAction(content)}
disabled={isExecuting}
className={classNames(
`px-3 py-2 rounded-md text-sm font-medium`,
'bg-[#098F5F]',
'hover:bg-[#0aa06c]',
'focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-green-500',
'text-white',
'flex items-center gap-1.5',
isExecuting ? 'opacity-70 cursor-not-allowed' : '',
)}
>
{isExecuting ? 'Applying...' : 'Apply Changes'}
</button>
)}
<button
onClick={clearAlert}
disabled={isExecuting}
className={classNames(
`px-3 py-2 rounded-md text-sm font-medium`,
'bg-[#503B26]',
'hover:bg-[#774f28]',
'focus:outline-none',
'text-[#F79007]',
isExecuting ? 'opacity-70 cursor-not-allowed' : '',
)}
>
Dismiss
</button>
</div>
</div>
</motion.div>
</AnimatePresence>
);
}

View File

@@ -0,0 +1,339 @@
import { useEffect } from 'react';
import { useSupabaseConnection } from '~/lib/hooks/useSupabaseConnection';
import { classNames } from '~/utils/classNames';
import { useStore } from '@nanostores/react';
import { chatId } from '~/lib/persistence/useChatHistory';
import { fetchSupabaseStats } from '~/lib/stores/supabase';
import { Dialog, DialogRoot, DialogClose, DialogTitle, DialogButton } from '~/components/ui/Dialog';
export function SupabaseConnection() {
const {
connection: supabaseConn,
connecting,
fetchingStats,
isProjectsExpanded,
setIsProjectsExpanded,
isDropdownOpen: isDialogOpen,
setIsDropdownOpen: setIsDialogOpen,
handleConnect,
handleDisconnect,
selectProject,
handleCreateProject,
updateToken,
isConnected,
fetchProjectApiKeys,
} = useSupabaseConnection();
const currentChatId = useStore(chatId);
useEffect(() => {
const handleOpenConnectionDialog = () => {
setIsDialogOpen(true);
};
document.addEventListener('open-supabase-connection', handleOpenConnectionDialog);
return () => {
document.removeEventListener('open-supabase-connection', handleOpenConnectionDialog);
};
}, [setIsDialogOpen]);
useEffect(() => {
if (isConnected && currentChatId) {
const savedProjectId = localStorage.getItem(`supabase-project-${currentChatId}`);
/*
* If there's no saved project for this chat but there is a global selected project,
* use the global one instead of clearing it
*/
if (!savedProjectId && supabaseConn.selectedProjectId) {
// Save the current global project to this chat
localStorage.setItem(`supabase-project-${currentChatId}`, supabaseConn.selectedProjectId);
} else if (savedProjectId && savedProjectId !== supabaseConn.selectedProjectId) {
selectProject(savedProjectId);
}
}
}, [isConnected, currentChatId]);
useEffect(() => {
if (currentChatId && supabaseConn.selectedProjectId) {
localStorage.setItem(`supabase-project-${currentChatId}`, supabaseConn.selectedProjectId);
} else if (currentChatId && !supabaseConn.selectedProjectId) {
localStorage.removeItem(`supabase-project-${currentChatId}`);
}
}, [currentChatId, supabaseConn.selectedProjectId]);
useEffect(() => {
if (isConnected && supabaseConn.token) {
fetchSupabaseStats(supabaseConn.token).catch(console.error);
}
}, [isConnected, supabaseConn.token]);
useEffect(() => {
if (isConnected && supabaseConn.selectedProjectId && supabaseConn.token && !supabaseConn.credentials) {
fetchProjectApiKeys(supabaseConn.selectedProjectId).catch(console.error);
}
}, [isConnected, supabaseConn.selectedProjectId, supabaseConn.token, supabaseConn.credentials]);
return (
<div className="relative">
<div className="flex border border-bolt-elements-borderColor rounded-md overflow-hidden mr-2 text-sm">
<Button
active
disabled={connecting}
onClick={() => setIsDialogOpen(!isDialogOpen)}
className="hover:bg-bolt-elements-item-backgroundActive !text-white flex items-center gap-2"
>
<img
className="w-4 h-4"
height="20"
width="20"
crossOrigin="anonymous"
src="https://cdn.simpleicons.org/supabase"
/>
{isConnected && supabaseConn.project && (
<span className="ml-1 text-xs max-w-[100px] truncate">{supabaseConn.project.name}</span>
)}
</Button>
</div>
<DialogRoot open={isDialogOpen} onOpenChange={setIsDialogOpen}>
{isDialogOpen && (
<Dialog className="max-w-[520px] p-6">
{!isConnected ? (
<div className="space-y-4">
<DialogTitle>
<img
className="w-5 h-5"
height="24"
width="24"
crossOrigin="anonymous"
src="https://cdn.simpleicons.org/supabase"
/>
Connect to Supabase
</DialogTitle>
<div>
<label className="block text-sm text-bolt-elements-textSecondary mb-2">Access Token</label>
<input
type="password"
value={supabaseConn.token}
onChange={(e) => updateToken(e.target.value)}
disabled={connecting}
placeholder="Enter your Supabase access token"
className={classNames(
'w-full px-3 py-2 rounded-lg text-sm',
'bg-[#F8F8F8] dark:bg-[#1A1A1A]',
'border border-[#E5E5E5] dark:border-[#333333]',
'text-bolt-elements-textPrimary placeholder-bolt-elements-textTertiary',
'focus:outline-none focus:ring-1 focus:ring-[#3ECF8E]',
'disabled:opacity-50',
)}
/>
<div className="mt-2 text-sm text-bolt-elements-textSecondary">
<a
href="https://app.supabase.com/account/tokens"
target="_blank"
rel="noopener noreferrer"
className="text-[#3ECF8E] hover:underline inline-flex items-center gap-1"
>
Get your token
<div className="i-ph:arrow-square-out w-4 h-4" />
</a>
</div>
</div>
<div className="flex justify-end gap-2 mt-6">
<DialogClose asChild>
<DialogButton type="secondary">Cancel</DialogButton>
</DialogClose>
<button
onClick={handleConnect}
disabled={connecting || !supabaseConn.token}
className={classNames(
'px-4 py-2 rounded-lg text-sm flex items-center gap-2',
'bg-[#3ECF8E] text-white',
'hover:bg-[#3BBF84]',
'disabled:opacity-50 disabled:cursor-not-allowed',
)}
>
{connecting ? (
<>
<div className="i-ph:spinner-gap animate-spin" />
Connecting...
</>
) : (
<>
<div className="i-ph:plug-charging w-4 h-4" />
Connect
</>
)}
</button>
</div>
</div>
) : (
<div className="space-y-4">
<div className="flex items-center justify-between mb-2">
<DialogTitle>
<img
className="w-5 h-5"
height="24"
width="24"
crossOrigin="anonymous"
src="https://cdn.simpleicons.org/supabase"
/>
Supabase Connection
</DialogTitle>
</div>
<div className="flex items-center gap-4 p-3 bg-[#F8F8F8] dark:bg-[#1A1A1A] rounded-lg">
<div>
<h4 className="text-sm font-medium text-bolt-elements-textPrimary">{supabaseConn.user?.email}</h4>
<p className="text-xs text-bolt-elements-textSecondary">Role: {supabaseConn.user?.role}</p>
</div>
</div>
{fetchingStats ? (
<div className="flex items-center gap-2 text-sm text-bolt-elements-textSecondary">
<div className="i-ph:spinner-gap w-4 h-4 animate-spin" />
Fetching projects...
</div>
) : (
<div>
<div className="flex items-center justify-between mb-2">
<button
onClick={() => setIsProjectsExpanded(!isProjectsExpanded)}
className="bg-transparent text-left text-sm font-medium text-bolt-elements-textPrimary flex items-center gap-2"
>
<div className="i-ph:database w-4 h-4" />
Your Projects ({supabaseConn.stats?.totalProjects || 0})
<div
className={classNames(
'i-ph:caret-down w-4 h-4 transition-transform',
isProjectsExpanded ? 'rotate-180' : '',
)}
/>
</button>
<div className="flex items-center gap-2">
<button
onClick={() => fetchSupabaseStats(supabaseConn.token)}
className="px-2 py-1 rounded-md text-xs bg-[#F0F0F0] dark:bg-[#252525] text-bolt-elements-textSecondary hover:bg-[#E5E5E5] dark:hover:bg-[#333333] flex items-center gap-1"
title="Refresh projects list"
>
<div className="i-ph:arrows-clockwise w-3 h-3" />
Refresh
</button>
<button
onClick={() => handleCreateProject()}
className="px-2 py-1 rounded-md text-xs bg-[#3ECF8E] text-white hover:bg-[#3BBF84] flex items-center gap-1"
>
<div className="i-ph:plus w-3 h-3" />
New Project
</button>
</div>
</div>
{isProjectsExpanded && (
<>
{!supabaseConn.selectedProjectId && (
<div className="mb-2 p-3 bg-[#F8F8F8] dark:bg-[#1A1A1A] rounded-lg text-sm text-bolt-elements-textSecondary">
Select a project or create a new one for this chat
</div>
)}
{supabaseConn.stats?.projects?.length ? (
<div className="grid gap-2 max-h-60 overflow-y-auto">
{supabaseConn.stats.projects.map((project) => (
<div
key={project.id}
className="block p-3 rounded-lg border border-[#E5E5E5] dark:border-[#1A1A1A] hover:border-[#3ECF8E] dark:hover:border-[#3ECF8E] transition-colors"
>
<div className="flex items-center justify-between">
<div>
<h5 className="text-sm font-medium text-bolt-elements-textPrimary flex items-center gap-1">
<div className="i-ph:database w-3 h-3 text-[#3ECF8E]" />
{project.name}
</h5>
<div className="text-xs text-bolt-elements-textSecondary mt-1">
{project.region}
</div>
</div>
<button
onClick={() => selectProject(project.id)}
className={classNames(
'px-3 py-1 rounded-md text-xs',
supabaseConn.selectedProjectId === project.id
? 'bg-[#3ECF8E] text-white'
: 'bg-[#F0F0F0] dark:bg-[#252525] text-bolt-elements-textSecondary hover:bg-[#3ECF8E] hover:text-white',
)}
>
{supabaseConn.selectedProjectId === project.id ? (
<span className="flex items-center gap-1">
<div className="i-ph:check w-3 h-3" />
Selected
</span>
) : (
'Select'
)}
</button>
</div>
</div>
))}
</div>
) : (
<div className="text-sm text-bolt-elements-textSecondary flex items-center gap-2">
<div className="i-ph:info w-4 h-4" />
No projects found
</div>
)}
</>
)}
</div>
)}
<div className="flex justify-end gap-2 mt-6">
<DialogClose asChild>
<DialogButton type="secondary">Close</DialogButton>
</DialogClose>
<DialogButton type="danger" onClick={handleDisconnect}>
<div className="i-ph:plugs w-4 h-4" />
Disconnect
</DialogButton>
</div>
</div>
)}
</Dialog>
)}
</DialogRoot>
</div>
);
}
interface ButtonProps {
active?: boolean;
disabled?: boolean;
children?: any;
onClick?: VoidFunction;
className?: string;
}
function Button({ active = false, disabled = false, children, onClick, className }: ButtonProps) {
return (
<button
className={classNames(
'flex items-center p-1.5',
{
'bg-bolt-elements-item-backgroundDefault hover:bg-bolt-elements-item-backgroundActive text-bolt-elements-textTertiary hover:text-bolt-elements-textPrimary':
!active,
'bg-bolt-elements-item-backgroundDefault text-bolt-elements-item-contentAccent': active && !disabled,
'bg-bolt-elements-item-backgroundDefault text-alpha-gray-20 dark:text-alpha-white-20 cursor-not-allowed':
disabled,
},
className,
)}
onClick={onClick}
>
{children}
</button>
);
}

View File

@@ -0,0 +1,43 @@
import { useState, type PropsWithChildren } from 'react';
const ThoughtBox = ({ title, children }: PropsWithChildren<{ title: string }>) => {
const [isExpanded, setIsExpanded] = useState(false);
return (
<div
onClick={() => setIsExpanded(!isExpanded)}
className={`
bg-bolt-elements-background-depth-2
shadow-md
rounded-lg
cursor-pointer
transition-all
duration-300
${isExpanded ? 'max-h-96' : 'max-h-13'}
overflow-auto
border border-bolt-elements-borderColor
`}
>
<div className="p-4 flex items-center gap-4 rounded-lg text-bolt-elements-textSecondary font-medium leading-5 text-sm border border-bolt-elements-borderColor">
<div className="i-ph:brain-thin text-2xl" />
<div className="div">
<span> {title}</span>{' '}
{!isExpanded && <span className="text-bolt-elements-textTertiary"> - Click to expand</span>}
</div>
</div>
<div
className={`
transition-opacity
duration-300
p-4
rounded-lg
${isExpanded ? 'opacity-100' : 'opacity-0'}
`}
>
{children}
</div>
</div>
);
};
export default ThoughtBox;

View File

@@ -16,7 +16,7 @@ export function UserMessage({ content }: UserMessageProps) {
const images = content.filter((item) => item.type === 'image' && item.image);
return (
<div className="overflow-hidden pt-[4px]">
<div className="overflow-hidden flex items-center">
<div className="flex flex-col gap-4">
{textContent && <Markdown html>{textContent}</Markdown>}
{images.map((item, index) => (
@@ -43,5 +43,6 @@ export function UserMessage({ content }: UserMessageProps) {
}
function stripMetadata(content: string) {
return content.replace(MODEL_REGEX, '').replace(PROVIDER_REGEX, '');
const artifactRegex = /<boltArtifact\s+[^>]*>[\s\S]*?<\/boltArtifact>/gm;
return content.replace(MODEL_REGEX, '').replace(PROVIDER_REGEX, '').replace(artifactRegex, '');
}

View File

@@ -0,0 +1,158 @@
import { useStore } from '@nanostores/react';
import { vercelConnection } from '~/lib/stores/vercel';
import { chatId } from '~/lib/persistence/useChatHistory';
import * as Tooltip from '@radix-ui/react-tooltip';
import { useEffect, useState } from 'react';
export function VercelDeploymentLink() {
const connection = useStore(vercelConnection);
const currentChatId = useStore(chatId);
const [deploymentUrl, setDeploymentUrl] = useState<string | null>(null);
const [isLoading, setIsLoading] = useState(false);
useEffect(() => {
async function fetchProjectData() {
if (!connection.token || !currentChatId) {
return;
}
// Check if we have a stored project ID for this chat
const projectId = localStorage.getItem(`vercel-project-${currentChatId}`);
if (!projectId) {
return;
}
setIsLoading(true);
try {
// Fetch projects directly from the API
const projectsResponse = await fetch('https://api.vercel.com/v9/projects', {
headers: {
Authorization: `Bearer ${connection.token}`,
'Content-Type': 'application/json',
},
cache: 'no-store',
});
if (!projectsResponse.ok) {
throw new Error(`Failed to fetch projects: ${projectsResponse.status}`);
}
const projectsData = (await projectsResponse.json()) as any;
const projects = projectsData.projects || [];
// Extract the chat number from currentChatId
const chatNumber = currentChatId.split('-')[0];
// Find project by matching the chat number in the name
const project = projects.find((p: { name: string | string[] }) => p.name.includes(`bolt-diy-${chatNumber}`));
if (project) {
// Fetch project details including deployments
const projectDetailsResponse = await fetch(`https://api.vercel.com/v9/projects/${project.id}`, {
headers: {
Authorization: `Bearer ${connection.token}`,
'Content-Type': 'application/json',
},
cache: 'no-store',
});
if (projectDetailsResponse.ok) {
const projectDetails = (await projectDetailsResponse.json()) as any;
// Try to get URL from production aliases first
if (projectDetails.targets?.production?.alias && projectDetails.targets.production.alias.length > 0) {
// Find the clean URL (without -projects.vercel.app)
const cleanUrl = projectDetails.targets.production.alias.find(
(a: string) => a.endsWith('.vercel.app') && !a.includes('-projects.vercel.app'),
);
if (cleanUrl) {
setDeploymentUrl(`https://${cleanUrl}`);
return;
} else {
// If no clean URL found, use the first alias
setDeploymentUrl(`https://${projectDetails.targets.production.alias[0]}`);
return;
}
}
}
// If no aliases or project details failed, try fetching deployments
const deploymentsResponse = await fetch(
`https://api.vercel.com/v6/deployments?projectId=${project.id}&limit=1`,
{
headers: {
Authorization: `Bearer ${connection.token}`,
'Content-Type': 'application/json',
},
cache: 'no-store',
},
);
if (deploymentsResponse.ok) {
const deploymentsData = (await deploymentsResponse.json()) as any;
if (deploymentsData.deployments && deploymentsData.deployments.length > 0) {
setDeploymentUrl(`https://${deploymentsData.deployments[0].url}`);
return;
}
}
}
// Fallback to API call if not found in fetched projects
const fallbackResponse = await fetch(`/api/vercel-deploy?projectId=${projectId}&token=${connection.token}`, {
method: 'GET',
});
const data = await fallbackResponse.json();
if ((data as { deploy?: { url?: string } }).deploy?.url) {
setDeploymentUrl((data as { deploy: { url: string } }).deploy.url);
} else if ((data as { project?: { url?: string } }).project?.url) {
setDeploymentUrl((data as { project: { url: string } }).project.url);
}
} catch (err) {
console.error('Error fetching Vercel deployment:', err);
} finally {
setIsLoading(false);
}
}
fetchProjectData();
}, [connection.token, currentChatId]);
if (!deploymentUrl) {
return null;
}
return (
<Tooltip.Provider>
<Tooltip.Root>
<Tooltip.Trigger asChild>
<a
href={deploymentUrl}
target="_blank"
rel="noopener noreferrer"
className="inline-flex items-center justify-center w-8 h-8 rounded hover:bg-bolt-elements-item-backgroundActive text-bolt-elements-textSecondary hover:text-[#000000] z-50"
onClick={(e) => {
e.stopPropagation();
}}
>
<div className={`i-ph:link w-4 h-4 hover:text-blue-400 ${isLoading ? 'animate-pulse' : ''}`} />
</a>
</Tooltip.Trigger>
<Tooltip.Portal>
<Tooltip.Content
className="px-3 py-2 rounded bg-bolt-elements-background-depth-3 text-bolt-elements-textPrimary text-xs z-50"
sideOffset={5}
>
{deploymentUrl}
<Tooltip.Arrow className="fill-bolt-elements-background-depth-3" />
</Tooltip.Content>
</Tooltip.Portal>
</Tooltip.Root>
</Tooltip.Provider>
);
}

View File

@@ -1,6 +1,8 @@
import type { Message } from 'ai';
import { toast } from 'react-toastify';
import { ImportFolderButton } from '~/components/chat/ImportFolderButton';
import { Button } from '~/components/ui/Button';
import { classNames } from '~/utils/classNames';
type ChatData = {
messages?: Message[]; // Standard Bolt format
@@ -57,19 +59,35 @@ export function ImportButtons(importChat: ((description: string, messages: Messa
/>
<div className="flex flex-col items-center gap-4 max-w-2xl text-center">
<div className="flex gap-2">
<button
<Button
onClick={() => {
const input = document.getElementById('chat-import');
input?.click();
}}
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"
variant="default"
size="lg"
className={classNames(
'gap-2 bg-bolt-elements-background-depth-1',
'text-bolt-elements-textPrimary',
'hover:bg-bolt-elements-background-depth-2',
'border border-bolt-elements-borderColor',
'h-10 px-4 py-2 min-w-[120px] justify-center',
'transition-all duration-200 ease-in-out',
)}
>
<div className="i-ph:upload-simple" />
<span className="i-ph:upload-simple w-4 h-4" />
Import Chat
</button>
</Button>
<ImportFolderButton
importChat={importChat}
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"
className={classNames(
'gap-2 bg-bolt-elements-background-depth-1',
'text-bolt-elements-textPrimary',
'hover:bg-bolt-elements-background-depth-2',
'border border-[rgba(0,0,0,0.08)] dark:border-[rgba(255,255,255,0.08)]',
'h-10 px-4 py-2 min-w-[120px] justify-center',
'transition-all duration-200 ease-in-out rounded-lg',
)}
/>
</div>
</div>

View File

@@ -0,0 +1,197 @@
import { AnimatePresence, motion } from 'framer-motion';
import { classNames } from '~/utils/classNames';
import type { DeployAlert } from '~/types/actions';
interface DeployAlertProps {
alert: DeployAlert;
clearAlert: () => void;
postMessage: (message: string) => void;
}
export default function DeployChatAlert({ alert, clearAlert, postMessage }: DeployAlertProps) {
const { type, title, description, content, url, stage, buildStatus, deployStatus } = alert;
// Determine if we should show the deployment progress
const showProgress = stage && (buildStatus || deployStatus);
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 mb-2`}
>
<div className="flex items-start">
{/* Icon */}
<motion.div
className="flex-shrink-0"
initial={{ scale: 0 }}
animate={{ scale: 1 }}
transition={{ delay: 0.2 }}
>
<div
className={classNames(
'text-xl',
type === 'success'
? 'i-ph:check-circle-duotone text-bolt-elements-icon-success'
: type === 'error'
? 'i-ph:warning-duotone text-bolt-elements-button-danger-text'
: 'i-ph:info-duotone text-bolt-elements-loader-progress',
)}
></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>{description}</p>
{/* Deployment Progress Visualization */}
{showProgress && (
<div className="mt-4 mb-2">
<div className="flex items-center space-x-2 mb-3">
{/* Build Step */}
<div className="flex items-center">
<div
className={classNames(
'w-6 h-6 rounded-full flex items-center justify-center',
buildStatus === 'running'
? 'bg-bolt-elements-loader-progress'
: buildStatus === 'complete'
? 'bg-bolt-elements-icon-success'
: buildStatus === 'failed'
? 'bg-bolt-elements-button-danger-background'
: 'bg-bolt-elements-textTertiary',
)}
>
{buildStatus === 'running' ? (
<div className="i-svg-spinners:90-ring-with-bg text-white text-xs"></div>
) : buildStatus === 'complete' ? (
<div className="i-ph:check text-white text-xs"></div>
) : buildStatus === 'failed' ? (
<div className="i-ph:x text-white text-xs"></div>
) : (
<span className="text-white text-xs">1</span>
)}
</div>
<span className="ml-2">Build</span>
</div>
{/* Connector Line */}
<div
className={classNames(
'h-0.5 w-8',
buildStatus === 'complete' ? 'bg-bolt-elements-icon-success' : 'bg-bolt-elements-textTertiary',
)}
></div>
{/* Deploy Step */}
<div className="flex items-center">
<div
className={classNames(
'w-6 h-6 rounded-full flex items-center justify-center',
deployStatus === 'running'
? 'bg-bolt-elements-loader-progress'
: deployStatus === 'complete'
? 'bg-bolt-elements-icon-success'
: deployStatus === 'failed'
? 'bg-bolt-elements-button-danger-background'
: 'bg-bolt-elements-textTertiary',
)}
>
{deployStatus === 'running' ? (
<div className="i-svg-spinners:90-ring-with-bg text-white text-xs"></div>
) : deployStatus === 'complete' ? (
<div className="i-ph:check text-white text-xs"></div>
) : deployStatus === 'failed' ? (
<div className="i-ph:x text-white text-xs"></div>
) : (
<span className="text-white text-xs">2</span>
)}
</div>
<span className="ml-2">Deploy</span>
</div>
</div>
</div>
)}
{content && (
<div className="text-xs text-bolt-elements-textSecondary p-2 bg-bolt-elements-background-depth-3 rounded mt-4 mb-4">
{content}
</div>
)}
{url && type === 'success' && (
<div className="mt-2">
<a
href={url}
target="_blank"
rel="noopener noreferrer"
className="text-bolt-elements-item-contentAccent hover:underline flex items-center"
>
<span className="mr-1">View deployed site</span>
<div className="i-ph:arrow-square-out"></div>
</a>
</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')}>
{type === 'error' && (
<button
onClick={() =>
postMessage(`*Fix this deployment error*\n\`\`\`\n${content || description}\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

@@ -0,0 +1,243 @@
import { toast } from 'react-toastify';
import { useStore } from '@nanostores/react';
import { netlifyConnection } from '~/lib/stores/netlify';
import { workbenchStore } from '~/lib/stores/workbench';
import { webcontainer } from '~/lib/webcontainer';
import { path } from '~/utils/path';
import { useState } from 'react';
import type { ActionCallbackData } from '~/lib/runtime/message-parser';
import { chatId } from '~/lib/persistence/useChatHistory';
export function useNetlifyDeploy() {
const [isDeploying, setIsDeploying] = useState(false);
const netlifyConn = useStore(netlifyConnection);
const currentChatId = useStore(chatId);
const handleNetlifyDeploy = async () => {
if (!netlifyConn.user || !netlifyConn.token) {
toast.error('Please connect to Netlify first in the settings tab!');
return false;
}
if (!currentChatId) {
toast.error('No active chat found');
return false;
}
try {
setIsDeploying(true);
const artifact = workbenchStore.firstArtifact;
if (!artifact) {
throw new Error('No active project found');
}
// Create a deployment artifact for visual feedback
const deploymentId = `deploy-artifact`;
workbenchStore.addArtifact({
id: deploymentId,
messageId: deploymentId,
title: 'Netlify Deployment',
type: 'standalone',
});
const deployArtifact = workbenchStore.artifacts.get()[deploymentId];
// Notify that build is starting
deployArtifact.runner.handleDeployAction('building', 'running', { source: 'netlify' });
// Set up build action
const actionId = 'build-' + Date.now();
const actionData: ActionCallbackData = {
messageId: 'netlify build',
artifactId: artifact.id,
actionId,
action: {
type: 'build' as const,
content: 'npm run build',
},
};
// Add the action first
artifact.runner.addAction(actionData);
// Then run it
await artifact.runner.runAction(actionData);
if (!artifact.runner.buildOutput) {
// Notify that build failed
deployArtifact.runner.handleDeployAction('building', 'failed', {
error: 'Build failed. Check the terminal for details.',
source: 'netlify',
});
throw new Error('Build failed');
}
// Notify that build succeeded and deployment is starting
deployArtifact.runner.handleDeployAction('deploying', 'running', { source: 'netlify' });
// Get the build files
const container = await webcontainer;
// Remove /home/project from buildPath if it exists
const buildPath = artifact.runner.buildOutput.path.replace('/home/project', '');
console.log('Original buildPath', buildPath);
// Check if the build path exists
let finalBuildPath = buildPath;
// List of common output directories to check if the specified build path doesn't exist
const commonOutputDirs = [buildPath, '/dist', '/build', '/out', '/output', '/.next', '/public'];
// Verify the build path exists, or try to find an alternative
let buildPathExists = false;
for (const dir of commonOutputDirs) {
try {
await container.fs.readdir(dir);
finalBuildPath = dir;
buildPathExists = true;
console.log(`Using build directory: ${finalBuildPath}`);
break;
} catch (error) {
// Directory doesn't exist, try the next one
console.log(`Directory ${dir} doesn't exist, trying next option. ${error}`);
continue;
}
}
if (!buildPathExists) {
throw new Error('Could not find build output directory. Please check your build configuration.');
}
async function getAllFiles(dirPath: string): Promise<Record<string, string>> {
const files: Record<string, string> = {};
const entries = await container.fs.readdir(dirPath, { withFileTypes: true });
for (const entry of entries) {
const fullPath = path.join(dirPath, entry.name);
if (entry.isFile()) {
const content = await container.fs.readFile(fullPath, 'utf-8');
// Remove build path prefix from the path
const deployPath = fullPath.replace(finalBuildPath, '');
files[deployPath] = content;
} else if (entry.isDirectory()) {
const subFiles = await getAllFiles(fullPath);
Object.assign(files, subFiles);
}
}
return files;
}
const fileContents = await getAllFiles(finalBuildPath);
// Use chatId instead of artifact.id
const existingSiteId = localStorage.getItem(`netlify-site-${currentChatId}`);
const response = await fetch('/api/netlify-deploy', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
siteId: existingSiteId || undefined,
files: fileContents,
token: netlifyConn.token,
chatId: currentChatId,
}),
});
const data = (await response.json()) as any;
if (!response.ok || !data.deploy || !data.site) {
console.error('Invalid deploy response:', data);
// Notify that deployment failed
deployArtifact.runner.handleDeployAction('deploying', 'failed', {
error: data.error || 'Invalid deployment response',
source: 'netlify',
});
throw new Error(data.error || 'Invalid deployment response');
}
const maxAttempts = 20; // 2 minutes timeout
let attempts = 0;
let deploymentStatus;
while (attempts < maxAttempts) {
try {
const statusResponse = await fetch(
`https://api.netlify.com/api/v1/sites/${data.site.id}/deploys/${data.deploy.id}`,
{
headers: {
Authorization: `Bearer ${netlifyConn.token}`,
},
},
);
deploymentStatus = (await statusResponse.json()) as any;
if (deploymentStatus.state === 'ready' || deploymentStatus.state === 'uploaded') {
break;
}
if (deploymentStatus.state === 'error') {
// Notify that deployment failed
deployArtifact.runner.handleDeployAction('deploying', 'failed', {
error: 'Deployment failed: ' + (deploymentStatus.error_message || 'Unknown error'),
source: 'netlify',
});
throw new Error('Deployment failed: ' + (deploymentStatus.error_message || 'Unknown error'));
}
attempts++;
await new Promise((resolve) => setTimeout(resolve, 1000));
} catch (error) {
console.error('Status check error:', error);
attempts++;
await new Promise((resolve) => setTimeout(resolve, 2000));
}
}
if (attempts >= maxAttempts) {
// Notify that deployment timed out
deployArtifact.runner.handleDeployAction('deploying', 'failed', {
error: 'Deployment timed out',
source: 'netlify',
});
throw new Error('Deployment timed out');
}
// Store the site ID if it's a new site
if (data.site) {
localStorage.setItem(`netlify-site-${currentChatId}`, data.site.id);
}
// Notify that deployment completed successfully
deployArtifact.runner.handleDeployAction('complete', 'complete', {
url: deploymentStatus.ssl_url || deploymentStatus.url,
source: 'netlify',
});
return true;
} catch (error) {
console.error('Deploy error:', error);
toast.error(error instanceof Error ? error.message : 'Deployment failed');
return false;
} finally {
setIsDeploying(false);
}
};
return {
isDeploying,
handleNetlifyDeploy,
isConnected: !!netlifyConn.user,
};
}

View File

@@ -0,0 +1,193 @@
import { toast } from 'react-toastify';
import { useStore } from '@nanostores/react';
import { vercelConnection } from '~/lib/stores/vercel';
import { workbenchStore } from '~/lib/stores/workbench';
import { webcontainer } from '~/lib/webcontainer';
import { path } from '~/utils/path';
import { useState } from 'react';
import type { ActionCallbackData } from '~/lib/runtime/message-parser';
import { chatId } from '~/lib/persistence/useChatHistory';
export function useVercelDeploy() {
const [isDeploying, setIsDeploying] = useState(false);
const vercelConn = useStore(vercelConnection);
const currentChatId = useStore(chatId);
const handleVercelDeploy = async () => {
if (!vercelConn.user || !vercelConn.token) {
toast.error('Please connect to Vercel first in the settings tab!');
return false;
}
if (!currentChatId) {
toast.error('No active chat found');
return false;
}
try {
setIsDeploying(true);
const artifact = workbenchStore.firstArtifact;
if (!artifact) {
throw new Error('No active project found');
}
// Create a deployment artifact for visual feedback
const deploymentId = `deploy-vercel-project`;
workbenchStore.addArtifact({
id: deploymentId,
messageId: deploymentId,
title: 'Vercel Deployment',
type: 'standalone',
});
const deployArtifact = workbenchStore.artifacts.get()[deploymentId];
// Notify that build is starting
deployArtifact.runner.handleDeployAction('building', 'running', { source: 'vercel' });
const actionId = 'build-' + Date.now();
const actionData: ActionCallbackData = {
messageId: 'vercel build',
artifactId: artifact.id,
actionId,
action: {
type: 'build' as const,
content: 'npm run build',
},
};
// Add the action first
artifact.runner.addAction(actionData);
// Then run it
await artifact.runner.runAction(actionData);
if (!artifact.runner.buildOutput) {
// Notify that build failed
deployArtifact.runner.handleDeployAction('building', 'failed', {
error: 'Build failed. Check the terminal for details.',
source: 'vercel',
});
throw new Error('Build failed');
}
// Notify that build succeeded and deployment is starting
deployArtifact.runner.handleDeployAction('deploying', 'running', { source: 'vercel' });
// Get the build files
const container = await webcontainer;
// Remove /home/project from buildPath if it exists
const buildPath = artifact.runner.buildOutput.path.replace('/home/project', '');
// Check if the build path exists
let finalBuildPath = buildPath;
// List of common output directories to check if the specified build path doesn't exist
const commonOutputDirs = [buildPath, '/dist', '/build', '/out', '/output', '/.next', '/public'];
// Verify the build path exists, or try to find an alternative
let buildPathExists = false;
for (const dir of commonOutputDirs) {
try {
await container.fs.readdir(dir);
finalBuildPath = dir;
buildPathExists = true;
console.log(`Using build directory: ${finalBuildPath}`);
break;
} catch (error) {
console.log(`Directory ${dir} doesn't exist, trying next option. ${error}`);
// Directory doesn't exist, try the next one
continue;
}
}
if (!buildPathExists) {
throw new Error('Could not find build output directory. Please check your build configuration.');
}
// Get all files recursively
async function getAllFiles(dirPath: string): Promise<Record<string, string>> {
const files: Record<string, string> = {};
const entries = await container.fs.readdir(dirPath, { withFileTypes: true });
for (const entry of entries) {
const fullPath = path.join(dirPath, entry.name);
if (entry.isFile()) {
const content = await container.fs.readFile(fullPath, 'utf-8');
// Remove build path prefix from the path
const deployPath = fullPath.replace(finalBuildPath, '');
files[deployPath] = content;
} else if (entry.isDirectory()) {
const subFiles = await getAllFiles(fullPath);
Object.assign(files, subFiles);
}
}
return files;
}
const fileContents = await getAllFiles(finalBuildPath);
// Use chatId instead of artifact.id
const existingProjectId = localStorage.getItem(`vercel-project-${currentChatId}`);
const response = await fetch('/api/vercel-deploy', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
projectId: existingProjectId || undefined,
files: fileContents,
token: vercelConn.token,
chatId: currentChatId,
}),
});
const data = (await response.json()) as any;
if (!response.ok || !data.deploy || !data.project) {
console.error('Invalid deploy response:', data);
// Notify that deployment failed
deployArtifact.runner.handleDeployAction('deploying', 'failed', {
error: data.error || 'Invalid deployment response',
source: 'vercel',
});
throw new Error(data.error || 'Invalid deployment response');
}
if (data.project) {
localStorage.setItem(`vercel-project-${currentChatId}`, data.project.id);
}
// Notify that deployment completed successfully
deployArtifact.runner.handleDeployAction('complete', 'complete', {
url: data.deploy.url,
source: 'vercel',
});
return true;
} catch (err) {
console.error('Vercel deploy error:', err);
toast.error(err instanceof Error ? err.message : 'Vercel deployment failed');
return false;
} finally {
setIsDeploying(false);
}
};
return {
isDeploying,
handleVercelDeploy,
isConnected: !!vercelConn.user,
};
}

View File

@@ -21,13 +21,18 @@ import type { Theme } from '~/types/theme';
import { classNames } from '~/utils/classNames';
import { debounce } from '~/utils/debounce';
import { createScopedLogger, renderLogger } from '~/utils/logger';
import { isFileLocked, getCurrentChatId } from '~/utils/fileLocks';
import { BinaryContent } from './BinaryContent';
import { getTheme, reconfigureTheme } from './cm-theme';
import { indentKeyBinding } from './indent';
import { getLanguage } from './languages';
import { createEnvMaskingExtension } from './EnvMasking';
const logger = createScopedLogger('CodeMirrorEditor');
// Create a module-level reference to the current document for use in tooltip functions
let currentDocRef: EditorDocument | undefined;
export interface EditorDocument {
value: string;
isBinary: boolean;
@@ -46,8 +51,10 @@ type TextEditorDocument = EditorDocument & {
};
export interface ScrollPosition {
top: number;
left: number;
top?: number;
left?: number;
line?: number;
column?: number;
}
export interface EditorUpdate {
@@ -134,6 +141,9 @@ export const CodeMirrorEditor = memo(
const [languageCompartment] = useState(new Compartment());
// Add a compartment for the env masking extension
const [envMaskingCompartment] = useState(new Compartment());
const containerRef = useRef<HTMLDivElement | null>(null);
const viewRef = useRef<EditorView>();
const themeRef = useRef<Theme>();
@@ -152,9 +162,44 @@ export const CodeMirrorEditor = memo(
onChangeRef.current = onChange;
onSaveRef.current = onSave;
docRef.current = doc;
// Update the module-level reference for use in tooltip functions
currentDocRef = doc;
themeRef.current = theme;
});
useEffect(() => {
if (!viewRef.current || !doc || doc.isBinary) {
return;
}
if (typeof doc.scroll?.line === 'number') {
const line = doc.scroll.line;
const column = doc.scroll.column ?? 0;
try {
// Check if the line number is valid for the current document
const totalLines = viewRef.current.state.doc.lines;
// Only proceed if the line number is within the document's range
if (line < totalLines) {
const linePos = viewRef.current.state.doc.line(line + 1).from + column;
viewRef.current.dispatch({
selection: { anchor: linePos },
scrollIntoView: true,
});
viewRef.current.focus();
} else {
logger.warn(`Invalid line number ${line + 1} in ${totalLines}-line document`);
}
} catch (error) {
logger.error('Error scrolling to line:', error);
}
} else if (typeof doc.scroll?.top === 'number' || typeof doc.scroll?.left === 'number') {
viewRef.current.scrollDOM.scrollTo(doc.scroll.left ?? 0, doc.scroll.top ?? 0);
}
}, [doc?.scroll?.line, doc?.scroll?.column, doc?.scroll?.top, doc?.scroll?.left]);
useEffect(() => {
const onUpdate = debounce((update: EditorUpdate) => {
onChangeRef.current?.(update);
@@ -214,6 +259,7 @@ export const CodeMirrorEditor = memo(
if (!doc) {
const state = newEditorState('', theme, settings, onScrollRef, debounceScroll, onSaveRef, [
languageCompartment.of([]),
envMaskingCompartment.of([]),
]);
view.setState(state);
@@ -236,6 +282,7 @@ export const CodeMirrorEditor = memo(
if (!state) {
state = newEditorState(doc.value, theme, settings, onScrollRef, debounceScroll, onSaveRef, [
languageCompartment.of([]),
envMaskingCompartment.of([createEnvMaskingExtension(() => docRef.current?.filePath)]),
]);
editorStates.set(doc.filePath, state);
@@ -251,6 +298,16 @@ export const CodeMirrorEditor = memo(
autoFocusOnDocumentChange,
doc as TextEditorDocument,
);
// Check if the file is locked and update the editor state accordingly
const currentChatId = getCurrentChatId();
const { locked } = isFileLocked(doc.filePath, currentChatId);
if (locked) {
view.dispatch({
effects: [editableStateEffect.of(false)],
});
}
}, [doc?.value, editable, doc?.filePath, autoFocusOnDocumentChange]);
return (
@@ -392,8 +449,13 @@ function setEditorDocument(
});
}
// Check if the file is locked
const currentChatId = getCurrentChatId();
const { locked } = isFileLocked(doc.filePath, currentChatId);
// Set editable state based on both the editable prop and the file's lock state
view.dispatch({
effects: [editableStateEffect.of(editable && !doc.isBinary)],
effects: [editableStateEffect.of(editable && !doc.isBinary && !locked)],
});
getLanguage(doc.filePath).then((languageSupport) => {
@@ -411,11 +473,36 @@ function setEditorDocument(
const newLeft = doc.scroll?.left ?? 0;
const newTop = doc.scroll?.top ?? 0;
if (typeof doc.scroll?.line === 'number') {
const line = doc.scroll.line;
const column = doc.scroll.column ?? 0;
try {
// Check if the line number is valid for the current document
const totalLines = view.state.doc.lines;
// Only proceed if the line number is within the document's range
if (line < totalLines) {
const linePos = view.state.doc.line(line + 1).from + column;
view.dispatch({
selection: { anchor: linePos },
scrollIntoView: true,
});
view.focus();
} else {
logger.warn(`Invalid line number ${line + 1} in ${totalLines}-line document`);
}
} catch (error) {
logger.error('Error scrolling to line:', error);
}
return;
}
const needsScrolling = currentLeft !== newLeft || currentTop !== newTop;
if (autoFocus && editable) {
if (needsScrolling) {
// we have to wait until the scroll position was changed before we can set the focus
view.scrollDOM.addEventListener(
'scroll',
() => {
@@ -424,7 +511,6 @@ function setEditorDocument(
{ once: true },
);
} else {
// if the scroll position is still the same we can focus immediately
view.focus();
}
}
@@ -439,6 +525,20 @@ function getReadOnlyTooltip(state: EditorState) {
return [];
}
// Get the current document from the module-level reference
const currentDoc = currentDocRef;
let tooltipMessage = 'Cannot edit file while AI response is being generated';
// If we have a current document, check if it's locked
if (currentDoc?.filePath) {
const currentChatId = getCurrentChatId();
const { locked } = isFileLocked(currentDoc.filePath, currentChatId);
if (locked) {
tooltipMessage = 'This file is locked and cannot be edited';
}
}
return state.selection.ranges
.filter((range) => {
return range.empty;
@@ -452,7 +552,7 @@ function getReadOnlyTooltip(state: EditorState) {
create: () => {
const divElement = document.createElement('div');
divElement.className = 'cm-readonly-tooltip';
divElement.textContent = 'Cannot edit file while AI response is being generated';
divElement.textContent = tooltipMessage;
return { dom: divElement };
},

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