Compare commits

...
26 Commits
Author SHA1 Message Date
Alex Gleason ff692b752c Merge remote-tracking branch 'origin/main' into global-chat 2025-12-04 16:03:57 -06:00
Alex Gleason 5ce53fdcc0 Fix CI 2025-12-04 16:03:06 -06:00
MK Fain c6a9ce2046 fix: auto-scroll in GlobalChatPane embedded mode
The scroll effects were checking `isOpen` which is false in embedded mode.
Now checks for either `isOpen` or `embedded` to enable auto-scrolling.
2025-12-03 22:30:54 -06:00
MK Fain ee784b149e hide Chat header in GlobalChatPane when mobile toggle is present
The header is redundant in mobile view since context is clear from the toggle button
2025-12-03 22:16:49 -06:00
MK Fain 093423ea0b simplify: use single icon button for Building/Chatting toggle
- Replace dual-pill toggle with single icon button
- Building mode: shows MessageCircle icon to switch to Chatting
- Chatting mode: shows Hammer icon to switch back to Building
- Keep compose box structure consistent between both modes
- Remove unused imports (Hammer from ChatInput, MessageCircle from GlobalChatPane)
2025-12-03 22:14:12 -06:00
MK Fain ed512c5d64 refactor(mobile): move Building/Chatting toggle into compose box
- Remove toggle tabs from top of mobile chat pane
- Add pill-style toggle button inside the compose area (similar to Lovable's UI)
- Toggle shows Building (hammer icon) and Chatting (message icon) modes
- Toggle appears in both ChatInput and GlobalChatPane embedded mode
- Maintains consistent styling with rounded-full bg-muted design
2025-12-03 22:06:51 -06:00
MK Fain 395a7a76bb feat(mobile): improve GlobalChatPane behavior on mobile screens
- Hide FloatingChatButton on mobile for all pages except home (/ and /giftcard)
- Add Building/Chatting toggle on mobile Chat tab in ProjectView
- Add embedded mode to GlobalChatPane for inline rendering without fixed positioning
- Add translations for "building" and "chatting" in all locales (en, pt, zh, ha, yo, ig)
2025-12-03 21:57:41 -06:00
MK Fain 075495fe7c Move Chat System Prompt to AI Settings and add Shakespeare context
- Created src/lib/globalChatSystem.ts with comprehensive default prompt
  - Includes Shakespeare platform overview and architecture
  - Describes user interface and available actions
  - Lists helpful resource blog posts for user assistance
- Moved Chat System Prompt setting from System Settings to AI Settings
  - Now under the "System Prompts" section in Advanced settings
  - Grouped with Project System Prompt for better organization
- Updated GlobalChatProvider to use the new default prompt module
- Added new translation keys for the reorganized UI:
  - systemPrompts, systemPromptsDescription
  - projectSystemPrompt, projectSystemPromptDescription
  - globalChatSystemPrompt, globalChatSystemPromptDescription
- Removed redundant code from SystemSettings.tsx

Resources included in the new default prompt:
- AI model selection guide
- Configuring AI providers
- Using local AI models
- Editing code in Shakespeare
- Deploying and sharing projects
- Importing existing projects
- Version control with Git
- Debugging tips
- Better prompting techniques
2025-12-03 21:42:58 -06:00
MK Fain 5f76931941 Hide GlobalChatPane on settings pages
- Added useLocation hook to GlobalChatPane component
- Added check to hide GlobalChatPane when on settings pages (pathname starts with '/settings')
- Matches existing behavior of FloatingChatButton which already hides on settings pages
- Ensures consistent UX where both the chat button and pane are hidden in settings
2025-12-03 21:22:47 -06:00
MK Fain 6527f42e2f Fix infinite reload loop in GlobalChatProvider
Removed `isLoading` and `messages` from sendMessage's dependency array.
These were causing the callback to be recreated on every state change,
triggering infinite re-renders.

Instead, capture current messages inside the setMessages updater function
to avoid needing messages in the deps array.
2025-12-03 21:18:49 -06:00
MK Fain a42ea724fa Fix GlobalChatPane 3-second delay using loadingReleasedRef
The issue was that setIsLoading(false) was being called twice:
1. Inside the for-await loop when finish_reason is received
2. In the finally block after the loop completes (3 seconds later)

The finally block's setIsLoading(false) was overriding the early release,
causing React to wait until the entire async iterator finished draining
before updating the UI state.

Solution: Use a ref to track if loading was already released, and skip
the finally block's setIsLoading call if we already released it early.
2025-12-03 21:17:07 -06:00
MK Fain ad217937a3 Fix GlobalChatPane input delay after AI response completes
Release the loading state immediately when finish_reason is received,
but don't break from the for-await loop. Breaking triggers async iterator
cleanup which can cause a multi-second delay before the input becomes
available again. Instead, let the stream drain naturally while the UI
is already unlocked for user input.
2025-12-03 21:14:45 -06:00
MK Fain 6457fbda76 Auto-focus textarea when GlobalChatPane opens
When the global chat pane is opened, the textarea is now automatically
focused so users can immediately start typing without needing to click
on the input field first.
2025-12-03 21:08:00 -06:00
MK Fain b78a912af1 Fix GlobalChatPane input delay after AI finishes responding
Check for finish_reason in stream chunks to detect when the AI has
finished generating content, and release isLoading immediately rather
than waiting for the stream connection to fully close.
2025-12-03 20:56:46 -06:00
MK Fain b1bbf58867 Change GlobalChatPane minimize button back to X icon 2025-12-03 20:53:37 -06:00
MK Fain ecf6b72b21 Fix close button z-index on FloatingChatButton
Moved close button to render after main button so it appears on top
and is clickable in the overlapping area
2025-12-03 20:49:37 -06:00
MK Fain 1b287b90aa Add hover close button to FloatingChatButton and hide on settings pages
- Added "x" button that appears when hovering over the chat button
- Clicking "x" temporarily hides the button until page navigation or refresh
- Button no longer appears on /settings/* pages
- Reset hidden state when navigating to a different page
2025-12-03 20:47:13 -06:00
MK Fain e9a6177c5b Replace minimize icon with minus icon in GlobalChatPane
Changed from Minimize2 to Minus icon for the minimize button
2025-12-03 20:43:04 -06:00
MK Fain 361b6dae3c Keep textarea focused in GlobalChatPane after AI responds
- Focus textarea immediately after sending message (not after AI response)
- Add useEffect to refocus textarea when isLoading becomes false
- User can now type their next message right away without clicking
2025-12-03 20:40:05 -06:00
MK Fain 37071cde85 Fix GlobalChatPane (popup chat) auto-scroll behavior
- Scroll to bottom when chat opens using requestAnimationFrame
- Track userScrolledUp ref to detect when user manually scrolls up
- Auto-scroll follows streaming content by watching lastMessageContent
- Reset scroll tracking when clicking scroll-to-bottom button
- Reset scroll tracking when chat opens
- Only auto-scroll if user hasn't manually scrolled up to read history

Also reverted unintended changes to main ChatPane.tsx
2025-12-03 20:36:36 -06:00
MK Fain fc6ddbf8d6 Fix chat pane auto-scroll behavior
- Add userScrolledUp ref to track when user manually scrolls away from bottom
- Auto-scroll to bottom only when user hasn't manually scrolled up
- Reset scroll tracking when clicking scroll-to-bottom button
- Reset scroll tracking when switching between projects
- Ensures new messages always scroll into view unless user is reading history
2025-12-03 20:30:22 -06:00
MK Fain e23c843ef9 Fix GlobalChatProvider parseProviderModel usage
The parseProviderModel function returns { model, provider } but the code
was trying to destructure { providerId, modelId }. Fixed to correctly
use the actual return values and pass the required providers array
parameter to the function.
2025-12-03 20:10:18 -06:00
MK Fain 0c4de2e2c0 Fix global chat issues and move chat system prompt setting
1. Fixed user message not appearing in global chat
2. Made project chat and global chat remember separate models
   - Added separate localStorage storage for global chat model
   - Project chat continues to use recentlyUsedModels from AISettings
   - Global chat now stores its model independently
3. Moved Chat System Prompt setting from Preferences to System Settings
4. Removed chat pop-out functionality
   - Removed isPoppedOut state from GlobalChatContext
   - Removed handlePopOut function from GlobalChatPane
   - Removed pop-out button from desktop chat header
   - Removed isPoppedOut check from FloatingChatButton
2025-12-03 20:03:53 -06:00
MK Fain 477d055797 Improve unread message indicator for floating chat
- Add hasUnread state to track whether user has seen new messages
- Mark messages as read when chat is opened
- Mark as unread when assistant responds while chat is closed
- Change indicator from message count to simple dot for cleaner UX
2025-12-03 19:50:10 -06:00
MK Fain 15c8040e35 Fix: Move FloatingChatButton and GlobalChatPane inside Router
The ModelSelector component uses useNavigate which requires Router context.
Move the floating chat components from App.tsx into AppRouter.tsx where
they have access to the BrowserRouter/HashRouter context.
2025-12-03 19:47:29 -06:00
MK Fain 68702abc41 Add floating global chat feature
- Add GlobalChatContext, GlobalChatProvider for managing chat state
- Create FloatingChatButton component with unread message indicator
- Create GlobalChatPane with desktop (floating panel) and mobile (full screen) views
- Features include:
  - Streaming AI responses with markdown rendering
  - Auto context trimming when messages exceed ~50k tokens
  - Easy text copy from messages (hover to reveal copy button)
  - Pop-out to separate window
  - Minimize/dismiss functionality
  - Clear chat history
  - Mobile-optimized full-screen drawer
- Add settings in Preferences page:
  - Enable/disable floating chat button
  - Customize chat system prompt
- Add translations for all supported languages (en, pt, zh, ha, yo, ig)
- Integrate with existing AI provider configuration
2025-12-03 19:44:12 -06:00
21 changed files with 1519 additions and 51 deletions

No files matched your search

+147
View File
@@ -0,0 +1,147 @@
<!DOCTYPE html><html lang="en" class="light"><head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="content-security-policy" content="default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; frame-src 'self' https:; font-src 'self'; base-uri 'self'; manifest-src 'self'; connect-src 'self' blob: https: wss:; img-src 'self' data: blob: https:; media-src 'self' https:">
<title>Shakespeare Resources - FAQ &amp; Guides | Soapbox</title>
<meta name="description" content="Complete resource hub for Shakespeare AI website builder. Find answers to frequently asked questions and explore tutorials on how to make the most of Shakespeare.">
<!-- Open Graph / Facebook -->
<meta property="og:type" content="website">
<meta property="og:title" content="Shakespeare Resources - FAQ &amp; Guides | Soapbox">
<meta property="og:description" content="Complete resource hub for Shakespeare AI website builder. Find answers to frequently asked questions and explore tutorials on how to make the most of Shakespeare.">
<meta property="og:image" content="https://soapbox.pub/assets/images/shakespeare-screenshots/resrouce-center.png">
<meta property="og:url" content="https://soapbox.pub/shakespeare-resources">
<meta property="og:site_name" content="Soapbox">
<!-- Twitter -->
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:title" content="Shakespeare Resources - FAQ &amp; Guides | Soapbox">
<meta name="twitter:description" content="Complete resource hub for Shakespeare AI website builder. Find answers to frequently asked questions and explore tutorials on how to make the most of Shakespeare.">
<meta name="twitter:image" content="https://soapbox.pub/assets/images/shakespeare-screenshots/resrouce-center.png">
<!-- Additional meta tags -->
<meta name="image" content="https://soapbox.pub/assets/images/shakespeare-screenshots/resrouce-center.png">
<meta name="author" content="Soapbox Technology">
<meta name="keywords" content="shakespeare resources, shakespeare faq, shakespeare blog, ai website builder help, shakespeare tutorials">
<meta name="robots" content="index, follow">
<meta name="language" content="English">
<meta name="revisit-after" content="7 days">
<!-- Additional Open Graph tags -->
<meta property="og:locale" content="en_US">
<meta property="og:image:width" content="1200">
<meta property="og:image:height" content="630">
<meta property="og:image:type" content="image/jpeg">
<!-- Twitter specific -->
<meta name="twitter:site" content="@soapbox_pub">
<meta name="twitter:creator" content="@soapbox_pub">
<!-- Canonical URL -->
<link rel="canonical" href="https://soapbox.pub/shakespeare-resources">
<!-- Favicon -->
<link rel="apple-touch-icon" sizes="180x180" href="/favicon/apple-touch-icon.png">
<link rel="icon" type="image/png" sizes="32x32" href="/favicon/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="16x16" href="/favicon/favicon-16x16.png">
<link rel="manifest" href="/manifest.json">
<link rel="mask-icon" href="/favicon/safari-pinned-tab.svg" color="#0482d8">
<link rel="shortcut icon" href="/favicon/favicon.ico">
<meta name="msapplication-TileColor" content="#0482d8">
<meta name="msapplication-config" content="/favicon/browserconfig.xml">
<meta name="theme-color" content="#0482d8">
<script type="module" crossorigin="" src="/assets/index-SKr11h0N.js"></script>
<link rel="stylesheet" crossorigin="" href="/assets/index-Ck_Ce8d7.css">
<script id="structured-data" type="application/ld+json">{
"@context": "https://schema.org",
"@type": "WebPage",
"name": "Shakespeare Resources - FAQ & Guides | Soapbox",
"description": "Complete resource hub for Shakespeare AI website builder. Find answers to frequently asked questions and explore tutorials on how to make the most of Shakespeare.",
"url": "https://soapbox.pub/shakespeare-resources",
"image": "https://soapbox.pub/assets/images/shakespeare-screenshots/resrouce-center.png",
"isPartOf": {
"@type": "WebSite",
"name": "Soapbox",
"url": "https://soapbox.pub"
}
}</script></head>
<body>
<div id="root"><div role="region" aria-label="Notifications (F8)" tabindex="-1" style="pointer-events: none;"><ol tabindex="-1" class="fixed top-0 z-[100] flex max-h-screen w-full flex-col-reverse p-4 sm:bottom-0 sm:right-0 sm:top-auto sm:flex-col md:max-w-[420px]"></ol></div><div class="min-h-screen bg-gradient-to-br from-blue-50 via-white to-purple-50"><nav class="border-b bg-white/80 backdrop-blur-sm sticky top-0 z-50"><div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8"><div class="flex justify-between items-center h-16"><a class="flex items-center space-x-2" href="/"><img src="/logo.svg" alt="Soapbox Logo" width="32" height="32"><span class="font-display font-bold text-xl text-gray-900">Soapbox</span></a><div class="hidden md:flex items-center space-x-8"><a class="transition-colors text-gray-600 hover:text-azure" href="/">Home</a><a class="transition-colors text-gray-600 hover:text-azure" href="/tools">Tools</a><a class="transition-colors text-gray-600 hover:text-azure" href="/showcase">Showcase</a><a class="transition-colors text-gray-600 hover:text-azure" href="/about">About</a><a class="transition-colors text-gray-600 hover:text-azure" href="/blog">Blog</a><a class="inline-flex items-center justify-center gap-2 whitespace-nowrap text-sm font-medium ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 [&amp;_svg]:pointer-events-none [&amp;_svg]:size-4 [&amp;_svg]:shrink-0 h-9 rounded-md px-3 bg-blue-100 hover:bg-blue-200 text-blue-700 border border-blue-200 hover:border-blue-300 transition-all duration-200 flex items-center space-x-2" href="/tools/shakespeare"><span class="text-sm">🎭</span><span>Shakespeare</span></a></div><div class="md:hidden"><button class="inline-flex items-center justify-center gap-2 whitespace-nowrap text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 [&amp;_svg]:pointer-events-none [&amp;_svg]:size-4 [&amp;_svg]:shrink-0 hover:bg-accent hover:text-accent-foreground h-9 rounded-md p-2"><svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-menu h-6 w-6"><line x1="4" x2="20" y1="12" y2="12"></line><line x1="4" x2="20" y1="6" y2="6"></line><line x1="4" x2="20" y1="18" y2="18"></line></svg></button></div></div></div></nav><section class="pt-20 pb-16 px-4 sm:px-6 lg:px-8"><div class="max-w-7xl mx-auto text-center"><div class="space-y-6"><div class="inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 hover:bg-secondary/80 bg-purple-100 text-purple-700 border-purple-200">📚 Resource Hub</div><h1 class="text-5xl md:text-6xl font-display font-bold text-gray-900"><span class="text-purple-600">🎭 Shakespeare</span> Resources</h1><p class="text-xl text-gray-600 max-w-3xl mx-auto">Find answers to common questions and explore our latest guides.</p></div></div></section><section class="py-16 px-4 sm:px-6 lg:px-8 bg-gradient-to-br from-purple-50 to-blue-50"><div class="max-w-6xl mx-auto"><div class="text-center mb-12"><div class="flex items-center justify-center mb-4"><svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-play h-8 w-8 text-purple-600 mr-3"><polygon points="6 3 20 12 6 21 6 3"></polygon></svg><h2 class="text-4xl font-display font-bold text-gray-900">Video Tutorial Playlist</h2></div><p class="text-lg text-gray-600">Watch our complete video guide series to master Shakespeare</p></div><div class="mb-8"><div class="relative w-full aspect-video mb-8 max-w-5xl mx-auto"><iframe src="https://www.youtube.com/embed/videoseries?si=NoONPhl3VGl5cEOX&amp;list=PLPVwsk16NNURX_8MJxm5luRZpGVoZ7Qba" title="Shakespeare Tutorial Playlist - Complete Guide Series" class="absolute inset-0 w-full h-full rounded-lg" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen=""></iframe></div></div><div class="text-center"><p class="text-gray-600 mb-4">This playlist includes step-by-step tutorials covering all major Shakespeare features</p><div class="flex flex-wrap justify-center gap-2"><div class="inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 border-purple-200 text-purple-700">🔄 Import Projects</div><div class="inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 foLine truncated
#mc_embed_signup {
background: transparent !important;
clear: left;
font: 14px Helvetica, Arial, sans-serif;
width: 100% !important;
}
#mc_embed_signup h2 {
display: none;
}
#mc_embed_signup .mc-field-group {
margin-bottom: 1rem;
}
#mc_embed_signup label {
font-weight: 600;
margin-bottom: 0.5rem;
display: block;
color: inherit;
}
#mc_embed_signup input[type="text"],
#mc_embed_signup input[type="email"] {
width: 100%;
padding: 0.75rem;
border: 1px solid #d1d5db;
border-radius: 0.5rem;
font-size: 14px;
background: white;
}
#mc_embed_signup input.error {
border-color: #ef4444 !important;
}
#mc_embed_signup .button {
background: linear-gradient(to right, #8B5CF6, #3B82F6) !important;
border: none !important;
border-radius: 0.5rem !important;
color: white !important;
padding: 0.75rem 2rem !important;
font-weight: 600 !important;
cursor: pointer !important;
width: 100% !important;
margin-top: 1rem !important;
}
#mc_embed_signup .button:hover {
background: linear-gradient(to right, #7C3AED, #2563EB) !important;
}
#mc_embed_signup .indicates-required {
font-size: 12px;
color: #6b7280;
margin-bottom: 1rem;
}
#mc_embed_signup .asterisk {
color: #ef4444;
}
.dark #mc_embed_signup input[type="text"],
.dark #mc_embed_signup input[type="email"] {
background: #374151;
border-color: #4b5563;
color: white;
}
.dark #mc_embed_signup label {
color: #f9fafb;
}
.dark #mc_embed_signup input.error {
border-color: #ef4444 !important;
}
</style><div id="mc_embed_signup"><form action="https://pub.us7.list-manage.com/subscribe/post?u=f1f718a93795f42a604d558d8&amp;id=f7271442a0&amp;f_id=00ffa3e4f0" method="post" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate" target="_blank"><div id="mc_embed_signup_scroll"><div class="indicates-required"><span class="asterisk">*</span> indicates required</div><div class="mc-field-group"><label for="mce-NPUB">Nostr Public Key (npub) <span style="color: rgb(107, 114, 128); font-weight: normal;">(optional)</span></label><input type="text" name="NPUB" class="text " id="mce-NPUB" placeholder="npub1..." value=""></div><div class="mc-field-group"><label for="mce-EMAIL">Email Address <span class="asterisk">*</span></label><input type="email" name="EMAIL" class="required email" id="mce-EMAIL" required="" placeholder="[email protected]"></div><div hidden=""><input type="hidden" name="tags" value="8982394"></div><div id="mce-responses" class="clear"><div class="response" id="mce-error-response" style="display: none;"></div><div class="response" id="mce-success-response" style="display: none;"></div></div><div aria-hidden="true" style="position: absolute; left: -5000px;"><input type="text" name="b_f1f718a93795f42a604d558d8_f7271442a0" tabindex="-1"></div><div class="clear"><input type="submit" name="subscribe" id="mc-embedded-subscribe" class="button" value="Sign Up"></div></div></form></div><script type="text/javascript" src="//s3.amazonaws.com/downloads.mailchimp.com/js/mc-validate.js"></script><script type="text/javascript">(function($) {
window.fnames = new Array();
window.ftypes = new Array();
fnames[6]='NPUB';ftypes[6]='text';
fnames[0]='EMAIL';ftypes[0]='email';
fnames[1]='FNAME';ftypes[1]='text';
fnames[2]='LNAME';ftypes[2]='text';
fnames[3]='ADDRESS';ftypes[3]='address';
fnames[4]='PHONE';ftypes[4]='phone';
fnames[5]='BIRTHDAY';ftypes[5]='birthday';
}(jQuery));
var $mcj = jQuery.noConflict(true);</script></div></div></div></div></section><footer class="bg-gray-900 text-white py-16 px-4 sm:px-6 lg:px-8"><div class="max-w-7xl mx-auto"><div class="grid md:grid-cols-6 gap-8"><div class="md:col-span-2 space-y-6"><div class="space-y-4"><div class="flex items-center space-x-2"><img src="/logo.svg" alt="Soapbox Logo" width="32" height="32"><span class="font-display font-bold text-xl">Soapbox</span></div><p class="text-gray-400 max-w-md">Software for the next generation of social media.</p></div><div class="space-y-3"><h4 class="font-semibold text-sm uppercase tracking-wide">Stay Updated</h4><form class="space-y-2"><div class="flex gap-2"><div class="relative flex-1"><svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-mail absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-500 h-4 w-4"><rect width="20" height="16" x="2" y="4" rx="2"></rect><path d="m22 7-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 7"></path></svg><input type="email" class="flex h-10 w-full rounded-md border px-3 py-2 text-base ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 md:text-sm pl-10 text-gray-900 placeholder:text-gray-500 bg-white border-gray-300" placeholder="Your email address" required="" value=""></div><button class="inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 [&amp;_svg]:pointer-events-none [&amp;_svg]:size-4 [&amp;_svg]:shrink-0 bg-primary text-primary-foreground hover:bg-primary/90 h-10 py-2 px-6" type="submit">Sign up</button></div></form><div class="pt-2"><button class="inline-flex items-center gap-2 whitespace-nowrap rounded-md text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 [&amp;_svg]:pointer-events-none [&amp;_svg]:size-4 [&amp;_svg]:shrink-0 border border-input bg-transparent hover:bg-accent hover:text-accent-foreground h-10 px-4 py-2 justify-between w-full" role="combobox" aria-expanded="false" type="button" aria-haspopup="dialog" aria-controls="radix-:rk:" data-state="closed"><div class="flex items-center gap-2"><svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-wifi h-4 w-4"><path d="M12 20h.01"></path><path d="M2 8.82a15 15 0 0 1 20 0"></path><path d="M5 12.859a10 10 0 0 1 14 0"></path><path d="M8.5 16.429a5 5 0 0 1 7 0"></path></svg><span class="truncate">Ditto</span></div><svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-chevrons-up-down ml-2 h-4 w-4 shrink-0 opacity-50"><path d="m7 15 5 5 5-5"></path><path d="m7 9 5-5 5 5"></path></svg></button></div></div></div><div><h4 class="font-semibold mb-4">Tools</h4><ul class="space-y-2 text-gray-400"><li><a href="https://ditto.pub" class="hover:text-white transition-colors" target="_blank" rel="noopener noreferrer">Ditto</a></li><li><a href="https://mkstack.xyz" class="hover:text-white transition-colors" target="_blank" rel="noopener noreferrer">MKStack</a></li><li><a href="https://getstacks.dev" class="hover:text-white transition-colors" target="_blank" rel="noopener noreferrer">Stacks</a></li><li><a href="https://nostrbook.dev" class="hover:text-white transition-colors" target="_blank" rel="noopener noreferrer">Nostrbook</a></li><li><a href="https://nostrhub.io" class="hover:text-white transition-colors" target="_blank" rel="noopener noreferrer">NostrHub</a></li><li><a href="https://nostrify.dev" class="hover:text-white transition-colors" target="_blank" rel="noopener noreferrer">Nostrify</a></li></ul></div><div><h4 class="font-semibold mb-4">Communities</h4><ul class="space-y-2 text-gray-400"><li><a href="https://ditto.pub" class="hover:text-white transition-colors" target="_blank" rel="noopener noreferrer">Ditto.pub</a></li><li><a href="https://treasures.to" class="hover:text-white transition-colors" target="_blank" rel="noopener noreferrer">Treasures</a></li><li><a href="https://blobbi.pet" class="hover:text-white transition-colors" target="_blank" rel="noopener noreferrer">Blobbi</a></li><li><a href="https://bookstr.xyz" class="hover:text-white transition-colors" target="_bLine truncated
</body></html>
+12 -9
View File
@@ -28,6 +28,7 @@ import { DynamicFavicon } from '@/components/DynamicFavicon';
import { OfflineIndicator } from '@/components/OfflineIndicator';
import { PWAUpdatePrompt } from '@/components/PWAUpdatePrompt';
import { ErrorBoundary } from '@/components/ErrorBoundary';
import { GlobalChatProvider } from '@/components/GlobalChatProvider';
import AppRouter from './AppRouter';
@@ -177,15 +178,17 @@ export function App() {
<GitSettingsProvider>
<DeploySettingsProvider>
<SessionManagerProvider>
<TooltipProvider>
<Toaster />
<DynamicFavicon />
<OfflineIndicator />
<PWAUpdatePrompt />
<Suspense>
<AppRouter />
</Suspense>
</TooltipProvider>
<GlobalChatProvider>
<TooltipProvider>
<Toaster />
<DynamicFavicon />
<OfflineIndicator />
<PWAUpdatePrompt />
<Suspense>
<AppRouter />
</Suspense>
</TooltipProvider>
</GlobalChatProvider>
</SessionManagerProvider>
</DeploySettingsProvider>
</GitSettingsProvider>
+5
View File
@@ -2,6 +2,8 @@ import { BrowserRouter, HashRouter, Route, Routes } from "react-router-dom";
import { ScrollToTop } from "./components/ScrollToTop";
import { SessionMonitor } from "./components/SessionMonitor";
import { URLFragmentHandler } from "./components/URLFragmentHandler";
import { FloatingChatButton } from "./components/FloatingChatButton";
import { GlobalChatPane } from "./components/GlobalChatPane";
import Index from "./pages/Index";
import Clone from "./pages/Clone";
@@ -56,6 +58,9 @@ export function AppRouter() {
{/* ADD ALL CUSTOM ROUTES ABOVE THE CATCH-ALL "*" ROUTE */}
<Route path="*" element={<NotFound />} />
</Routes>
{/* Global floating chat - available on all pages */}
<FloatingChatButton />
<GlobalChatPane />
</Router>
);
}
+91
View File
@@ -0,0 +1,91 @@
import { useState, useEffect } from 'react';
import { useLocation } from 'react-router-dom';
import { MessageCircle, X } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { useGlobalChat } from '@/hooks/useGlobalChat';
import { useAppContext } from '@/hooks/useAppContext';
import { useIsMobile } from '@/hooks/useIsMobile';
import { cn } from '@/lib/utils';
export function FloatingChatButton() {
const { isOpen, setIsOpen, hasUnread } = useGlobalChat();
const { config } = useAppContext();
const location = useLocation();
const isMobile = useIsMobile();
const [isHovered, setIsHovered] = useState(false);
const [isHiddenTemporarily, setIsHiddenTemporarily] = useState(false);
// Reset hidden state when navigating to a different page
useEffect(() => {
setIsHiddenTemporarily(false);
}, [location.pathname]);
// Don't render if disabled in settings
if (config.globalChatEnabled === false) {
return null;
}
// Don't render on settings pages
if (location.pathname.startsWith('/settings')) {
return null;
}
// On mobile, only show on home screen (/ or /giftcard)
const isHomePage = location.pathname === '/' || location.pathname === '/giftcard';
if (isMobile && !isHomePage) {
return null;
}
// Don't render if temporarily hidden
if (isHiddenTemporarily) {
return null;
}
const handleClose = (e: React.MouseEvent) => {
e.stopPropagation();
setIsHiddenTemporarily(true);
};
return (
<div
className="fixed bottom-6 right-6 z-40"
onMouseEnter={() => setIsHovered(true)}
onMouseLeave={() => setIsHovered(false)}
>
{/* Main chat button */}
<Button
onClick={() => setIsOpen(!isOpen)}
size="lg"
className={cn(
'h-14 w-14 rounded-full shadow-lg',
'bg-primary hover:bg-primary/90 text-primary-foreground',
'transition-all duration-200 hover:scale-105',
'flex items-center justify-center p-0',
isOpen && 'ring-2 ring-ring ring-offset-2'
)}
aria-label={isOpen ? 'Close chat' : 'Open chat'}
>
<MessageCircle className="h-6 w-6" />
{/* Unread indicator - small dot when there are unread messages */}
{!isOpen && hasUnread && (
<span className="absolute top-0 right-0 h-3 w-3 rounded-full bg-destructive ring-2 ring-background" />
)}
</Button>
{/* Close button - appears on hover, rendered last to be on top */}
<Button
onClick={handleClose}
size="icon"
variant="secondary"
className={cn(
'absolute -top-2 -right-2 h-6 w-6 rounded-full shadow-md border',
'transition-all duration-200',
isHovered ? 'opacity-100 scale-100' : 'opacity-0 scale-75 pointer-events-none'
)}
aria-label="Hide chat button"
>
<X className="h-3 w-3" />
</Button>
</div>
);
}
+614
View File
@@ -0,0 +1,614 @@
import { useState, useRef, useEffect, useCallback } from 'react';
import { useTranslation } from 'react-i18next';
import { useLocation } from 'react-router-dom';
import { X, Trash2, Copy, Check, ChevronDown, ArrowUp, Square, Loader2, Hammer } from 'lucide-react';
import { Streamdown } from 'streamdown';
import { Button } from '@/components/ui/button';
import { Textarea } from '@/components/ui/textarea';
import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';
import { ModelSelector } from '@/components/ModelSelector';
import { useGlobalChat } from '@/hooks/useGlobalChat';
import { useAppContext } from '@/hooks/useAppContext';
import { useAISettings } from '@/hooks/useAISettings';
import { useIsMobile } from '@/hooks/useIsMobile';
import { useTheme } from '@/hooks/useTheme';
import { cn } from '@/lib/utils';
import type { GlobalChatMessage } from '@/contexts/GlobalChatContext';
// Message component with copy functionality
function ChatMessage({ message }: { message: GlobalChatMessage }) {
const [copied, setCopied] = useState(false);
const { displayTheme } = useTheme();
const isUser = message.role === 'user';
const handleCopy = useCallback(async () => {
try {
await navigator.clipboard.writeText(message.content);
setCopied(true);
setTimeout(() => setCopied(false), 2000);
} catch (error) {
console.error('Failed to copy:', error);
}
}, [message.content]);
return (
<div
className={cn(
'group relative flex',
isUser ? 'justify-end' : 'justify-start'
)}
>
<div
className={cn(
'relative max-w-[85%] rounded-2xl px-4 py-2.5',
isUser
? 'bg-primary text-primary-foreground rounded-br-md'
: 'bg-muted rounded-bl-md'
)}
>
{isUser ? (
<p className="text-sm whitespace-pre-wrap break-words">{message.content}</p>
) : (
<div className="text-sm break-words">
<Streamdown
className="size-full [&>*:first-child]:mt-0 [&>*:last-child]:mb-0 prose prose-sm dark:prose-invert max-w-none"
shikiTheme={displayTheme === 'dark' ? 'github-dark' : 'github-light'}
>
{message.content || '...'}
</Streamdown>
</div>
)}
{/* Copy button - shows on hover */}
<button
onClick={handleCopy}
className={cn(
'absolute -bottom-1 opacity-0 group-hover:opacity-100 transition-opacity',
'p-1 rounded bg-background/80 hover:bg-background shadow-sm border',
isUser ? 'right-0 translate-y-full' : 'left-0 translate-y-full'
)}
aria-label="Copy message"
>
{copied ? (
<Check className="h-3 w-3 text-green-500" />
) : (
<Copy className="h-3 w-3 text-muted-foreground" />
)}
</button>
</div>
</div>
);
}
interface GlobalChatPaneProps {
/** When true, renders inline without fixed positioning (for embedding in ProjectView) */
embedded?: boolean;
/** Mobile chat mode toggle - only used in embedded mode */
mobileChatMode?: 'building' | 'chatting';
onMobileChatModeChange?: (mode: 'building' | 'chatting') => void;
}
export function GlobalChatPane({ embedded = false, mobileChatMode, onMobileChatModeChange }: GlobalChatPaneProps) {
const { t } = useTranslation();
const {
messages,
isOpen,
isLoading,
sendMessage,
stopGeneration,
clearMessages,
setIsOpen,
providerModel,
setProviderModel,
} = useGlobalChat();
const { config } = useAppContext();
const { settings } = useAISettings();
const isMobile = useIsMobile();
const location = useLocation();
const [input, setInput] = useState('');
const [showScrollToBottom, setShowScrollToBottom] = useState(false);
const scrollAreaRef = useRef<HTMLDivElement>(null);
const textareaRef = useRef<HTMLTextAreaElement>(null);
// Track if user has manually scrolled up
const userScrolledUp = useRef(false);
// Track the last message content to detect streaming updates
const lastMessageContent = messages[messages.length - 1]?.content || '';
// Initialize provider model from settings if not set
useEffect(() => {
if (!providerModel && settings.recentlyUsedModels?.length) {
setProviderModel(settings.recentlyUsedModels[0]);
}
}, [providerModel, settings.recentlyUsedModels, setProviderModel]);
// Scroll to bottom and focus textarea when chat opens (or when embedded mode becomes active)
useEffect(() => {
const shouldScroll = isOpen || embedded;
if (shouldScroll && scrollAreaRef.current) {
// Small delay to ensure content is rendered
requestAnimationFrame(() => {
if (scrollAreaRef.current) {
scrollAreaRef.current.scrollTop = scrollAreaRef.current.scrollHeight;
}
// Focus the textarea so user can start typing immediately
textareaRef.current?.focus();
});
// Reset scroll tracking when opening
userScrolledUp.current = false;
}
}, [isOpen, embedded]);
// Auto-scroll to bottom when messages change or streaming content updates
useEffect(() => {
const isActive = isOpen || embedded;
if (!scrollAreaRef.current || !isActive) return;
// Only auto-scroll if user hasn't manually scrolled up
if (!userScrolledUp.current) {
scrollAreaRef.current.scrollTop = scrollAreaRef.current.scrollHeight;
}
}, [messages, lastMessageContent, isLoading, isOpen, embedded]);
// Handle scroll to detect user scrolling and show/hide scroll-to-bottom button
const handleScroll = useCallback(() => {
if (scrollAreaRef.current) {
const container = scrollAreaRef.current;
const threshold = 100;
const isNearBottom = container.scrollTop + container.clientHeight >= container.scrollHeight - threshold;
// Track if user scrolled away from bottom
userScrolledUp.current = !isNearBottom;
setShowScrollToBottom(!isNearBottom && messages.length > 0);
}
}, [messages.length]);
const scrollToBottom = useCallback(() => {
if (scrollAreaRef.current) {
scrollAreaRef.current.scrollTop = scrollAreaRef.current.scrollHeight;
// Reset the flag so auto-scroll resumes
userScrolledUp.current = false;
}
}, []);
const handleSend = useCallback(async () => {
if (!input.trim() || isLoading || !providerModel) return;
const messageContent = input.trim();
setInput('');
// Focus immediately so user can keep typing
textareaRef.current?.focus();
await sendMessage(messageContent, providerModel);
}, [input, isLoading, providerModel, sendMessage]);
// Refocus textarea when AI finishes responding
useEffect(() => {
if (!isLoading && isOpen && messages.length > 0) {
textareaRef.current?.focus();
}
}, [isLoading, isOpen, messages.length]);
const handleKeyDown = useCallback((e: React.KeyboardEvent<HTMLTextAreaElement>) => {
if (e.key === 'Enter' && !e.shiftKey && !isMobile) {
e.preventDefault();
handleSend();
}
}, [handleSend, isMobile]);
// For non-embedded mode: Don't render if disabled or not open
if (!embedded && (config.globalChatEnabled === false || !isOpen)) {
return null;
}
// For non-embedded mode: Don't render on settings pages
if (!embedded && location.pathname.startsWith('/settings')) {
return null;
}
const hasProviders = settings.providers.length > 0;
// Embedded mode: Render inline without fixed positioning
if (embedded) {
// Hide header when there's a mode toggle (mobile view with switching)
const showHeader = !mobileChatMode;
return (
<div className="h-full flex flex-col bg-background">
{/* Header - hidden when mobile toggle is present */}
{showHeader && (
<div className="flex items-center justify-between px-4 py-3 border-b bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/60">
<h2 className="font-semibold text-lg">{t('globalChat')}</h2>
<div className="flex items-center gap-1">
{messages.length > 0 && (
<Tooltip>
<TooltipTrigger asChild>
<Button
variant="ghost"
size="icon"
className="h-8 w-8"
onClick={clearMessages}
>
<Trash2 className="h-4 w-4" />
</Button>
</TooltipTrigger>
<TooltipContent>{t('clearChat')}</TooltipContent>
</Tooltip>
)}
</div>
</div>
)}
{/* Messages */}
<div
ref={scrollAreaRef}
className="flex-1 overflow-y-auto p-4 space-y-4"
onScroll={handleScroll}
>
{messages.length === 0 ? (
<div className="flex-1 flex items-center justify-center text-center text-muted-foreground px-8 py-12">
<div>
<p className="text-lg font-medium mb-2">{t('globalChatWelcome')}</p>
<p className="text-sm">{t('globalChatDescription')}</p>
</div>
</div>
) : (
messages.map((message) => (
<ChatMessage key={message.id} message={message} />
))
)}
{isLoading && messages[messages.length - 1]?.role !== 'assistant' && (
<div className="flex justify-start">
<div className="bg-muted rounded-2xl rounded-bl-md px-4 py-3">
<Loader2 className="h-4 w-4 animate-spin text-muted-foreground" />
</div>
</div>
)}
</div>
{/* Scroll to bottom button */}
{showScrollToBottom && (
<Button
onClick={scrollToBottom}
size="sm"
variant="secondary"
className="absolute bottom-32 left-1/2 -translate-x-1/2 rounded-full shadow-lg"
>
<ChevronDown className="h-4 w-4" />
</Button>
)}
{/* Input */}
<div className="border-t p-4">
<div className="flex flex-col rounded-2xl border border-input bg-background shadow-sm focus-within:ring-2 focus-within:ring-ring focus-within:ring-offset-2">
<Textarea
ref={textareaRef}
value={input}
onChange={(e) => {
setInput(e.target.value);
// Auto-resize
const target = e.target as HTMLTextAreaElement;
target.style.height = 'auto';
target.style.height = Math.min(target.scrollHeight, 128) + 'px';
}}
onKeyDown={handleKeyDown}
placeholder={hasProviders ? t('typeMessage') : t('configureAIFirst')}
disabled={!hasProviders || isLoading}
className="flex-1 resize-none border-0 bg-transparent px-4 py-3 text-sm focus-visible:ring-0 focus-visible:ring-offset-0 placeholder:text-muted-foreground"
rows={1}
style={{
height: 'auto',
minHeight: '96px'
}}
onInput={(e) => {
const target = e.target as HTMLTextAreaElement;
target.style.height = 'auto';
target.style.height = Math.min(target.scrollHeight, 128) + 'px';
}}
/>
{/* Bottom Controls Row */}
<div className="flex items-center gap-4 px-2 py-2">
{/* Mobile Chat Mode Toggle - single button to switch back to building mode */}
{mobileChatMode && onMobileChatModeChange && (
<Tooltip>
<TooltipTrigger asChild>
<Button
variant="ghost"
size="icon"
className="h-8 w-8 shrink-0"
onClick={() => onMobileChatModeChange('building')}
>
<Hammer className="h-4 w-4" />
</Button>
</TooltipTrigger>
<TooltipContent>{t('building')}</TooltipContent>
</Tooltip>
)}
{/* Model Selector */}
<div className="flex-1 max-w-72 ml-auto overflow-hidden">
<ModelSelector
value={providerModel}
onChange={setProviderModel}
disabled={isLoading}
placeholder={t('chooseModel')}
/>
</div>
{/* Send/Stop Button */}
{isLoading ? (
<Button
onClick={stopGeneration}
size="sm"
variant="ghost"
className="size-8 rounded-full p-0 bg-foreground/10 [&_svg]:size-3.5 [&_svg]:fill-foreground hover:bg-foreground/20"
>
<Square />
</Button>
) : (
<Button
onClick={handleSend}
size="sm"
disabled={!input.trim() || !providerModel || !hasProviders}
className="size-8 [&_svg]:size-5 rounded-full p-0"
>
<ArrowUp />
</Button>
)}
</div>
</div>
</div>
</div>
);
}
// Mobile: Full screen drawer from bottom
if (isMobile) {
return (
<div className="fixed inset-0 z-50 bg-background flex flex-col animate-in slide-in-from-bottom duration-300">
{/* Header */}
<div className="flex items-center justify-between px-4 py-3 border-b bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/60">
<h2 className="font-semibold text-lg">{t('globalChat')}</h2>
<div className="flex items-center gap-1">
{messages.length > 0 && (
<Tooltip>
<TooltipTrigger asChild>
<Button
variant="ghost"
size="icon"
className="h-8 w-8"
onClick={clearMessages}
>
<Trash2 className="h-4 w-4" />
</Button>
</TooltipTrigger>
<TooltipContent>{t('clearChat')}</TooltipContent>
</Tooltip>
)}
<Button
variant="ghost"
size="icon"
className="h-8 w-8"
onClick={() => setIsOpen(false)}
>
<X className="h-4 w-4" />
</Button>
</div>
</div>
{/* Messages */}
<div
ref={scrollAreaRef}
className="flex-1 overflow-y-auto p-4 space-y-4"
onScroll={handleScroll}
>
{messages.length === 0 ? (
<div className="flex-1 flex items-center justify-center text-center text-muted-foreground px-8 py-12">
<div>
<p className="text-lg font-medium mb-2">{t('globalChatWelcome')}</p>
<p className="text-sm">{t('globalChatDescription')}</p>
</div>
</div>
) : (
messages.map((message) => (
<ChatMessage key={message.id} message={message} />
))
)}
{isLoading && messages[messages.length - 1]?.role !== 'assistant' && (
<div className="flex justify-start">
<div className="bg-muted rounded-2xl rounded-bl-md px-4 py-3">
<Loader2 className="h-4 w-4 animate-spin text-muted-foreground" />
</div>
</div>
)}
</div>
{/* Scroll to bottom button */}
{showScrollToBottom && (
<Button
onClick={scrollToBottom}
size="sm"
variant="secondary"
className="absolute bottom-32 left-1/2 -translate-x-1/2 rounded-full shadow-lg"
>
<ChevronDown className="h-4 w-4" />
</Button>
)}
{/* Input */}
<div className="p-4 border-t bg-background space-y-3 pb-safe">
<div className="flex gap-2">
<ModelSelector
value={providerModel}
onChange={setProviderModel}
className="flex-1"
disabled={isLoading}
placeholder={t('chooseModel')}
/>
</div>
<div className="flex gap-2 items-end">
<Textarea
ref={textareaRef}
value={input}
onChange={(e) => {
setInput(e.target.value);
// Auto-resize
const target = e.target as HTMLTextAreaElement;
target.style.height = 'auto';
target.style.height = Math.min(target.scrollHeight, 128) + 'px';
}}
onKeyDown={handleKeyDown}
placeholder={hasProviders ? t('typeMessage') : t('configureAIFirst')}
disabled={!hasProviders || isLoading}
className="resize-none min-h-[44px] max-h-32"
rows={1}
/>
{isLoading ? (
<Button onClick={stopGeneration} size="icon" variant="destructive" className="h-11 w-11 shrink-0">
<Square className="h-4 w-4" />
</Button>
) : (
<Button
onClick={handleSend}
size="icon"
disabled={!input.trim() || !providerModel || !hasProviders}
className="h-11 w-11 shrink-0"
>
<ArrowUp className="h-4 w-4" />
</Button>
)}
</div>
</div>
</div>
);
}
// Desktop: Floating panel
return (
<div className="fixed bottom-24 right-6 z-50 w-96 max-w-[calc(100vw-3rem)] bg-background border rounded-2xl shadow-2xl flex flex-col animate-in fade-in slide-in-from-bottom-4 duration-300">
{/* Header */}
<div className="flex items-center justify-between px-4 py-3 border-b">
<h2 className="font-semibold">{t('globalChat')}</h2>
<div className="flex items-center gap-1">
{messages.length > 0 && (
<Tooltip>
<TooltipTrigger asChild>
<Button
variant="ghost"
size="icon"
className="h-7 w-7"
onClick={clearMessages}
>
<Trash2 className="h-3.5 w-3.5" />
</Button>
</TooltipTrigger>
<TooltipContent>{t('clearChat')}</TooltipContent>
</Tooltip>
)}
<Tooltip>
<TooltipTrigger asChild>
<Button
variant="ghost"
size="icon"
className="h-7 w-7"
onClick={() => setIsOpen(false)}
>
<X className="h-3.5 w-3.5" />
</Button>
</TooltipTrigger>
<TooltipContent>{t('minimizeChat')}</TooltipContent>
</Tooltip>
</div>
</div>
{/* Messages */}
<div
ref={scrollAreaRef}
className="flex-1 overflow-y-auto p-4 space-y-4 max-h-96 min-h-48"
onScroll={handleScroll}
>
{messages.length === 0 ? (
<div className="flex items-center justify-center text-center text-muted-foreground px-4 py-8">
<div>
<p className="font-medium mb-1">{t('globalChatWelcome')}</p>
<p className="text-xs">{t('globalChatDescription')}</p>
</div>
</div>
) : (
messages.map((message) => (
<ChatMessage key={message.id} message={message} />
))
)}
{isLoading && messages[messages.length - 1]?.role !== 'assistant' && (
<div className="flex justify-start">
<div className="bg-muted rounded-2xl rounded-bl-md px-4 py-3">
<Loader2 className="h-4 w-4 animate-spin text-muted-foreground" />
</div>
</div>
)}
</div>
{/* Scroll to bottom button */}
{showScrollToBottom && (
<div className="absolute bottom-36 left-1/2 -translate-x-1/2">
<Button
onClick={scrollToBottom}
size="sm"
variant="secondary"
className="h-7 w-7 rounded-full shadow-lg p-0"
>
<ChevronDown className="h-3.5 w-3.5" />
</Button>
</div>
)}
{/* Input */}
<div className="p-3 border-t space-y-2">
<ModelSelector
value={providerModel}
onChange={setProviderModel}
className="w-full"
disabled={isLoading}
placeholder={t('chooseModel')}
/>
<div className="flex gap-2 items-end">
<Textarea
ref={textareaRef}
value={input}
onChange={(e) => {
setInput(e.target.value);
// Auto-resize
const target = e.target as HTMLTextAreaElement;
target.style.height = 'auto';
target.style.height = Math.min(target.scrollHeight, 96) + 'px';
}}
onKeyDown={handleKeyDown}
placeholder={hasProviders ? t('typeMessage') : t('configureAIFirst')}
disabled={!hasProviders || isLoading}
className="resize-none min-h-[40px] max-h-24 text-sm"
rows={1}
/>
{isLoading ? (
<Button onClick={stopGeneration} size="icon" variant="destructive" className="h-10 w-10 shrink-0">
<Square className="h-4 w-4" />
</Button>
) : (
<Button
onClick={handleSend}
size="icon"
disabled={!input.trim() || !providerModel || !hasProviders}
className="h-10 w-10 shrink-0"
>
<ArrowUp className="h-4 w-4" />
</Button>
)}
</div>
</div>
</div>
);
}
+224
View File
@@ -0,0 +1,224 @@
import { useState, useCallback, useRef, type ReactNode } from 'react';
import OpenAI from 'openai';
import { GlobalChatContext, type GlobalChatMessage } from '@/contexts/GlobalChatContext';
import { useAISettings } from '@/hooks/useAISettings';
import { useAppContext } from '@/hooks/useAppContext';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { useLocalStorage } from '@/hooks/useLocalStorage';
import { parseProviderModel } from '@/lib/parseProviderModel';
import { createAIClient } from '@/lib/ai-client';
import { defaultGlobalChatSystemPrompt } from '@/lib/globalChatSystem';
// Maximum context size in characters (approximately 50k tokens worth)
// This leaves room for the system prompt and response
const MAX_CONTEXT_CHARS = 150000;
interface GlobalChatProviderProps {
children: ReactNode;
}
export function GlobalChatProvider({ children }: GlobalChatProviderProps) {
const [messages, setMessages] = useState<GlobalChatMessage[]>([]);
const [isOpen, setIsOpenInternal] = useState(false);
const [isLoading, setIsLoading] = useState(false);
const [hasUnread, setHasUnread] = useState(false);
const abortControllerRef = useRef<AbortController | null>(null);
const isOpenRef = useRef(false);
const loadingReleasedRef = useRef(false);
// Separate model storage for global chat (independent from project chat)
const [globalChatModel, setGlobalChatModel] = useLocalStorage<string>('shakespeare-global-chat-model', '');
const { settings } = useAISettings();
const { config } = useAppContext();
const { user } = useCurrentUser();
// When opening the chat, mark messages as read
const setIsOpen = useCallback((open: boolean) => {
isOpenRef.current = open;
setIsOpenInternal(open);
if (open) {
setHasUnread(false);
}
}, []);
// Trim messages from the top when context gets too long
const trimMessages = useCallback((msgs: GlobalChatMessage[]): GlobalChatMessage[] => {
let totalChars = msgs.reduce((sum, msg) => sum + msg.content.length, 0);
if (totalChars <= MAX_CONTEXT_CHARS) {
return msgs;
}
// Remove messages from the beginning until we're under the limit
const trimmedMessages = [...msgs];
while (trimmedMessages.length > 1 && totalChars > MAX_CONTEXT_CHARS) {
const removed = trimmedMessages.shift();
if (removed) {
totalChars -= removed.content.length;
}
}
return trimmedMessages;
}, []);
const sendMessage = useCallback(async (content: string, providerModelString: string) => {
// Parse provider and model
const { model: modelId, provider } = parseProviderModel(providerModelString, settings.providers);
if (!provider) {
console.error('Provider not found');
return;
}
// Create user message
const userMessage: GlobalChatMessage = {
id: crypto.randomUUID(),
role: 'user',
content: content.trim(),
timestamp: Date.now(),
};
// Add user message and capture current messages for API call
let currentMessages: GlobalChatMessage[] = [];
setMessages(prev => {
currentMessages = prev;
return trimMessages([...prev, userMessage]);
});
setIsLoading(true);
// Create abort controller for this request
abortControllerRef.current = new AbortController();
// Reset the loading released flag for this new request
loadingReleasedRef.current = false;
try {
// Create AI client
const client = createAIClient(provider, user, config.corsProxy);
// Build messages for API using captured current messages
const systemPrompt = config.globalChatSystemPrompt || defaultGlobalChatSystemPrompt;
const apiMessages: OpenAI.Chat.Completions.ChatCompletionMessageParam[] = [
{ role: 'system', content: systemPrompt },
...currentMessages.map(msg => ({
role: msg.role as 'user' | 'assistant',
content: msg.content,
})),
{ role: 'user', content: content.trim() },
];
// Create assistant message placeholder
const assistantMessage: GlobalChatMessage = {
id: crypto.randomUUID(),
role: 'assistant',
content: '',
timestamp: Date.now(),
};
setMessages(prev => [...prev, assistantMessage]);
// Stream the response
const stream = await client.chat.completions.create({
model: modelId,
messages: apiMessages,
stream: true,
}, {
signal: abortControllerRef.current.signal,
});
let fullContent = '';
for await (const chunk of stream) {
const delta = chunk.choices[0]?.delta?.content || '';
fullContent += delta;
// Update the assistant message with streamed content
setMessages(prev => {
const updated = [...prev];
const lastMessage = updated[updated.length - 1];
if (lastMessage && lastMessage.role === 'assistant') {
lastMessage.content = fullContent;
}
return updated;
});
// Release loading as soon as finish_reason is received
// Don't break - let the stream drain naturally to avoid async iterator cleanup delays
const finishReason = chunk.choices[0]?.finish_reason;
if (finishReason && !loadingReleasedRef.current) {
loadingReleasedRef.current = true;
setIsLoading(false);
}
}
// Final trim after response is complete
setMessages(prev => trimMessages(prev));
// Mark as unread if chat is closed
if (!isOpenRef.current) {
setHasUnread(true);
}
} catch (error) {
if (error instanceof Error && error.name === 'AbortError') {
// User stopped generation, keep partial response
return;
}
console.error('Global chat error:', error);
// Add error message
const errorMessage: GlobalChatMessage = {
id: crypto.randomUUID(),
role: 'assistant',
content: `Sorry, I encountered an error: ${error instanceof Error ? error.message : 'Unknown error'}`,
timestamp: Date.now(),
};
setMessages(prev => {
// Remove empty assistant message if exists
const filtered = prev.filter(m => m.role !== 'assistant' || m.content.trim());
return [...filtered, errorMessage];
});
} finally {
// Only set loading to false if we haven't already released it
if (!loadingReleasedRef.current) {
setIsLoading(false);
}
abortControllerRef.current = null;
}
}, [config.corsProxy, config.globalChatSystemPrompt, settings.providers, trimMessages, user]);
const stopGeneration = useCallback(() => {
if (abortControllerRef.current) {
abortControllerRef.current.abort();
abortControllerRef.current = null;
setIsLoading(false);
}
}, []);
const clearMessages = useCallback(() => {
setMessages([]);
}, []);
return (
<GlobalChatContext.Provider
value={{
messages,
isOpen,
isLoading,
hasUnread,
providerModel: globalChatModel,
setProviderModel: setGlobalChatModel,
sendMessage,
stopGeneration,
clearMessages,
setIsOpen,
}}
>
{children}
</GlobalChatContext.Provider>
);
}
+25 -1
View File
@@ -5,7 +5,7 @@ import { Textarea } from '@/components/ui/textarea';
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip';
import { CircularProgress } from '@/components/ui/circular-progress';
import { FileAttachment } from '@/components/ui/file-attachment';
import { Square, ArrowUp } from 'lucide-react';
import { Square, ArrowUp, MessageCircle } from 'lucide-react';
import { ModelSelector } from '@/components/ModelSelector';
interface ChatInputProps {
@@ -28,6 +28,9 @@ interface ChatInputProps {
onDragOver: (e: React.DragEvent) => void;
onDragLeave: (e: React.DragEvent) => void;
onDrop: (e: React.DragEvent) => void;
/** Mobile chat mode toggle - only shown on mobile when global chat is enabled */
mobileChatMode?: 'building' | 'chatting';
onMobileChatModeChange?: (mode: 'building' | 'chatting') => void;
}
export const ChatInput = memo(function ChatInput({
@@ -50,6 +53,8 @@ export const ChatInput = memo(function ChatInput({
onDragOver,
onDragLeave,
onDrop,
mobileChatMode,
onMobileChatModeChange,
}: ChatInputProps) {
const { t } = useTranslation();
const [input, setInput] = useState('');
@@ -158,6 +163,25 @@ export const ChatInput = memo(function ChatInput({
{/* Bottom Controls Row */}
<div className="flex items-center gap-4 px-2 py-2">
{/* Mobile Chat Mode Toggle - single button to switch to chatting mode */}
{mobileChatMode && onMobileChatModeChange && (
<TooltipProvider>
<Tooltip>
<TooltipTrigger asChild>
<Button
variant="ghost"
size="icon"
className="h-8 w-8 shrink-0"
onClick={() => onMobileChatModeChange('chatting')}
>
<MessageCircle className="h-4 w-4" />
</Button>
</TooltipTrigger>
<TooltipContent>{t('chatting')}</TooltipContent>
</Tooltip>
</TooltipProvider>
)}
{/* File Attachment */}
<FileAttachment
onFileSelect={handleFileSelect}
+35 -7
View File
@@ -59,6 +59,9 @@ interface ChatPaneProps {
isBuildLoading?: boolean;
consoleError?: ProjectPreviewConsoleError | null;
onDismissConsoleError?: () => void;
/** Mobile chat mode toggle - only shown on mobile when global chat is enabled */
mobileChatMode?: 'building' | 'chatting';
onMobileChatModeChange?: (mode: 'building' | 'chatting') => void;
}
export interface ChatPaneRef {
@@ -74,6 +77,8 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
isBuildLoading: externalIsBuildLoading,
consoleError,
onDismissConsoleError,
mobileChatMode,
onMobileChatModeChange,
}, ref) => {
const { t } = useTranslation();
const [searchParams, setSearchParams] = useSearchParams();
@@ -377,6 +382,8 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
const scrollToBottom = useCallback(() => {
if (scrollAreaRef.current) {
scrollAreaRef.current.scrollTop = scrollAreaRef.current.scrollHeight;
// Reset the flag so auto-scroll resumes
userScrolledUp.current = false;
}
}, []);
@@ -427,17 +434,34 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
};
}, [messages]); // Re-run when messages change to ensure proper setup
// Track whether user has manually scrolled up
const userScrolledUp = useRef(false);
// Detect when user manually scrolls
useEffect(() => {
if (scrollAreaRef.current && (messages || streamingMessage)) {
// Check if user was already at or near the bottom (within 100px threshold)
const container = scrollAreaRef.current;
if (!container) return;
const handleUserScroll = () => {
const threshold = 100;
const container = scrollAreaRef.current;
const isNearBottom = container.scrollTop + container.clientHeight >= container.scrollHeight - threshold;
// Only auto-scroll if user was already near the bottom
if (isNearBottom) {
container.scrollTop = container.scrollHeight;
}
// If user scrolled away from bottom, mark it
// If user scrolled back to bottom, reset the flag
userScrolledUp.current = !isNearBottom;
};
container.addEventListener('scroll', handleUserScroll);
return () => container.removeEventListener('scroll', handleUserScroll);
}, []);
// Auto-scroll when messages change or streaming content updates
useEffect(() => {
if (!scrollAreaRef.current) return;
// Only auto-scroll if user hasn't manually scrolled up
if (!userScrolledUp.current) {
scrollAreaRef.current.scrollTop = scrollAreaRef.current.scrollHeight;
}
}, [messages, streamingMessage, isLoading]);
@@ -448,6 +472,8 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
const timer = setTimeout(() => {
scrollToBottom();
scrolledProjects.add(projectId);
// Reset the userScrolledUp flag when switching projects
userScrolledUp.current = false;
}, 100);
return () => clearTimeout(timer);
@@ -708,6 +734,8 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
onDragOver={handleDragOver}
onDragLeave={handleDragLeave}
onDrop={handleDrop}
mobileChatMode={mobileChatMode}
onMobileChatModeChange={onMobileChatModeChange}
/>
{/* Onboarding Dialog */}
+4
View File
@@ -57,6 +57,10 @@ export interface AppConfig {
sentryEnabled: boolean;
/** System prompt EJS template */
systemPrompt?: string;
/** Whether the global floating chat is enabled */
globalChatEnabled?: boolean;
/** Custom system prompt for global chat */
globalChatSystemPrompt?: string;
}
export interface AppContextType {
+23
View File
@@ -0,0 +1,23 @@
import { createContext } from 'react';
export interface GlobalChatMessage {
id: string;
role: 'user' | 'assistant';
content: string;
timestamp: number;
}
export interface GlobalChatContextType {
messages: GlobalChatMessage[];
isOpen: boolean;
isLoading: boolean;
hasUnread: boolean;
providerModel: string;
setProviderModel: (model: string) => void;
sendMessage: (content: string, providerModel: string) => Promise<void>;
stopGeneration: () => void;
clearMessages: () => void;
setIsOpen: (open: boolean) => void;
}
export const GlobalChatContext = createContext<GlobalChatContextType | undefined>(undefined);
+10
View File
@@ -0,0 +1,10 @@
import { useContext } from 'react';
import { GlobalChatContext, type GlobalChatContextType } from '@/contexts/GlobalChatContext';
export function useGlobalChat(): GlobalChatContextType {
const context = useContext(GlobalChatContext);
if (!context) {
throw new Error('useGlobalChat must be used within a GlobalChatProvider');
}
return context;
}
+96
View File
@@ -0,0 +1,96 @@
/**
* Default system prompt for global chat.
* This provides context about Shakespeare to help users with questions about the platform.
*/
export const defaultGlobalChatSystemPrompt = `You are a helpful AI assistant integrated into Shakespeare, an AI-powered website builder. You're here to have a friendly conversation and help answer questions on any topic.
Keep your responses concise but informative. Be friendly and conversational.
# Your Environment
You are operating within **Shakespeare**, an AI-powered website builder that allows users to create custom applications through natural language conversation.
Users can add or remove templates in Settings > AI.
## What Shakespeare Is
Shakespeare is a web-based development environment where users can build websites and applications by chatting with an AI assistant. The platform combines the power of AI-driven development with a user-friendly interface that requires no coding knowledge from the user.
**Important Architecture Notes:**
- **Browser-Based Storage**: All project files are stored locally in the browser's IndexedDB. If users clear browser data, they may lose their projects.
- **AI Provider Independence**: Shakespeare connects to various AI providers (OpenAI, Anthropic, Shakespeare AI, etc.). Each provider has its own pricing and authentication.
- **Shakespeare AI Credits**: Some AI providers like Shakespeare AI allow users to purchase credits with Bitcoin Lightning, linked to their Nostr identity. These credits are stored on the provider's servers and tied to the user's Nostr pubkey.
- **Cross-Browser Access**:
- **AI Credits**: Users who buy credits with Nostr-enabled providers (like Shakespeare AI) can access those credits from any browser by logging into the same Nostr account (Settings > Nostr).
- **Project Files**: Files are browser-specific. Users can export/import files via Settings > Storage, or sync via Git (Settings > Git) to access projects across browsers.
- **No Central Shakespeare Server**: Shakespeare itself is just client-side software running in the browser. It doesn't store user data or AI credits centrally.
## User Interface
The Shakespeare interface consists of several key areas:
1. **Homepage** (\`/\`): A simple interface with:
- A large textarea where users can describe what they want to build
- A submit button to create new projects from their description
- A left sidebar containing the list of existing projects for easy access
2. **Project View** (\`/projects/:projectId\`): A split-pane interface with:
- **Left Pane**: AI chat interface where users converse with the AI
- **Right Pane**: Toggles between two views:
- **Preview Mode**: Live preview of the website being built
- **Code View**: File explorer and code editor with syntax highlighting
3. **Settings** (\`/settings\`): Accessible from the sidebar menu, includes:
- **Preferences** (\`/settings/preferences\`): Theme and language settings
- **AI Settings** (\`/settings/ai\`): Configure AI providers, API keys, project templates, MCP servers, and plugins
- **Git Settings** (\`/settings/git\`): Configure Git credentials for version control
- **Deploy Settings** (\`/settings/deploy\`): Configure deployment providers (Shakespeare, Netlify, Vercel, nsite)
- **Nostr Settings** (\`/settings/nostr\`): Manage Nostr accounts, relay connections, and ngit servers
- **Storage Settings** (\`/settings/storage\`): Export/import project files, manage browser storage
- **System Settings** (\`/settings/system\`): Advanced configuration (ESM CDN, CORS proxy, service worker, etc.)
- **About** (\`/settings/about\`): License information and project details
## User Actions
Users interact with Shakespeare by:
1. **Creating Projects**: Describing what they want to build in natural language
2. **Chatting with AI**: Requesting features, modifications, and improvements through conversation
3. **Manual Code Editing**: Switching to code view to make direct file edits when desired
4. **Previewing Changes**: Viewing their website in real-time as it's being built
5. **Project Management**: Organizing and accessing multiple projects from the homepage
6. **Deploying Projects**: Publishing their creations to public URLs (requires Nostr login)
## Helpful Resources
When users ask questions about Shakespeare, you may recommend these helpful blog posts and guides:
- **Choosing AI Models**: Learn how to select the best AI model for your project
- https://soapbox.pub/blog/shakespeare-ai-model-selection
- **Configuring AI Providers**: Set up and configure different AI providers
- https://soapbox.pub/blog/shakespeare-configuring-ai-providers
- **Using Local AI Models**: Run AI models locally on your own hardware
- https://soapbox.pub/blog/shakespeare-local-ai-model
- **Editing Code**: Tips for manually editing code in Shakespeare
- https://soapbox.pub/blog/shakespeare-editing-code
- **Deploying & Sharing Projects**: How to deploy and share your projects
- https://soapbox.pub/blog/shakespeare-deploying-sharing-projects
- **Importing Existing Projects**: Bring existing projects into Shakespeare
- https://soapbox.pub/blog/shakespeare-importing-existing-projects
- **Version Control with Git**: Using Git for version control in Shakespeare
- https://soapbox.pub/blog/shakespeare-version-control
- **Debugging**: Troubleshooting and debugging your projects
- https://soapbox.pub/blog/debugging-in-shakespeare
- **Better Prompting**: Tips for writing better prompts to get better results
- https://soapbox.pub/blog/how-to-prompt-better-projects
When a user's question relates to one of these topics, provide a helpful answer and include the relevant link(s) so they can learn more.`;
+21 -1
View File
@@ -63,7 +63,13 @@
"shareErrorReports": "Share error reports",
"shareErrorReportsDescription": "Help improve this app by automatically sending crash and error reports.",
"systemPrompt": "System Prompt",
"systemPrompts": "System Prompts",
"systemPromptDescription": "AI system prompt controlling the assistant's behavior and knowledge.",
"systemPromptsDescription": "Configure the AI system prompts for project development and global chat.",
"projectSystemPrompt": "Project System Prompt",
"projectSystemPromptDescription": "System prompt used when the AI works on your projects. Supports Nunjucks templating for dynamic content.",
"globalChatSystemPrompt": "Chat System Prompt",
"globalChatSystemPromptDescription": "System prompt for the global chat assistant. This prompt provides context about Shakespeare and helpful resources.",
"english": "English",
"portuguese": "Portuguese",
"chinese": "Chinese",
@@ -524,5 +530,19 @@
"templateDeleted": "Template Deleted",
"templateDeletedDescription": "Project template '{{name}}' has been deleted.",
"noTemplatesConfigured": "No project templates configured yet. Add a template to get started.",
"atLeastOneTemplateRequired": "At least one template is required"
"atLeastOneTemplateRequired": "At least one template is required",
"globalChat": "Chat",
"globalChatWelcome": "Hi there! 👋",
"globalChatDescription": "Ask me anything. I'm here to help with questions, ideas, and conversation.",
"clearChat": "Clear chat",
"popOutChat": "Pop out",
"minimizeChat": "Minimize",
"typeMessage": "Type a message...",
"configureAIFirst": "Configure AI provider first",
"globalChatEnabled": "Floating Chat Button",
"globalChatEnabledDescription": "Show a floating chat button for quick AI conversations",
"globalChatSystemPrompt": "Chat System Prompt",
"globalChatSystemPromptDescription": "Custom system prompt for the floating chat assistant",
"building": "Building",
"chatting": "Chatting"
}
+15 -1
View File
@@ -431,5 +431,19 @@
"modified": "An Canza",
"restoreToDefault": "Mayar da asali",
"restoredToDefault": "An Mayar da Asali",
"terminal": "Terminal"
"terminal": "Terminal",
"globalChat": "Tattaunawa",
"globalChatWelcome": "Sannu! 👋",
"globalChatDescription": "Tambayi komai. Ina nan don taimaka da tambayoyi, ra'ayoyi, da tattaunawa.",
"clearChat": "Share tattaunawa",
"popOutChat": "Fitar da waje",
"minimizeChat": "Ragewa",
"typeMessage": "Rubuta sako...",
"configureAIFirst": "Da fari ka saita mai ba da AI",
"globalChatEnabled": "Maballin Tattaunawa Mai Yawo",
"globalChatEnabledDescription": "Nuna maballin tattaunawa mai yawo don saurin tattaunawa da AI",
"globalChatSystemPrompt": "Jagorar Tsarin Tattaunawa",
"globalChatSystemPromptDescription": "Jagorar tsarin da aka keɓe don mataimakin tattaunawa mai yawo",
"building": "Ginawa",
"chatting": "Tattaunawa"
}
+15 -1
View File
@@ -428,5 +428,19 @@
"modified": "Gbanwere",
"restoreToDefault": "Weghachi na nke mbụ",
"restoredToDefault": "Weghachiri na Nke Mbụ",
"terminal": "Terminal"
"terminal": "Terminal",
"globalChat": "Nkata",
"globalChatWelcome": "Ndewo! 👋",
"globalChatDescription": "Jụọ ihe ọ bụla. Anọ m ebe a inyere gị aka na ajụjụ, echiche, na nkata.",
"clearChat": "Kpochapụ nkata",
"popOutChat": "Wepụta",
"minimizeChat": "Belata",
"typeMessage": "Dee ozi...",
"configureAIFirst": "Bụrụ ụzọ hazie onye na-enye AI",
"globalChatEnabled": "Bọtịnụ Nkata Na-epupụta",
"globalChatEnabledDescription": "Gosi bọtịnụ nkata na-epupụta maka nkata AI ngwa ngwa",
"globalChatSystemPrompt": "Usoro Nkata",
"globalChatSystemPromptDescription": "Usoro nke gị maka onye enyemaka nkata na-epupụta",
"building": "Nrụpụta",
"chatting": "Nkwurịta"
}
+15 -1
View File
@@ -440,5 +440,19 @@
"modified": "Modificado",
"restoreToDefault": "Restaurar para padrão",
"restoredToDefault": "Restaurado para Padrão",
"terminal": "Terminal"
"terminal": "Terminal",
"globalChat": "Chat",
"globalChatWelcome": "Olá! 👋",
"globalChatDescription": "Pergunte-me qualquer coisa. Estou aqui para ajudar com perguntas, ideias e conversas.",
"clearChat": "Limpar chat",
"popOutChat": "Destacar",
"minimizeChat": "Minimizar",
"typeMessage": "Digite uma mensagem...",
"configureAIFirst": "Configure o provedor de IA primeiro",
"globalChatEnabled": "Botão de Chat Flutuante",
"globalChatEnabledDescription": "Mostrar um botão de chat flutuante para conversas rápidas com IA",
"globalChatSystemPrompt": "Prompt do Sistema do Chat",
"globalChatSystemPromptDescription": "Prompt do sistema personalizado para o assistente de chat flutuante",
"building": "Construindo",
"chatting": "Conversando"
}
+15 -1
View File
@@ -428,5 +428,19 @@
"modified": "Ti Yipada",
"restoreToDefault": "Pada si atilẹwa",
"restoredToDefault": "Ti Pada si Atilẹwa",
"terminal": "Terminal"
"terminal": "Terminal",
"globalChat": "Ibanisọrọ",
"globalChatWelcome": "Pẹlẹ o! 👋",
"globalChatDescription": "Beere ohunkohun. Mo wa nibi lati ran ọ lọwọ pẹlu awọn ibeere, awọn ero, ati ibaraẹnisọrọ.",
"clearChat": "Pa ibanisọrọ rẹ",
"popOutChat": "Ya jade",
"minimizeChat": "Din ku",
"typeMessage": "Tẹ ifiranṣẹ...",
"configureAIFirst": "Ṣeto olupese AI ni akọkọ",
"globalChatEnabled": "Bọtini Ibanisọrọ Ti O N Lọ",
"globalChatEnabledDescription": "Fi bọtini ibanisọrọ ti o n lọ han fun ibaraẹnisọrọ AI ni iyara",
"globalChatSystemPrompt": "Itọsọna Eto Ibanisọrọ",
"globalChatSystemPromptDescription": "Itọsọna eto aṣa fun oluranlọwọ ibanisọrọ ti o n lọ",
"building": "Kíkọ́",
"chatting": "Sísọ̀rọ̀"
}
+15 -1
View File
@@ -440,5 +440,19 @@
"modified": "已修改",
"restoreToDefault": "恢复默认值",
"restoredToDefault": "已恢复默认值",
"terminal": "终端"
"terminal": "终端",
"globalChat": "聊天",
"globalChatWelcome": "你好! 👋",
"globalChatDescription": "随便问我什么。我在这里帮助回答问题、提供想法和进行对话。",
"clearChat": "清除聊天",
"popOutChat": "弹出窗口",
"minimizeChat": "最小化",
"typeMessage": "输入消息...",
"configureAIFirst": "请先配置AI提供商",
"globalChatEnabled": "浮动聊天按钮",
"globalChatEnabledDescription": "显示浮动聊天按钮以便快速AI对话",
"globalChatSystemPrompt": "聊天系统提示",
"globalChatSystemPromptDescription": "浮动聊天助手的自定义系统提示",
"building": "构建",
"chatting": "聊天"
}
+72 -7
View File
@@ -1,6 +1,6 @@
import { useState, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import { Check, Bot, ArrowLeft, Trash2, GripVertical, ChevronDown, RotateCcw, FileText, Plus, Edit, ExternalLink } from 'lucide-react';
import { Check, Bot, ArrowLeft, Trash2, GripVertical, ChevronDown, RotateCcw, FileText, Plus, Edit, ExternalLink, MessageCircle } from 'lucide-react';
import {
DndContext,
closestCenter,
@@ -44,6 +44,7 @@ import { MCPServersSection } from '@/components/MCPServersSection';
import { PluginsSection } from '@/components/PluginsSection';
import { ProjectTemplatesSection } from '@/components/ProjectTemplatesSection';
import { defaultSystemPrompt } from '@/lib/system';
import { defaultGlobalChatSystemPrompt } from '@/lib/globalChatSystem';
interface SortableProviderItemProps {
provider: AIProvider;
@@ -217,12 +218,20 @@ export function AISettings() {
const [activeCreditsDialog, setActiveCreditsDialog] = useState<string | null>(null);
const [showAdvanced, setShowAdvanced] = useState(false);
const [systemPromptInput, setSystemPromptInput] = useState(config.systemPrompt || defaultSystemPrompt);
const [chatSystemPromptInput, setChatSystemPromptInput] = useState(
config.globalChatSystemPrompt || defaultGlobalChatSystemPrompt
);
// Check if system prompt differs from default
const isSystemPromptModified = useMemo(() =>
(config.systemPrompt || defaultSystemPrompt) !== (defaultConfig.systemPrompt || defaultSystemPrompt),
[config, defaultConfig]);
// Check if chat system prompt differs from default
const isChatSystemPromptModified = useMemo(() =>
(config.globalChatSystemPrompt || defaultGlobalChatSystemPrompt) !== defaultGlobalChatSystemPrompt,
[config]);
const restoreSystemPrompt = () => {
const defaultValue = defaultSystemPrompt;
setSystemPromptInput(defaultValue);
@@ -232,6 +241,14 @@ export function AISettings() {
});
};
const restoreChatSystemPrompt = () => {
setChatSystemPromptInput(defaultGlobalChatSystemPrompt);
updateConfig((current) => {
const { globalChatSystemPrompt, ...rest } = current;
return rest;
});
};
const sensors = useSensors(
useSensor(PointerSensor),
useSensor(KeyboardSensor, {
@@ -685,28 +702,34 @@ export function AISettings() {
<div className="space-y-2">
<div className="flex items-center gap-2">
<FileText className="h-5 w-5 text-primary" />
<h3 className="text-lg font-semibold">{t('systemPrompt')}</h3>
{isSystemPromptModified && (
<h3 className="text-lg font-semibold">{t('systemPrompts')}</h3>
{(isSystemPromptModified || isChatSystemPromptModified) && (
<div className="h-2 w-2 rounded-full bg-yellow-500" title={t('modified')} />
)}
</div>
<p className="text-sm text-muted-foreground">
{t('systemPromptDescription')}
{t('systemPromptsDescription')}
</p>
</div>
<Accordion type="single" collapsible className="w-full">
<Accordion type="single" collapsible className="w-full space-y-2">
<AccordionItem value="system-prompt" className="border rounded-lg">
<AccordionTrigger className="px-4 py-3 hover:no-underline">
<div className="flex items-center gap-2">
<Edit className="h-4 w-4" />
<span className="font-medium">{t('systemPrompt')}</span>
<span className="font-medium">{t('projectSystemPrompt')}</span>
{isSystemPromptModified && (
<div className="h-2 w-2 rounded-full bg-yellow-500" title={t('modified')} />
)}
</div>
</AccordionTrigger>
<AccordionContent className="px-4 pb-4">
<div className="space-y-2">
<p className="text-xs text-muted-foreground mb-2">
{t('projectSystemPromptDescription')}
</p>
<Textarea
id="system-prompt"
placeholder="Enter EJS template..."
placeholder="Enter Nunjucks template..."
value={systemPromptInput}
onChange={(e) => {
const value = e.target.value;
@@ -731,6 +754,48 @@ export function AISettings() {
</div>
</AccordionContent>
</AccordionItem>
<AccordionItem value="chat-system-prompt" className="border rounded-lg">
<AccordionTrigger className="px-4 py-3 hover:no-underline">
<div className="flex items-center gap-2">
<MessageCircle className="h-4 w-4" />
<span className="font-medium">{t('globalChatSystemPrompt')}</span>
{isChatSystemPromptModified && (
<div className="h-2 w-2 rounded-full bg-yellow-500" title={t('modified')} />
)}
</div>
</AccordionTrigger>
<AccordionContent className="px-4 pb-4">
<div className="space-y-2">
<p className="text-xs text-muted-foreground mb-2">
{t('globalChatSystemPromptDescription')}
</p>
<Textarea
id="chat-system-prompt"
placeholder="Enter system prompt..."
value={chatSystemPromptInput}
onChange={(e) => {
const value = e.target.value;
setChatSystemPromptInput(value);
updateConfig((current) => ({
...current,
globalChatSystemPrompt: value,
}));
}}
className="flex-1 font-mono text-xs min-h-[300px]"
/>
{isChatSystemPromptModified && (
<Button
variant="outline"
onClick={restoreChatSystemPrompt}
className="w-full"
>
<RotateCcw className="h-4 w-4 mr-2" />
{t('restoreToDefault')}
</Button>
)}
</div>
</AccordionContent>
</AccordionItem>
</Accordion>
</div>
</div>
+27
View File
@@ -6,6 +6,7 @@ import { ThemePicker } from "@/components/ThemePicker";
import { LanguagePicker } from "@/components/LanguagePicker";
import { Switch } from "@/components/ui/switch";
import { Label } from "@/components/ui/label";
import { Separator } from "@/components/ui/separator";
import { useIsMobile } from "@/hooks/useIsMobile";
import { useNavigate } from "react-router-dom";
import { useAppContext } from "@/hooks/useAppContext";
@@ -98,6 +99,32 @@ export function Preferences() {
{t('shareErrorReportsDescription')}
</p>
</div>
<Separator className="my-4" />
{/* Global Chat Settings */}
<div className="space-y-2">
<div className="flex items-center justify-between">
<div className="space-y-0.5">
<Label htmlFor="global-chat-enabled" className="text-sm font-medium">
{t('globalChatEnabled')}
</Label>
</div>
<Switch
id="global-chat-enabled"
checked={config.globalChatEnabled !== false}
onCheckedChange={(checked) => {
updateConfig((current) => ({
...current,
globalChatEnabled: checked,
}));
}}
/>
</div>
<p className="text-sm text-muted-foreground">
{t('globalChatEnabledDescription')}
</p>
</div>
</div>
</CardContent>
</Card>
+38 -21
View File
@@ -20,6 +20,8 @@ import { useBuildProject } from '@/hooks/useBuildProject';
import { useIsProjectPreviewable } from '@/hooks/useIsProjectPreviewable';
import { useConsoleError } from '@/hooks/useConsoleError';
import { useAutoBuild } from '@/hooks/useAutoBuild';
import { GlobalChatPane } from '@/components/GlobalChatPane';
import { useAppContext } from '@/hooks/useAppContext';
export function ProjectView() {
const { projectId } = useParams<{ projectId: string }>();
@@ -28,6 +30,7 @@ export function ProjectView() {
const [isLoading, setIsLoading] = useState(true);
const [activeTab, setActiveTab] = useState<'preview' | 'code'>('preview');
const [mobileView, setMobileView] = useState<'chat' | 'preview' | 'code'>('chat');
const [mobileChatMode, setMobileChatMode] = useState<'building' | 'chatting'>('building');
const [isAILoading, setIsAILoading] = useState(false);
const [isProjectDetailsOpen, setIsProjectDetailsOpen] = useState(false);
@@ -38,6 +41,7 @@ export function ProjectView() {
const chatPaneRef = useRef<ChatPaneRef>(null);
const navigate = useNavigate();
const isMobile = useIsMobile();
const { config } = useAppContext();
const [isSidebarVisible, setIsSidebarVisible] = useState(!isMobile);
@@ -218,28 +222,41 @@ export function ProjectView() {
</div>
)}
<div className="flex-1 overflow-hidden">
<div className="flex-1 overflow-hidden flex flex-col">
{mobileView === 'chat' && (
project ? (
<ChatPane
ref={chatPaneRef}
projectId={project.id}
onNewChat={handleNewChat}
onFirstInteraction={handleFirstInteraction}
onLoadingChange={handleAILoadingChange}
isLoading={isAILoading}
isBuildLoading={build.isPending}
consoleError={consoleError}
onDismissConsoleError={handleDismissConsoleError}
/>
) : (
<div className="h-full p-4 space-y-4">
<Skeleton className="h-12 w-full" />
<Skeleton className="h-8 w-3/4" />
<Skeleton className="h-8 w-1/2" />
<Skeleton className="h-32 w-full" />
</div>
)
/* Chat content based on mode - toggle is inside the compose area */
<div className="flex-1 overflow-hidden">
{mobileChatMode === 'building' ? (
project ? (
<ChatPane
ref={chatPaneRef}
projectId={project.id}
onNewChat={handleNewChat}
onFirstInteraction={handleFirstInteraction}
onLoadingChange={handleAILoadingChange}
isLoading={isAILoading}
isBuildLoading={build.isPending}
consoleError={consoleError}
onDismissConsoleError={handleDismissConsoleError}
mobileChatMode={config.globalChatEnabled !== false ? mobileChatMode : undefined}
onMobileChatModeChange={config.globalChatEnabled !== false ? setMobileChatMode : undefined}
/>
) : (
<div className="h-full p-4 space-y-4">
<Skeleton className="h-12 w-full" />
<Skeleton className="h-8 w-3/4" />
<Skeleton className="h-8 w-1/2" />
<Skeleton className="h-32 w-full" />
</div>
)
) : (
<GlobalChatPane
embedded
mobileChatMode={mobileChatMode}
onMobileChatModeChange={setMobileChatMode}
/>
)}
</div>
)}
{(mobileView === 'preview' || mobileView === 'code') && (
project ? (