Compare commits

...
39 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
Alex Gleason 2096c83b3c Let baseDomain be configured for Cloudflare and Deno Deploy 2025-12-04 00:17:11 -06:00
Alex Gleason bbb4a2534b Fix Deno Deploy so it works 2025-12-04 00:02:50 -06:00
Alex Gleason 5685c6f52f Fix Deno config in configUtils 2025-12-03 23:57:01 -06:00
Alex Gleason 12c4acf3d5 Add Deno Deploy adapter 2025-12-03 23:48:20 -06:00
Alex Gleason 77a648e77e Redesign inputs on other pages 2025-12-03 23:20:02 -06:00
Alex Gleason ff6932ecda Upload Cloudflare files in parallel 2025-12-03 23:11:15 -06:00
Alex Gleason 74b5f60df8 Improve Get Key inputs 2025-12-03 23:02:50 -06:00
Alex Gleason 6c4bd9bd7c Deploy to Cloudflare Workers instead of Cloudflare Pages 2025-12-03 22:57:12 -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
Alex Gleason 45061bfbb9 Merge remote-tracking branch 'origin/main' into cf 2025-12-03 22:05:31 -06:00
Alex Gleason 6ce25ad2a1 Add the missing headers to the OPTIONS response 2025-12-03 22:05:05 -06:00
Alex Gleason 1f896b2ab5 Merge remote-tracking branch 'origin/main' into cf 2025-12-03 22:04:33 -06:00
Alex Gleason ed7f60692d Allow PUT and PATCH through CORS proxy 2025-12-03 21:58:02 -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
Alex Gleason cc8a02a564 Fix Cloudflare config persistence 2025-12-03 21:21:30 -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
Alex Gleason 9017c5c382 Fix Cloudflare deploy 2025-12-03 20:53:04 -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
Alex Gleason 3f3ac26c65 Fix account ID URL 2025-12-03 20:28:33 -06:00
Alex Gleason fef40abcae Improve input external link hover style 2025-12-03 20:09:47 -06:00
Alex Gleason b345145ad3 Improve design of "Get Key" inputs 2025-12-03 20:02:50 -06:00
Alex Gleason 46db6542aa Add Cloudflare deployment provider 2025-12-03 19:37:36 -06:00
32 changed files with 2547 additions and 326 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>
+2 -2
View File
@@ -13,7 +13,7 @@ export default {
status: 200,
headers: {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET,HEAD,POST,OPTIONS",
"Access-Control-Allow-Methods": "GET,HEAD,POST,PUT,PATCH,DELETE,OPTIONS",
"Access-Control-Allow-Headers": "*", // Or specify specific headers
"Access-Control-Max-Age": "86400", // Cache preflight for 24 hours
}
@@ -32,7 +32,7 @@ export default {
const response = new Response(targetResponse.body, targetResponse);
response.headers.set("Access-Control-Allow-Origin", "*");
response.headers.set("Access-Control-Allow-Methods", "GET,HEAD,POST,OPTIONS");
response.headers.set("Access-Control-Allow-Methods", "GET,HEAD,POST,PUT,PATCH,DELETE,OPTIONS");
response.headers.set("Access-Control-Allow-Headers", "*");
return response;
+133 -3
View File
@@ -27,13 +27,15 @@ import { useFS } from '@/hooks/useFS';
import { useFSPaths } from '@/hooks/useFSPaths';
import { useAppContext } from '@/hooks/useAppContext';
import { useNostr } from '@nostrify/react';
import { ShakespeareAdapter, NetlifyAdapter, VercelAdapter, NsiteAdapter, DeployAdapter } from '@/lib/deploy';
import { ShakespeareAdapter, NetlifyAdapter, VercelAdapter, NsiteAdapter, CloudflareAdapter, DenoDeployAdapter, DeployAdapter } from '@/lib/deploy';
import { Link } from 'react-router-dom';
import type { DeployProvider, ShakespeareDeployProvider, NetlifyProvider, VercelProvider } from '@/contexts/DeploySettingsContext';
import type { DeployProvider, ShakespeareDeployProvider, NetlifyProvider, VercelProvider, CloudflareProvider, DenoDeployProvider } from '@/contexts/DeploySettingsContext';
import { ShakespeareDeployForm } from '@/components/deploy/ShakespeareDeployForm';
import { NetlifyDeployForm } from '@/components/deploy/NetlifyDeployForm';
import { VercelDeployForm } from '@/components/deploy/VercelDeployForm';
import { NsiteDeployForm } from '@/components/deploy/NsiteDeployForm';
import { CloudflareDeployForm } from '@/components/deploy/CloudflareDeployForm';
import { DenoDeployForm } from '@/components/deploy/DenoDeployForm';
/**
* Helper function to get provider URL for favicon
@@ -58,6 +60,18 @@ function getProviderUrl(provider: DeployProvider): string | null {
}
return 'https://vercel.com';
case 'cloudflare':
if (provider.baseURL) {
return provider.baseURL;
}
return 'https://cloudflare.com';
case 'deno':
if (provider.baseURL) {
return provider.baseURL;
}
return 'https://deno.com';
case 'nsite':
return null;
@@ -110,6 +124,14 @@ interface VercelFormData {
teamId: string;
}
interface CloudflareFormData {
projectName: string;
}
interface DenoDeployFormData {
projectName: string;
}
export function DeployDialog({ projectId, projectName, open, onOpenChange }: DeployDialogProps) {
const { t } = useTranslation();
const { settings } = useDeploySettings();
@@ -141,6 +163,12 @@ export function DeployDialog({ projectId, projectName, open, onOpenChange }: Dep
projectName: projectName || projectId,
teamId: '',
});
const [cloudflareForm, setCloudflareForm] = useState<CloudflareFormData>({
projectName: projectName || projectId,
});
const [denoDeployForm, setDenoDeployForm] = useState<DenoDeployFormData>({
projectName: projectName || projectId,
});
// Load project settings when dialog opens
useEffect(() => {
@@ -230,6 +258,42 @@ export function DeployDialog({ projectId, projectName, open, onOpenChange }: Dep
projectName: vercelForm.projectName || undefined,
corsProxy: vercelProvider.proxy ? config.corsProxy : undefined,
});
} else if (selectedProvider.type === 'cloudflare') {
const cloudflareProvider = selectedProvider as CloudflareProvider;
if (!cloudflareProvider.apiKey) {
throw new Error('Cloudflare API key is required');
}
if (!cloudflareProvider.accountId) {
throw new Error('Cloudflare account ID is required');
}
adapter = new CloudflareAdapter({
fs,
apiKey: cloudflareProvider.apiKey,
accountId: cloudflareProvider.accountId,
baseURL: cloudflareProvider.baseURL,
baseDomain: cloudflareProvider.baseDomain,
projectName: cloudflareForm.projectName || undefined,
corsProxy: cloudflareProvider.proxy ? config.corsProxy : undefined,
});
} else if (selectedProvider.type === 'deno') {
const denoProvider = selectedProvider as DenoDeployProvider;
if (!denoProvider.apiKey) {
throw new Error('Deno Deploy access token is required');
}
if (!denoProvider.organizationId) {
throw new Error('Deno Deploy organization ID is required');
}
adapter = new DenoDeployAdapter({
fs,
apiKey: denoProvider.apiKey,
organizationId: denoProvider.organizationId,
baseDomain: denoProvider.baseDomain,
baseURL: denoProvider.baseURL,
projectName: denoDeployForm.projectName || undefined,
corsProxy: denoProvider.proxy ? config.corsProxy : undefined,
});
} else {
throw new Error('Unknown provider type');
}
@@ -269,6 +333,20 @@ export function DeployDialog({ projectId, projectName, open, onOpenChange }: Dep
projectId: vercelForm.projectName || undefined,
},
});
} else if (selectedProvider.type === 'cloudflare') {
await updateProjectSettings(selectedProviderId, {
type: 'cloudflare',
data: {
projectName: cloudflareForm.projectName || undefined,
},
});
} else if (selectedProvider.type === 'deno') {
await updateProjectSettings(selectedProviderId, {
type: 'deno',
data: {
projectName: denoDeployForm.projectName || undefined,
},
});
}
setDeployResult(result);
@@ -288,6 +366,8 @@ export function DeployDialog({ projectId, projectName, open, onOpenChange }: Dep
setNsiteForm({ nsec: '' });
setNetlifyForm({ siteId: '', siteName: '' });
setVercelForm({ projectName: projectName || projectId, teamId: '' });
setCloudflareForm({ projectName: projectName || projectId });
setDenoDeployForm({ projectName: projectName || projectId });
onOpenChange(false);
};
@@ -311,6 +391,14 @@ export function DeployDialog({ projectId, projectName, open, onOpenChange }: Dep
setVercelForm({ projectName, teamId });
}, []);
const handleCloudflareProjectChange = useCallback((projectName: string) => {
setCloudflareForm({ projectName });
}, []);
const handleDenoDeployProjectChange = useCallback((projectName: string) => {
setDenoDeployForm({ projectName });
}, []);
const renderProviderFields = () => {
if (!selectedProvider) return null;
@@ -373,6 +461,46 @@ export function DeployDialog({ projectId, projectName, open, onOpenChange }: Dep
);
}
if (selectedProvider.type === 'cloudflare') {
const cloudflareProvider = selectedProvider as CloudflareProvider;
const savedConfig = projectSettings.providers[selectedProviderId];
const savedProjectName = savedConfig?.type === 'cloudflare' ? savedConfig.data.projectName : undefined;
return (
<CloudflareDeployForm
apiKey={cloudflareProvider.apiKey}
accountId={cloudflareProvider.accountId}
baseURL={cloudflareProvider.baseURL}
baseDomain={cloudflareProvider.baseDomain}
projectId={projectId}
projectName={projectName}
savedProjectName={savedProjectName}
onProjectChange={handleCloudflareProjectChange}
corsProxy={cloudflareProvider.proxy ? config.corsProxy : undefined}
/>
);
}
if (selectedProvider.type === 'deno') {
const denoProvider = selectedProvider as DenoDeployProvider;
const savedConfig = projectSettings.providers[selectedProviderId];
const savedProjectName = savedConfig?.type === 'deno' ? savedConfig.data.projectName : undefined;
return (
<DenoDeployForm
apiKey={denoProvider.apiKey}
organizationId={denoProvider.organizationId}
baseURL={denoProvider.baseURL}
baseDomain={denoProvider.baseDomain}
projectId={projectId}
projectName={projectName}
savedProjectName={savedProjectName}
onProjectChange={handleDenoDeployProjectChange}
corsProxy={denoProvider.proxy ? config.corsProxy : undefined}
/>
);
}
return null;
};
@@ -503,7 +631,9 @@ export function DeployDialog({ projectId, projectName, open, onOpenChange }: Dep
(selectedProvider.type === 'shakespeare' && !user) ||
(selectedProvider.type === 'shakespeare' && !isShakespeareFormValid) ||
(selectedProvider.type === 'nsite' && !nsiteForm.nsec) ||
(selectedProvider.type === 'netlify' && !netlifyForm.siteId && !netlifyForm.siteName)
(selectedProvider.type === 'netlify' && !netlifyForm.siteId && !netlifyForm.siteName) ||
(selectedProvider.type === 'cloudflare' && !cloudflareForm.projectName) ||
(selectedProvider.type === 'deno' && !denoDeployForm.projectName)
}
>
{isDeploying ? (
+73 -18
View File
@@ -1,36 +1,91 @@
import { MessageCircle } from 'lucide-react';
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 (
<Button
onClick={() => setIsOpen(!isOpen)}
size="lg"
className={cn(
'fixed bottom-6 right-6 z-40 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'}
<div
className="fixed bottom-6 right-6 z-40"
onMouseEnter={() => setIsHovered(true)}
onMouseLeave={() => setIsHovered(false)}
>
<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>
{/* 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>
);
}
+223 -19
View File
@@ -1,6 +1,7 @@
import { useState, useRef, useEffect, useCallback } from 'react';
import { useTranslation } from 'react-i18next';
import { X, Minimize2, Trash2, Copy, Check, ChevronDown, ArrowUp, Square, Loader2 } from 'lucide-react';
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';
@@ -79,7 +80,15 @@ function ChatMessage({ message }: { message: GlobalChatMessage }) {
);
}
export function GlobalChatPane() {
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,
@@ -95,12 +104,18 @@ export function GlobalChatPane() {
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) {
@@ -108,23 +123,43 @@ export function GlobalChatPane() {
}
}, [providerModel, settings.recentlyUsedModels, setProviderModel]);
// Auto-scroll to bottom when new messages arrive
// Scroll to bottom and focus textarea when chat opens (or when embedded mode becomes active)
useEffect(() => {
if (scrollAreaRef.current) {
const container = scrollAreaRef.current;
const isNearBottom = container.scrollTop + container.clientHeight >= container.scrollHeight - 100;
if (isNearBottom || messages.length <= 1) {
container.scrollTop = container.scrollHeight;
}
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;
}
}, [messages]);
}, [isOpen, embedded]);
// Handle scroll to show/hide scroll-to-bottom button
// 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 isNearBottom = container.scrollTop + container.clientHeight >= container.scrollHeight - 100;
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]);
@@ -132,6 +167,8 @@ export function GlobalChatPane() {
const scrollToBottom = useCallback(() => {
if (scrollAreaRef.current) {
scrollAreaRef.current.scrollTop = scrollAreaRef.current.scrollHeight;
// Reset the flag so auto-scroll resumes
userScrolledUp.current = false;
}
}, []);
@@ -141,12 +178,19 @@ export function GlobalChatPane() {
const messageContent = input.trim();
setInput('');
await sendMessage(messageContent, providerModel);
// Focus back on textarea
// 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();
@@ -154,13 +198,173 @@ export function GlobalChatPane() {
}
}, [handleSend, isMobile]);
// Don't render if disabled or not open
if (config.globalChatEnabled === false || !isOpen) {
// 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 (
@@ -313,7 +517,7 @@ export function GlobalChatPane() {
className="h-7 w-7"
onClick={() => setIsOpen(false)}
>
<Minimize2 className="h-3.5 w-3.5" />
<X className="h-3.5 w-3.5" />
</Button>
</TooltipTrigger>
<TooltipContent>{t('minimizeChat')}</TooltipContent>
+28 -15
View File
@@ -7,16 +7,12 @@ 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;
// Default system prompt for global chat
const DEFAULT_GLOBAL_CHAT_SYSTEM_PROMPT = `You are a helpful AI assistant. 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.`;
interface GlobalChatProviderProps {
children: ReactNode;
}
@@ -28,6 +24,7 @@ export function GlobalChatProvider({ children }: GlobalChatProviderProps) {
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', '');
@@ -66,8 +63,6 @@ export function GlobalChatProvider({ children }: GlobalChatProviderProps) {
}, []);
const sendMessage = useCallback(async (content: string, providerModelString: string) => {
if (!content.trim() || isLoading) return;
// Parse provider and model
const { model: modelId, provider } = parseProviderModel(providerModelString, settings.providers);
@@ -84,23 +79,30 @@ export function GlobalChatProvider({ children }: GlobalChatProviderProps) {
timestamp: Date.now(),
};
// Add user message and trim if necessary
setMessages(prev => trimMessages([...prev, userMessage]));
// 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, config.corsProxy, user?.signer);
const client = createAIClient(provider, user, config.corsProxy);
// Build messages for API
const systemPrompt = config.globalChatSystemPrompt || DEFAULT_GLOBAL_CHAT_SYSTEM_PROMPT;
// Build messages for API using captured current messages
const systemPrompt = config.globalChatSystemPrompt || defaultGlobalChatSystemPrompt;
const apiMessages: OpenAI.Chat.Completions.ChatCompletionMessageParam[] = [
{ role: 'system', content: systemPrompt },
...messages.map(msg => ({
...currentMessages.map(msg => ({
role: msg.role as 'user' | 'assistant',
content: msg.content,
})),
@@ -141,6 +143,14 @@ export function GlobalChatProvider({ children }: GlobalChatProviderProps) {
}
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
@@ -173,10 +183,13 @@ export function GlobalChatProvider({ children }: GlobalChatProviderProps) {
return [...filtered, errorMessage];
});
} finally {
setIsLoading(false);
// Only set loading to false if we haven't already released it
if (!loadingReleasedRef.current) {
setIsLoading(false);
}
abortControllerRef.current = null;
}
}, [config.corsProxy, config.globalChatSystemPrompt, isLoading, messages, settings.providers, trimMessages, user?.signer]);
}, [config.corsProxy, config.globalChatSystemPrompt, settings.providers, trimMessages, user]);
const stopGeneration = useCallback(() => {
if (abortControllerRef.current) {
+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 */}
@@ -0,0 +1,219 @@
import { useState, useEffect, useCallback } from 'react';
import { Plus, ExternalLink } from 'lucide-react';
import { Label } from '@/components/ui/label';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/components/ui/select';
import { Alert, AlertDescription } from '@/components/ui/alert';
import { Skeleton } from '@/components/ui/skeleton';
import { proxyUrl } from '@/lib/proxyUrl';
interface CloudflareWorkerScript {
id: string;
etag: string;
handlers: string[];
modified_on: string;
created_on: string;
has_assets: boolean;
}
interface CloudflareDeployFormProps {
apiKey: string;
accountId: string;
baseURL?: string;
baseDomain?: string;
projectId: string;
projectName?: string;
savedProjectName?: string;
onProjectChange: (projectName: string) => void;
corsProxy?: string;
}
export function CloudflareDeployForm({
apiKey,
accountId,
baseURL = 'https://api.cloudflare.com/client/v4',
baseDomain = 'workers.dev',
projectId,
projectName,
savedProjectName,
onProjectChange,
corsProxy,
}: CloudflareDeployFormProps) {
const [workers, setWorkers] = useState<CloudflareWorkerScript[]>([]);
const [workersSubdomain, setWorkersSubdomain] = useState<string | null>(null);
const [isLoading, setIsLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [selectedProjectName, setSelectedProjectName] = useState<string>('');
const [newProjectName, setNewProjectName] = useState(projectName || projectId);
const fetchWorkersData = useCallback(async () => {
setIsLoading(true);
setError(null);
try {
// Fetch workers subdomain and workers list in parallel
const subdomainUrl = `${baseURL}/accounts/${accountId}/workers/subdomain`;
const workersUrl = `${baseURL}/accounts/${accountId}/workers/scripts`;
const [subdomainResponse, workersResponse] = await Promise.all([
fetch(corsProxy ? proxyUrl(corsProxy, subdomainUrl) : subdomainUrl, {
headers: { 'Authorization': `Bearer ${apiKey}` },
}),
fetch(corsProxy ? proxyUrl(corsProxy, workersUrl) : workersUrl, {
headers: { 'Authorization': `Bearer ${apiKey}` },
}),
]);
if (!subdomainResponse.ok) {
throw new Error(`Failed to fetch workers subdomain: ${subdomainResponse.status} ${subdomainResponse.statusText}`);
}
if (!workersResponse.ok) {
throw new Error(`Failed to fetch workers: ${workersResponse.status} ${workersResponse.statusText}`);
}
const [subdomainData, workersData] = await Promise.all([
subdomainResponse.json(),
workersResponse.json(),
]);
setWorkersSubdomain(subdomainData.result?.subdomain || null);
setWorkers(workersData.result || []);
// If there's a saved project name and it exists in the list, select it
// Otherwise leave it empty (showing placeholder)
if (savedProjectName && workersData.result?.some((w: CloudflareWorkerScript) => w.id === savedProjectName)) {
setSelectedProjectName(savedProjectName);
}
} catch (err) {
setError(err instanceof Error ? err.message : 'Failed to fetch workers data');
} finally {
setIsLoading(false);
}
}, [apiKey, accountId, baseURL, savedProjectName, corsProxy]);
useEffect(() => {
fetchWorkersData();
}, [fetchWorkersData]);
// Update newProjectName when switching to "new" if it's empty
useEffect(() => {
if (selectedProjectName === 'new' && !newProjectName) {
setNewProjectName(projectName || projectId);
}
}, [selectedProjectName, newProjectName, projectName, projectId]);
useEffect(() => {
if (selectedProjectName === '') {
// No selection yet - don't call onProjectChange
return;
} else if (selectedProjectName === 'new') {
onProjectChange(newProjectName);
} else {
onProjectChange(selectedProjectName);
}
}, [selectedProjectName, newProjectName, onProjectChange]);
if (isLoading) {
return (
<div className="space-y-4">
<div className="space-y-2">
<Label>Project</Label>
<Skeleton className="h-10 w-full" />
</div>
<Skeleton className="h-4 w-3/4" />
</div>
);
}
const selectedWorker = workers.find(w => w.id === selectedProjectName);
// Construct the URL preview
const getWorkerUrl = (scriptName: string) => {
if (workersSubdomain) {
return `https://${scriptName}.${workersSubdomain}.${baseDomain}`;
}
return `https://${scriptName}.<subdomain>.${baseDomain}`;
};
return (
<div className="space-y-4">
{error && (
<Alert variant="destructive">
<AlertDescription>{error}</AlertDescription>
</Alert>
)}
<div className="space-y-2">
<Label htmlFor="cloudflare-project">Select Worker</Label>
<Select value={selectedProjectName} onValueChange={setSelectedProjectName}>
<SelectTrigger id="cloudflare-project">
<SelectValue placeholder="Select a worker or create new..." />
</SelectTrigger>
<SelectContent>
<SelectItem value="new">
<div className="flex items-center gap-2">
<Plus className="h-4 w-4" />
Create new worker
</div>
</SelectItem>
{workers.map((worker) => (
<SelectItem key={worker.id} value={worker.id}>
{worker.id}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
{selectedProjectName === 'new' ? (
<div className="space-y-2">
<Label htmlFor="new-project-name">New Worker Name</Label>
<Input
id="new-project-name"
value={newProjectName}
onChange={(e) => setNewProjectName(e.target.value)}
placeholder={projectName || projectId}
/>
<p className="text-xs text-muted-foreground">
URL: <span className="font-mono">{getWorkerUrl(newProjectName || projectId)}</span>
</p>
<p className="text-xs text-muted-foreground">
A new worker will be created when you deploy
</p>
</div>
) : selectedWorker ? (
<div className="space-y-2">
<div className="rounded-lg border p-3 space-y-2">
<div className="flex items-center justify-between">
<div>
<p className="text-sm font-medium">{selectedWorker.id}</p>
<p className="text-xs text-muted-foreground font-mono">
{getWorkerUrl(selectedWorker.id)}
</p>
</div>
<Button
type="button"
variant="ghost"
size="sm"
onClick={() => window.open(`https://dash.cloudflare.com/${accountId}/workers/services/view/${selectedWorker.id}`, '_blank')}
>
<ExternalLink className="h-4 w-4" />
</Button>
</div>
</div>
<p className="text-xs text-muted-foreground">
Deployment will update this existing worker
</p>
</div>
) : null}
</div>
);
}
+198
View File
@@ -0,0 +1,198 @@
import { useState, useEffect, useCallback } from 'react';
import { Plus, ExternalLink } from 'lucide-react';
import { Label } from '@/components/ui/label';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/components/ui/select';
import { Alert, AlertDescription } from '@/components/ui/alert';
import { Skeleton } from '@/components/ui/skeleton';
import { proxyUrl } from '@/lib/proxyUrl';
interface DenoProject {
id: string;
name: string;
createdAt: string;
updatedAt: string;
}
interface DenoDeployFormProps {
apiKey: string;
organizationId: string;
baseURL?: string;
baseDomain?: string;
projectId: string;
projectName?: string;
savedProjectName?: string;
onProjectChange: (projectName: string) => void;
corsProxy?: string;
}
export function DenoDeployForm({
apiKey,
organizationId,
baseURL = 'https://api.deno.com/v1',
baseDomain = 'deno.dev',
projectId,
projectName,
savedProjectName,
onProjectChange,
corsProxy,
}: DenoDeployFormProps) {
const [projects, setProjects] = useState<DenoProject[]>([]);
const [isLoading, setIsLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [selectedProjectName, setSelectedProjectName] = useState<string>('');
const [newProjectName, setNewProjectName] = useState(projectName || projectId);
const fetchProjects = useCallback(async () => {
setIsLoading(true);
setError(null);
try {
const url = `${baseURL}/organizations/${organizationId}/projects?limit=100`;
const targetUrl = corsProxy ? proxyUrl(corsProxy, url) : url;
const response = await fetch(targetUrl, {
headers: { 'Authorization': `Bearer ${apiKey}` },
});
if (!response.ok) {
throw new Error(`Failed to fetch projects: ${response.status} ${response.statusText}`);
}
const data: DenoProject[] = await response.json();
setProjects(data);
// If there's a saved project name and it exists in the list, select it
// Otherwise leave it empty (showing placeholder)
if (savedProjectName && data.some((p: DenoProject) => p.name === savedProjectName)) {
setSelectedProjectName(savedProjectName);
}
} catch (err) {
setError(err instanceof Error ? err.message : 'Failed to fetch projects');
} finally {
setIsLoading(false);
}
}, [apiKey, organizationId, baseURL, savedProjectName, corsProxy]);
useEffect(() => {
fetchProjects();
}, [fetchProjects]);
// Update newProjectName when switching to "new" if it's empty
useEffect(() => {
if (selectedProjectName === 'new' && !newProjectName) {
setNewProjectName(projectName || projectId);
}
}, [selectedProjectName, newProjectName, projectName, projectId]);
useEffect(() => {
if (selectedProjectName === '') {
// No selection yet - don't call onProjectChange
return;
} else if (selectedProjectName === 'new') {
onProjectChange(newProjectName);
} else {
onProjectChange(selectedProjectName);
}
}, [selectedProjectName, newProjectName, onProjectChange]);
if (isLoading) {
return (
<div className="space-y-4">
<div className="space-y-2">
<Label>Project</Label>
<Skeleton className="h-10 w-full" />
</div>
<Skeleton className="h-4 w-3/4" />
</div>
);
}
const selectedProject = projects.find(p => p.name === selectedProjectName);
// Construct the URL preview
const getProjectUrl = (name: string) => {
return `https://${name}.${baseDomain}`;
};
return (
<div className="space-y-4">
{error && (
<Alert variant="destructive">
<AlertDescription>{error}</AlertDescription>
</Alert>
)}
<div className="space-y-2">
<Label htmlFor="deno-project">Select Project</Label>
<Select value={selectedProjectName} onValueChange={setSelectedProjectName}>
<SelectTrigger id="deno-project">
<SelectValue placeholder="Select a project or create new..." />
</SelectTrigger>
<SelectContent>
<SelectItem value="new">
<div className="flex items-center gap-2">
<Plus className="h-4 w-4" />
Create new project
</div>
</SelectItem>
{projects.map((project) => (
<SelectItem key={project.id} value={project.name}>
{project.name}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
{selectedProjectName === 'new' ? (
<div className="space-y-2">
<Label htmlFor="new-project-name">New Project Name</Label>
<Input
id="new-project-name"
value={newProjectName}
onChange={(e) => setNewProjectName(e.target.value)}
placeholder={projectName || projectId}
/>
<p className="text-xs text-muted-foreground">
URL: <span className="font-mono">{getProjectUrl(newProjectName || projectId)}</span>
</p>
<p className="text-xs text-muted-foreground">
A new project will be created when you deploy
</p>
</div>
) : selectedProject ? (
<div className="space-y-2">
<div className="rounded-lg border p-3 space-y-2">
<div className="flex items-center justify-between">
<div>
<p className="text-sm font-medium">{selectedProject.name}</p>
<p className="text-xs text-muted-foreground font-mono">
{getProjectUrl(selectedProject.name)}
</p>
</div>
<Button
type="button"
variant="ghost"
size="sm"
onClick={() => window.open(`https://dash.deno.com/projects/${selectedProject.name}`, '_blank')}
>
<ExternalLink className="h-4 w-4" />
</Button>
</div>
</div>
<p className="text-xs text-muted-foreground">
Deployment will create a new version for this project
</p>
</div>
) : null}
</div>
);
}
+2
View File
@@ -2,3 +2,5 @@ export { ShakespeareDeployForm } from './ShakespeareDeployForm';
export { NetlifyDeployForm } from './NetlifyDeployForm';
export { VercelDeployForm } from './VercelDeployForm';
export { NsiteDeployForm } from './NsiteDeployForm';
export { CloudflareDeployForm } from './CloudflareDeployForm';
export { DenoDeployForm } from './DenoDeployForm';
+24 -16
View File
@@ -2,8 +2,13 @@ import * as React from "react"
import { Eye, EyeOff } from "lucide-react"
import { cn } from "@/lib/utils"
const PasswordInput = React.forwardRef<HTMLInputElement, React.InputHTMLAttributes<HTMLInputElement>>(
({ className, ...props }, ref) => {
interface PasswordInputProps extends React.InputHTMLAttributes<HTMLInputElement> {
/** Whether to show the visibility toggle button. Defaults to true. */
showToggle?: boolean;
}
const PasswordInput = React.forwardRef<HTMLInputElement, PasswordInputProps>(
({ className, showToggle = true, ...props }, ref) => {
const [showPassword, setShowPassword] = React.useState(false)
const [isFocused, setIsFocused] = React.useState(false)
@@ -12,7 +17,8 @@ const PasswordInput = React.forwardRef<HTMLInputElement, React.InputHTMLAttribut
<input
type={showPassword ? "text" : "password"}
className={cn(
"flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 pr-10 text-base ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-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",
"flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-base ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-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",
showToggle && "pr-10",
isFocused && "ring-2 ring-ring ring-offset-2"
)}
ref={ref}
@@ -26,19 +32,21 @@ const PasswordInput = React.forwardRef<HTMLInputElement, React.InputHTMLAttribut
}}
{...props}
/>
<button
type="button"
onClick={() => setShowPassword(!showPassword)}
className="absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground focus:outline-none disabled:cursor-not-allowed disabled:opacity-50"
disabled={props.disabled}
aria-label={showPassword ? "Hide password" : "Show password"}
>
{showPassword ? (
<EyeOff className="h-4 w-4" />
) : (
<Eye className="h-4 w-4" />
)}
</button>
{showToggle && (
<button
type="button"
onClick={() => setShowPassword(!showPassword)}
className="absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground focus:outline-none disabled:cursor-not-allowed disabled:opacity-50"
disabled={props.disabled}
aria-label={showPassword ? "Hide password" : "Show password"}
>
{showPassword ? (
<EyeOff className="h-4 w-4" />
) : (
<Eye className="h-4 w-4" />
)}
</button>
)}
</div>
)
}
+19 -1
View File
@@ -32,7 +32,25 @@ export interface NsiteProvider extends BaseDeployProvider {
blossomServers: string[];
}
export type DeployProvider = ShakespeareDeployProvider | NetlifyProvider | VercelProvider | NsiteProvider;
export interface CloudflareProvider extends BaseDeployProvider {
type: 'cloudflare';
apiKey: string;
accountId: string;
baseURL?: string;
baseDomain?: string;
proxy?: boolean;
}
export interface DenoDeployProvider extends BaseDeployProvider {
type: 'deno';
apiKey: string;
organizationId: string;
baseURL?: string;
baseDomain?: string;
proxy?: boolean;
}
export type DeployProvider = ShakespeareDeployProvider | NetlifyProvider | VercelProvider | NsiteProvider | CloudflareProvider | DenoDeployProvider;
export interface DeploySettings {
providers: DeployProvider[];
+15 -1
View File
@@ -31,7 +31,21 @@ export interface VercelProjectConfig {
};
}
export type ProjectProviderConfig = ShakespeareProjectConfig | NsiteProjectConfig | NetlifyProjectConfig | VercelProjectConfig;
export interface CloudflareProjectConfig {
type: 'cloudflare';
data: {
projectName?: string;
};
}
export interface DenoDeployProjectConfig {
type: 'deno';
data: {
projectName?: string;
};
}
export type ProjectProviderConfig = ShakespeareProjectConfig | NsiteProjectConfig | NetlifyProjectConfig | VercelProjectConfig | CloudflareProjectConfig | DenoDeployProjectConfig;
export interface ProjectDeploySettings {
providers: Record<string, ProjectProviderConfig>;
+7
View File
@@ -228,6 +228,13 @@ describe('configUtils', () => {
name: 'Shakespeare',
type: 'shakespeare',
},
{
id: 'provider-4',
name: 'My Cloudflare',
type: 'cloudflare',
apiKey: 'cloudflare-token-789',
accountId: 'account-123',
},
],
};
+18
View File
@@ -106,11 +106,29 @@ const nsiteProviderSchema = baseDeployProviderSchema.extend({
blossomServers: z.array(z.string()),
});
const cloudflareProviderSchema = baseDeployProviderSchema.extend({
type: z.literal('cloudflare'),
apiKey: z.string(),
accountId: z.string(),
baseURL: z.string().optional(),
baseDomain: z.string().optional(),
});
const denoDeployProviderSchema = baseDeployProviderSchema.extend({
type: z.literal('deno'),
apiKey: z.string(),
organizationId: z.string(),
baseURL: z.string().optional(),
baseDomain: z.string().optional(),
});
const deployProviderSchema: z.ZodType<DeployProvider> = z.discriminatedUnion('type', [
shakespeareDeployProviderSchema,
netlifyProviderSchema,
vercelProviderSchema,
nsiteProviderSchema,
cloudflareProviderSchema,
denoDeployProviderSchema,
]);
const deploySettingsSchema = z.object({
+406
View File
@@ -0,0 +1,406 @@
import type { JSRuntimeFS } from '../JSRuntime';
import type { DeployAdapter, DeployOptions, DeployResult, CloudflareDeployConfig } from './types';
import { proxyUrl } from '../proxyUrl';
interface AssetManifest {
[path: string]: { hash: string; size: number };
}
interface InitializeAssetsResponse {
buckets: string[][];
jwt: string;
}
interface UploadResponse {
jwt?: string;
}
interface WorkerScript {
id: string;
etag: string;
handlers: string[];
modified_on: string;
created_on: string;
has_assets: boolean;
}
interface FileInfo {
hash: string;
content: Uint8Array;
size: number;
contentType: string;
}
/**
* Cloudflare Workers Deploy Adapter
* Uses Cloudflare Workers API with static assets support
*
* Implements the Workers Assets upload workflow:
* 1. Build asset manifest with file hashes
* 2. Initialize upload session to get buckets of files to upload
* 3. Upload files in buckets using FormData with base64 content
* 4. Deploy worker with assets JWT
*/
export class CloudflareAdapter implements DeployAdapter {
private fs: JSRuntimeFS;
private apiKey: string;
private accountId: string;
private baseURL: string;
private baseDomain: string;
private projectName?: string;
private corsProxy?: string;
constructor(config: CloudflareDeployConfig) {
this.fs = config.fs;
this.apiKey = config.apiKey;
this.accountId = config.accountId;
this.baseURL = config.baseURL || 'https://api.cloudflare.com/client/v4';
this.baseDomain = config.baseDomain || 'workers.dev';
this.projectName = config.projectName;
this.corsProxy = config.corsProxy;
}
async deploy(options: DeployOptions): Promise<DeployResult> {
const { projectId, projectPath } = options;
// Check if dist directory exists and contains index.html
const distPath = `${projectPath}/dist`;
try {
await this.fs.readFile(`${distPath}/index.html`, 'utf8');
} catch {
throw new Error('No index.html found in dist directory. Please build the project first.');
}
const scriptName = this.projectName || projectId;
// Step 1: Collect all files and build manifest
const files = new Map<string, FileInfo>();
await this.collectFiles(distPath, '', files);
const manifest: AssetManifest = {};
for (const [filePath, fileInfo] of files) {
// Normalize path with leading slash
const normalizedPath = '/' + filePath.replace(/\\/g, '/');
manifest[normalizedPath] = {
hash: fileInfo.hash,
size: fileInfo.size,
};
}
// Step 2: Initialize upload session
const initResponse = await this.initializeUploadSession(scriptName, manifest);
// Step 3: Upload files in buckets (in parallel for speed)
let completionJwt = initResponse.jwt;
if (initResponse.buckets.flat().length > 0) {
// Create lookup from hash to file info
const hashToFile = new Map<string, { path: string; info: FileInfo }>();
for (const [filePath, fileInfo] of files) {
hashToFile.set(fileInfo.hash, { path: filePath, info: fileInfo });
}
// Upload all buckets in parallel
const uploadResults = await Promise.all(
initResponse.buckets.map((bucket) =>
this.uploadBucket(initResponse.jwt, bucket, hashToFile)
)
);
// Get the completion JWT from the last result that has one
const lastJwtResult = [...uploadResults].reverse().find((r) => r.jwt);
if (lastJwtResult?.jwt) {
completionJwt = lastJwtResult.jwt;
}
}
// Step 4: Deploy the worker with assets
const deployment = await this.deployWorker(scriptName, completionJwt);
// Step 5: Enable the workers.dev subdomain for this script
await this.enableWorkersDevSubdomain(scriptName);
// Step 6: Get the account's workers subdomain
const subdomain = await this.getWorkersSubdomain();
// Construct the URL using the configurable base domain
const workerUrl = `https://${scriptName}.${subdomain}.${this.baseDomain}`;
return {
url: workerUrl,
metadata: {
scriptId: deployment.id,
scriptName: scriptName,
provider: 'cloudflare-workers',
hasAssets: deployment.has_assets,
modifiedOn: deployment.modified_on,
},
};
}
private async getWorkersSubdomain(): Promise<string> {
const url = `${this.baseURL}/accounts/${this.accountId}/workers/subdomain`;
const targetUrl = this.corsProxy ? proxyUrl(this.corsProxy, url) : url;
const response = await fetch(targetUrl, {
method: 'GET',
headers: {
'Authorization': `Bearer ${this.apiKey}`,
},
});
if (!response.ok) {
const errorText = await response.text().catch(() => 'Unknown error');
throw new Error(`Failed to get workers subdomain: ${response.status} ${response.statusText}. ${errorText}`);
}
const data = await response.json();
return data.result.subdomain;
}
private async enableWorkersDevSubdomain(scriptName: string): Promise<void> {
const url = `${this.baseURL}/accounts/${this.accountId}/workers/scripts/${scriptName}/subdomain`;
const targetUrl = this.corsProxy ? proxyUrl(this.corsProxy, url) : url;
const response = await fetch(targetUrl, {
method: 'POST',
headers: {
'Authorization': `Bearer ${this.apiKey}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
enabled: true,
previews_enabled: true,
}),
});
if (!response.ok) {
const errorText = await response.text().catch(() => 'Unknown error');
throw new Error(`Failed to enable workers.dev subdomain: ${response.status} ${response.statusText}. ${errorText}`);
}
}
private async initializeUploadSession(
scriptName: string,
manifest: AssetManifest
): Promise<InitializeAssetsResponse> {
const url = `${this.baseURL}/accounts/${this.accountId}/workers/scripts/${scriptName}/assets-upload-session`;
const targetUrl = this.corsProxy ? proxyUrl(this.corsProxy, url) : url;
const response = await fetch(targetUrl, {
method: 'POST',
headers: {
'Authorization': `Bearer ${this.apiKey}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({ manifest }),
});
if (!response.ok) {
const errorText = await response.text().catch(() => 'Unknown error');
throw new Error(`Failed to initialize upload session: ${response.status} ${response.statusText}. ${errorText}`);
}
const data = await response.json();
return data.result;
}
private async uploadBucket(
jwt: string,
bucket: string[],
hashToFile: Map<string, { path: string; info: FileInfo }>
): Promise<UploadResponse> {
const url = `${this.baseURL}/accounts/${this.accountId}/workers/assets/upload?base64=true`;
const targetUrl = this.corsProxy ? proxyUrl(this.corsProxy, url) : url;
const formData = new FormData();
for (const fileHash of bucket) {
const fileData = hashToFile.get(fileHash);
if (!fileData) {
throw new Error(`File with hash ${fileHash} not found in manifest`);
}
// Convert content to base64
const base64Content = this.uint8ArrayToBase64(fileData.info.content);
// Use content type or "application/null" to signal no content-type header
const contentType = fileData.info.contentType || 'application/null';
// Create a File/Blob with the base64 content
const blob = new Blob([base64Content], { type: contentType });
formData.append(fileHash, blob, fileHash);
}
const response = await fetch(targetUrl, {
method: 'POST',
headers: {
'Authorization': `Bearer ${jwt}`,
},
body: formData,
});
if (!response.ok) {
const errorText = await response.text().catch(() => 'Unknown error');
throw new Error(`Failed to upload assets: ${response.status} ${response.statusText}. ${errorText}`);
}
const data = await response.json();
return data.result || {};
}
private async deployWorker(scriptName: string, assetsJwt: string): Promise<WorkerScript> {
const url = `${this.baseURL}/accounts/${this.accountId}/workers/scripts/${scriptName}`;
const targetUrl = this.corsProxy ? proxyUrl(this.corsProxy, url) : url;
// Create a minimal worker script that serves static assets
// This is an assets-only worker - Cloudflare will automatically serve the uploaded assets
const workerScript = `
export default {
async fetch(request, env) {
// This worker only serves static assets
// The assets are automatically served by Cloudflare's asset handler
return new Response('Not Found', { status: 404 });
}
};
`;
const formData = new FormData();
// Add the worker script as the main module
const scriptBlob = new Blob([workerScript], { type: 'application/javascript+module' });
formData.append('worker.js', scriptBlob, 'worker.js');
// Add metadata with assets configuration
const metadata = {
main_module: 'worker.js',
compatibility_date: new Date().toISOString().split('T')[0],
assets: {
jwt: assetsJwt,
config: {
html_handling: 'auto-trailing-slash',
not_found_handling: 'single-page-application',
},
},
};
formData.append('metadata', new Blob([JSON.stringify(metadata)], { type: 'application/json' }));
const response = await fetch(targetUrl, {
method: 'PUT',
headers: {
'Authorization': `Bearer ${this.apiKey}`,
},
body: formData,
});
if (!response.ok) {
const errorText = await response.text().catch(() => 'Unknown error');
throw new Error(`Failed to deploy worker: ${response.status} ${response.statusText}. ${errorText}`);
}
const data = await response.json();
return data.result;
}
private async collectFiles(
dirPath: string,
relativePath: string,
files: Map<string, FileInfo>
): Promise<void> {
try {
const entries = await this.fs.readdir(dirPath, { withFileTypes: true });
for (const entry of entries) {
const fullPath = `${dirPath}/${entry.name}`;
const entryRelativePath = relativePath ? `${relativePath}/${entry.name}` : entry.name;
if (entry.isDirectory()) {
await this.collectFiles(fullPath, entryRelativePath, files);
} else if (entry.isFile()) {
try {
const fileContent = await this.fs.readFile(fullPath);
// Convert to Uint8Array
let content: Uint8Array;
if (typeof fileContent === 'string') {
content = new TextEncoder().encode(fileContent);
} else {
content = fileContent;
}
// Calculate hash (same algorithm as Wrangler uses)
const hash = await this.calculateHash(content);
// Determine content type
const contentType = this.getContentType(entry.name);
files.set(entryRelativePath, {
hash,
content,
size: content.length,
contentType,
});
} catch (error) {
console.warn(`Failed to read file ${fullPath}:`, error);
}
}
}
} catch (error) {
console.warn(`Failed to read directory ${dirPath}:`, error);
}
}
private async calculateHash(content: Uint8Array): Promise<string> {
// Use xxHash algorithm like Wrangler does, but fall back to SHA-256 for browser compatibility
const hashBuffer = await crypto.subtle.digest('SHA-256', content);
const hashArray = Array.from(new Uint8Array(hashBuffer));
// Take first 16 bytes (32 hex chars) to match Wrangler's hash length
const hashHex = hashArray.slice(0, 16).map(b => b.toString(16).padStart(2, '0')).join('');
return hashHex;
}
private uint8ArrayToBase64(bytes: Uint8Array): string {
let binary = '';
for (let i = 0; i < bytes.length; i++) {
binary += String.fromCharCode(bytes[i]);
}
return btoa(binary);
}
private getContentType(filename: string): string {
const ext = filename.split('.').pop()?.toLowerCase() || '';
const mimeTypes: Record<string, string> = {
'html': 'text/html',
'htm': 'text/html',
'css': 'text/css',
'js': 'application/javascript',
'mjs': 'application/javascript',
'json': 'application/json',
'png': 'image/png',
'jpg': 'image/jpeg',
'jpeg': 'image/jpeg',
'gif': 'image/gif',
'svg': 'image/svg+xml',
'ico': 'image/x-icon',
'webp': 'image/webp',
'avif': 'image/avif',
'woff': 'font/woff',
'woff2': 'font/woff2',
'ttf': 'font/ttf',
'eot': 'application/vnd.ms-fontobject',
'otf': 'font/otf',
'txt': 'text/plain',
'xml': 'application/xml',
'pdf': 'application/pdf',
'zip': 'application/zip',
'mp4': 'video/mp4',
'webm': 'video/webm',
'mp3': 'audio/mpeg',
'wav': 'audio/wav',
'ogg': 'audio/ogg',
'wasm': 'application/wasm',
};
return mimeTypes[ext] || 'application/octet-stream';
}
}
+287
View File
@@ -0,0 +1,287 @@
import type { JSRuntimeFS } from '../JSRuntime';
import type { DeployAdapter, DeployOptions, DeployResult, DenoDeployConfig } from './types';
import { proxyUrl } from '../proxyUrl';
interface Project {
id: string;
name: string;
createdAt: string;
updatedAt: string;
}
interface Deployment {
id: string;
projectId: string;
status: string;
domains: string[];
createdAt: string;
updatedAt: string;
}
/**
* Deno Deploy Adapter
* Uses Deno Deploy API to deploy static sites
*
* Implements the Deno Deploy workflow:
* 1. Create or find existing project
* 2. Build asset manifest with file contents
* 3. Create deployment with assets
* 4. Attach domain to deployment
*/
export class DenoDeployAdapter implements DeployAdapter {
private fs: JSRuntimeFS;
private apiKey: string;
private organizationId: string;
private baseURL: string;
private baseDomain: string;
private projectName?: string;
private corsProxy?: string;
constructor(config: DenoDeployConfig) {
this.fs = config.fs;
this.apiKey = config.apiKey;
this.organizationId = config.organizationId;
this.baseURL = config.baseURL || 'https://api.deno.com/v1';
this.baseDomain = config.baseDomain || 'deno.dev';
this.projectName = config.projectName;
this.corsProxy = config.corsProxy;
}
async deploy(options: DeployOptions): Promise<DeployResult> {
const { projectId, projectPath } = options;
// Check if dist directory exists and contains index.html
const distPath = `${projectPath}/dist`;
try {
await this.fs.readFile(`${distPath}/index.html`, 'utf8');
} catch {
throw new Error('No index.html found in dist directory. Please build the project first.');
}
const projectName = this.projectName || projectId;
// Step 1: Get or create project
const project = await this.getOrCreateProject(projectName);
// Step 2: Collect all files and build assets
const assets: Record<string, { kind: string; content: string; encoding: string }> = {};
await this.collectFiles(distPath, '', assets);
// Step 3: Create deployment with assets and domain
const domain = `${project.name}.${this.baseDomain}`;
const deployment = await this.createDeployment(project.id, assets, domain);
return {
url: `https://${domain}`,
metadata: {
deploymentId: deployment.id,
projectId: project.id,
projectName: project.name,
provider: 'deno-deploy',
status: deployment.status,
},
};
}
private async getOrCreateProject(projectName: string): Promise<Project> {
// First, try to find existing project
const existingProject = await this.findProject(projectName);
if (existingProject) {
return existingProject;
}
// Create new project
return this.createProject(projectName);
}
private async findProject(projectName: string): Promise<Project | null> {
const url = `${this.baseURL}/organizations/${this.organizationId}/projects?q=${encodeURIComponent(projectName)}`;
const targetUrl = this.corsProxy ? proxyUrl(this.corsProxy, url) : url;
const response = await fetch(targetUrl, {
method: 'GET',
headers: {
'Authorization': `Bearer ${this.apiKey}`,
},
});
if (!response.ok) {
// If we can't list projects, just return null and try to create
return null;
}
const projects: Project[] = await response.json();
return projects.find(p => p.name === projectName) || null;
}
private async createProject(projectName: string): Promise<Project> {
const url = `${this.baseURL}/organizations/${this.organizationId}/projects`;
const targetUrl = this.corsProxy ? proxyUrl(this.corsProxy, url) : url;
const response = await fetch(targetUrl, {
method: 'POST',
headers: {
'Authorization': `Bearer ${this.apiKey}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
name: projectName,
}),
});
if (!response.ok) {
const errorText = await response.text().catch(() => 'Unknown error');
throw new Error(`Failed to create project: ${response.status} ${response.statusText}. ${errorText}`);
}
return response.json();
}
private async createDeployment(
projectId: string,
assets: Record<string, { kind: string; content: string; encoding: string }>,
domain: string
): Promise<Deployment> {
const url = `${this.baseURL}/projects/${projectId}/deployments`;
const targetUrl = this.corsProxy ? proxyUrl(this.corsProxy, url) : url;
// Create a minimal server script that serves static files
// For static sites, we use a simple file server entry point
const entryPointUrl = 'main.ts';
// Add the entry point script that serves static files
const serverScript = `
import { serveDir } from "jsr:@std/http/file-server";
Deno.serve((req) => {
return serveDir(req, {
fsRoot: ".",
showIndex: true,
enableCors: true,
});
});
`;
// Add the server script to assets
assets['main.ts'] = {
kind: 'file',
content: serverScript,
encoding: 'utf-8',
};
const response = await fetch(targetUrl, {
method: 'POST',
headers: {
'Authorization': `Bearer ${this.apiKey}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
entryPointUrl,
assets,
importMapUrl: null,
lockFileUrl: null,
compilerOptions: null,
envVars: {},
// Attach domain during deployment creation instead of separately
domains: [domain],
}),
});
if (!response.ok) {
const errorText = await response.text().catch(() => 'Unknown error');
throw new Error(`Failed to create deployment: ${response.status} ${response.statusText}. ${errorText}`);
}
return response.json();
}
private async collectFiles(
dirPath: string,
relativePath: string,
assets: Record<string, { kind: string; content: string; encoding: string }>
): Promise<void> {
try {
const entries = await this.fs.readdir(dirPath, { withFileTypes: true });
for (const entry of entries) {
const fullPath = `${dirPath}/${entry.name}`;
const entryRelativePath = relativePath ? `${relativePath}/${entry.name}` : entry.name;
if (entry.isDirectory()) {
await this.collectFiles(fullPath, entryRelativePath, assets);
} else if (entry.isFile()) {
try {
const fileContent = await this.fs.readFile(fullPath);
// Determine if file is text or binary based on extension
const isText = this.isTextFile(entry.name);
let content: string;
let encoding: 'utf-8' | 'base64';
if (isText) {
if (typeof fileContent === 'string') {
content = fileContent;
} else {
content = new TextDecoder().decode(fileContent);
}
encoding = 'utf-8';
} else {
// Binary file - encode as base64
let bytes: Uint8Array;
if (typeof fileContent === 'string') {
bytes = new TextEncoder().encode(fileContent);
} else {
bytes = fileContent;
}
content = this.uint8ArrayToBase64(bytes);
encoding = 'base64';
}
assets[entryRelativePath] = {
kind: 'file',
content,
encoding,
};
} catch (error) {
console.warn(`Failed to read file ${fullPath}:`, error);
}
}
}
} catch (error) {
console.warn(`Failed to read directory ${dirPath}:`, error);
}
}
private isTextFile(filename: string): boolean {
const textExtensions = [
'html', 'htm', 'css', 'js', 'mjs', 'cjs', 'ts', 'tsx', 'jsx',
'json', 'xml', 'svg', 'txt', 'md', 'yaml', 'yml', 'toml',
'sh', 'bash', 'zsh', 'fish', 'bat', 'cmd', 'ps1',
'py', 'rb', 'php', 'java', 'c', 'cpp', 'h', 'hpp',
'rs', 'go', 'swift', 'kt', 'scala', 'clj', 'ex', 'exs',
'vue', 'svelte', 'astro', 'njk', 'ejs', 'pug', 'hbs',
'graphql', 'gql', 'sql', 'csv', 'tsv', 'log', 'ini', 'cfg',
'env', 'gitignore', 'dockerignore', 'editorconfig',
'prettierrc', 'eslintrc', 'babelrc', 'npmrc',
'map', // source maps
];
const ext = filename.split('.').pop()?.toLowerCase() || '';
// Also check if filename itself is a known text file
const textFilenames = [
'dockerfile', 'makefile', 'gemfile', 'rakefile', 'procfile',
'license', 'readme', 'changelog', 'authors', 'contributors',
];
return textExtensions.includes(ext) || textFilenames.includes(filename.toLowerCase());
}
private uint8ArrayToBase64(bytes: Uint8Array): string {
let binary = '';
for (let i = 0; i < bytes.length; i++) {
binary += String.fromCharCode(bytes[i]);
}
return btoa(binary);
}
}
+2
View File
@@ -3,3 +3,5 @@ export * from './ShakespeareAdapter';
export * from './NetlifyAdapter';
export * from './VercelAdapter';
export * from './NsiteAdapter';
export * from './CloudflareAdapter';
export * from './DenoDeployAdapter';
+20
View File
@@ -54,3 +54,23 @@ export interface NsiteDeployConfig {
relayUrls: string[];
blossomServers: string[];
}
export interface CloudflareDeployConfig {
fs: JSRuntimeFS;
apiKey: string;
accountId: string;
baseURL?: string;
baseDomain?: string;
projectName?: string;
corsProxy?: string;
}
export interface DenoDeployConfig {
fs: JSRuntimeFS;
apiKey: string;
organizationId: string;
baseURL?: string;
baseDomain?: string;
projectName?: string;
corsProxy?: string;
}
+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.`;
+9 -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",
@@ -536,5 +542,7 @@
"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"
"globalChatSystemPromptDescription": "Custom system prompt for the floating chat assistant",
"building": "Building",
"chatting": "Chatting"
}
+3 -1
View File
@@ -443,5 +443,7 @@
"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"
"globalChatSystemPromptDescription": "Jagorar tsarin da aka keɓe don mataimakin tattaunawa mai yawo",
"building": "Ginawa",
"chatting": "Tattaunawa"
}
+3 -1
View File
@@ -440,5 +440,7 @@
"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"
"globalChatSystemPromptDescription": "Usoro nke gị maka onye enyemaka nkata na-epupụta",
"building": "Nrụpụta",
"chatting": "Nkwurịta"
}
+3 -1
View File
@@ -452,5 +452,7 @@
"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"
"globalChatSystemPromptDescription": "Prompt do sistema personalizado para o assistente de chat flutuante",
"building": "Construindo",
"chatting": "Conversando"
}
+3 -1
View File
@@ -440,5 +440,7 @@
"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ọ"
"globalChatSystemPromptDescription": "Itọsọna eto aṣa fun oluranlọwọ ibanisọrọ ti o n lọ",
"building": "Kíkọ́",
"chatting": "Sísọ̀rọ̀"
}
+3 -1
View File
@@ -452,5 +452,7 @@
"globalChatEnabled": "浮动聊天按钮",
"globalChatEnabledDescription": "显示浮动聊天按钮以便快速AI对话",
"globalChatSystemPrompt": "聊天系统提示",
"globalChatSystemPromptDescription": "浮动聊天助手的自定义系统提示"
"globalChatSystemPromptDescription": "浮动聊天助手的自定义系统提示",
"building": "构建",
"chatting": "聊天"
}
+107 -41
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 } 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, {
@@ -420,24 +437,13 @@ export function AISettings() {
return (
<Card key={preset.id}>
<CardContent className="p-4 space-y-3">
<div className="flex items-center justify-between">
<div className="flex items-center gap-2">
<ExternalFavicon
url={preset.baseURL}
size={16}
fallback={<Bot size={16} />}
/>
<h5 className="font-medium">{preset.name}</h5>
</div>
{(preset.apiKeysURL && preset.id !== "routstr") && (
<button
type="button"
className="text-xs text-muted-foreground underline hover:text-foreground"
onClick={() => window.open(preset.apiKeysURL, '_blank')}
>
{t('getApiKey')}
</button>
)}
<div className="flex items-center gap-2">
<ExternalFavicon
url={preset.baseURL}
size={16}
fallback={<Bot size={16} />}
/>
<h5 className="font-medium">{preset.name}</h5>
</div>
{showNostrLoginRequired ? (
@@ -458,22 +464,34 @@ export function AISettings() {
<div className="space-y-2">
<div className="flex gap-2">
{!preset.nostr && (
<PasswordInput
placeholder={preset.id === "routstr" ? t('enterCashuToken') : t('enterApiKey')}
className="flex-1"
value={presetApiKeys[preset.id] || ''}
onChange={(e) => setPresetApiKeys(prev => ({
...prev,
[preset.id]: e.target.value,
}))}
onKeyDown={(e) => {
if (e.key === 'Enter' &&
presetApiKeys[preset.id]?.trim() &&
presetTermsAgreements[preset.id]) {
handleAddPresetProvider(preset);
}
}}
/>
<div className="relative flex-1">
<PasswordInput
placeholder={preset.id === "routstr" ? t('enterCashuToken') : t('enterApiKey')}
value={presetApiKeys[preset.id] || ''}
onChange={(e) => setPresetApiKeys(prev => ({
...prev,
[preset.id]: e.target.value,
}))}
onKeyDown={(e) => {
if (e.key === 'Enter' &&
presetApiKeys[preset.id]?.trim() &&
presetTermsAgreements[preset.id]) {
handleAddPresetProvider(preset);
}
}}
showToggle={!!presetApiKeys[preset.id]}
/>
{preset.apiKeysURL && !presetApiKeys[preset.id] && (
<button
type="button"
className="absolute right-3 top-1/2 -translate-y-1/2 inline-flex items-center gap-1 px-2 py-1 text-xs font-medium text-muted-foreground hover:text-foreground transition-colors rounded-md hover:bg-muted"
onClick={() => window.open(preset.apiKeysURL, '_blank')}
>
Get Key
<ExternalLink className="h-3 w-3" />
</button>
)}
</div>
)}
<Button
onClick={() => handleAddPresetProvider(preset)}
@@ -684,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;
@@ -730,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>
+338 -63
View File
@@ -1,6 +1,6 @@
import { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Rocket, ArrowLeft, Trash2, Check, GripVertical, ChevronDown, Plus } from 'lucide-react';
import { Rocket, ArrowLeft, Trash2, Check, GripVertical, ChevronDown, Plus, ExternalLink } from 'lucide-react';
import { Checkbox } from '@/components/ui/checkbox';
import {
DropdownMenu,
@@ -46,12 +46,16 @@ import { normalizeUrl } from '@/lib/faviconUrl';
interface PresetProvider {
id: string;
type: 'shakespeare' | 'netlify' | 'vercel' | 'nsite';
type: 'shakespeare' | 'netlify' | 'vercel' | 'nsite' | 'cloudflare' | 'deno';
name: string;
description: string;
requiresNostr?: boolean;
apiKeyLabel?: string;
apiKeyURL?: string;
accountIdLabel?: string;
accountIdURL?: string;
organizationIdLabel?: string;
organizationIdURL?: string;
proxy?: boolean;
}
@@ -187,6 +191,32 @@ function SortableProviderItem({ provider, index, preset, onRemove, onUpdate, sho
</>
) : (
<>
{provider.type === 'cloudflare' && (
<div className="grid gap-2">
<Label htmlFor={`provider-${index}-accountId`}>
{preset?.accountIdLabel || 'Account ID'} <span className="text-destructive">*</span>
</Label>
<Input
id={`provider-${index}-accountId`}
placeholder="Enter Account ID"
value={provider.accountId}
onChange={(e) => onUpdate(index, { ...provider, accountId: e.target.value })}
/>
</div>
)}
{provider.type === 'deno' && (
<div className="grid gap-2">
<Label htmlFor={`provider-${index}-organizationId`}>
{preset?.organizationIdLabel || 'Organization ID'} <span className="text-destructive">*</span>
</Label>
<Input
id={`provider-${index}-organizationId`}
placeholder="Enter Organization ID"
value={provider.organizationId}
onChange={(e) => onUpdate(index, { ...provider, organizationId: e.target.value })}
/>
</div>
)}
<div className="grid gap-2">
<Label htmlFor={`provider-${index}-apiKey`}>
{preset?.apiKeyLabel || t('apiKey')} <span className="text-destructive">*</span>
@@ -200,6 +230,10 @@ function SortableProviderItem({ provider, index, preset, onRemove, onUpdate, sho
onUpdate(index, { ...provider, apiKey: e.target.value });
} else if (provider.type === 'vercel') {
onUpdate(index, { ...provider, apiKey: e.target.value });
} else if (provider.type === 'cloudflare') {
onUpdate(index, { ...provider, apiKey: e.target.value });
} else if (provider.type === 'deno') {
onUpdate(index, { ...provider, apiKey: e.target.value });
}
}}
/>
@@ -210,17 +244,45 @@ function SortableProviderItem({ provider, index, preset, onRemove, onUpdate, sho
</Label>
<Input
id={`provider-${index}-baseURL`}
placeholder={provider.type === 'netlify' ? 'https://api.netlify.com/api/v1' : 'https://api.vercel.com'}
placeholder={
provider.type === 'netlify' ? 'https://api.netlify.com/api/v1' :
provider.type === 'vercel' ? 'https://api.vercel.com' :
provider.type === 'cloudflare' ? 'https://api.cloudflare.com/client/v4' :
provider.type === 'deno' ? 'https://api.deno.com/v1' :
'Base URL'
}
value={provider.baseURL || ''}
onChange={(e) => {
if (provider.type === 'netlify') {
onUpdate(index, { ...provider, baseURL: e.target.value });
} else if (provider.type === 'vercel') {
onUpdate(index, { ...provider, baseURL: e.target.value });
} else if (provider.type === 'cloudflare') {
onUpdate(index, { ...provider, baseURL: e.target.value });
} else if (provider.type === 'deno') {
onUpdate(index, { ...provider, baseURL: e.target.value });
}
}}
/>
</div>
{(provider.type === 'cloudflare' || provider.type === 'deno') && (
<div className="grid gap-2">
<Label htmlFor={`provider-${index}-baseDomain`}>
Base Domain (Optional)
</Label>
<Input
id={`provider-${index}-baseDomain`}
placeholder={provider.type === 'cloudflare' ? 'workers.dev' : 'deno.dev'}
value={provider.baseDomain || ''}
onChange={(e) => onUpdate(index, { ...provider, baseDomain: e.target.value })}
/>
<p className="text-xs text-muted-foreground">
{provider.type === 'cloudflare'
? 'The domain suffix for deployed workers (e.g., workers.dev)'
: 'The domain suffix for deployed projects (e.g., deno.dev)'}
</p>
</div>
)}
<div className="flex items-center space-x-2">
<Checkbox
id={`provider-${index}-proxy`}
@@ -282,6 +344,28 @@ const PRESET_PROVIDERS: PresetProvider[] = [
apiKeyURL: 'https://vercel.com/account/tokens',
proxy: true,
},
{
id: 'cloudflare',
type: 'cloudflare',
name: 'Cloudflare',
description: 'Deploy to Cloudflare Workers',
apiKeyLabel: 'API Token',
apiKeyURL: 'https://dash.cloudflare.com/profile/api-tokens',
accountIdLabel: 'Account ID',
accountIdURL: 'https://developers.cloudflare.com/fundamentals/account/find-account-and-zone-ids/',
proxy: true,
},
{
id: 'deno',
type: 'deno',
name: 'Deno Deploy',
description: 'Deploy to Deno Deploy',
apiKeyLabel: 'Access Token',
apiKeyURL: 'https://dash.deno.com/account#access-tokens',
organizationIdLabel: 'Organization ID',
organizationIdURL: 'https://dash.deno.com/orgs',
proxy: true,
},
];
// Helper function to generate custom provider ID
@@ -314,6 +398,20 @@ function getProviderUrl(provider: DeployProvider | PresetProvider): string | nul
}
return 'https://vercel.com';
case 'cloudflare':
// For Cloudflare providers, check for custom baseURL first, then use default
if ('baseURL' in provider && provider.baseURL) {
return provider.baseURL;
}
return 'https://cloudflare.com';
case 'deno':
// For Deno Deploy providers, check for custom baseURL first, then use default
if ('baseURL' in provider && provider.baseURL) {
return provider.baseURL;
}
return 'https://deno.com';
case 'nsite':
// nsite uses Rocket icon fallback
return null;
@@ -338,10 +436,13 @@ export function DeploySettings() {
const [forceManualEntry, setForceManualEntry] = useState<Record<string, boolean>>({});
// Custom provider form state
const [customProviderType, setCustomProviderType] = useState<'shakespeare' | 'netlify' | 'vercel' | 'nsite' | ''>('');
const [customProviderType, setCustomProviderType] = useState<'shakespeare' | 'netlify' | 'vercel' | 'nsite' | 'cloudflare' | 'deno' | ''>('');
const [customName, setCustomName] = useState('');
const [customApiKey, setCustomApiKey] = useState('');
const [customAccountId, setCustomAccountId] = useState('');
const [customOrganizationId, setCustomOrganizationId] = useState('');
const [customBaseURL, setCustomBaseURL] = useState('');
const [customBaseDomain, setCustomBaseDomain] = useState('');
const [customHost, setCustomHost] = useState('');
const [customProxy, setCustomProxy] = useState(false);
const [customGateway, setCustomGateway] = useState('');
@@ -416,7 +517,7 @@ export function DeploySettings() {
apiKey: apiKey.trim(),
...(preset.proxy && { proxy: true }),
};
} else {
} else if (preset.type === 'vercel') {
newProvider = {
id: preset.id, // Use preset ID for presets
name: preset.name,
@@ -424,6 +525,34 @@ export function DeploySettings() {
apiKey: apiKey.trim(),
...(preset.proxy && { proxy: true }),
};
} else if (preset.type === 'cloudflare') {
const accountId = presetApiKeys[`${preset.id}-accountId`];
if (!accountId?.trim()) {
return;
}
newProvider = {
id: preset.id, // Use preset ID for presets
name: preset.name,
type: 'cloudflare',
apiKey: apiKey.trim(),
accountId: accountId.trim(),
...(preset.proxy && { proxy: true }),
};
} else if (preset.type === 'deno') {
const organizationId = presetApiKeys[`${preset.id}-organizationId`];
if (!organizationId?.trim()) {
return;
}
newProvider = {
id: preset.id, // Use preset ID for presets
name: preset.name,
type: 'deno',
apiKey: apiKey.trim(),
organizationId: organizationId.trim(),
...(preset.proxy && { proxy: true }),
};
} else {
return; // Unknown type
}
setProviders([...settings.providers, newProvider]);
@@ -472,7 +601,7 @@ export function DeploySettings() {
...(customBaseURL?.trim() && { baseURL: customBaseURL.trim() }),
...(customProxy && { proxy: true }),
};
} else {
} else if (customProviderType === 'vercel') {
if (!customApiKey.trim()) return;
newProvider = {
id: generateCustomProviderId(customProviderType), // Generate custom ID
@@ -482,6 +611,32 @@ export function DeploySettings() {
...(customBaseURL?.trim() && { baseURL: customBaseURL.trim() }),
...(customProxy && { proxy: true }),
};
} else if (customProviderType === 'cloudflare') {
if (!customApiKey.trim() || !customAccountId.trim()) return;
newProvider = {
id: generateCustomProviderId(customProviderType), // Generate custom ID
name: customName.trim(),
type: 'cloudflare',
apiKey: customApiKey.trim(),
accountId: customAccountId.trim(),
...(customBaseURL?.trim() && { baseURL: customBaseURL.trim() }),
...(customBaseDomain?.trim() && { baseDomain: customBaseDomain.trim() }),
...(customProxy && { proxy: true }),
};
} else if (customProviderType === 'deno') {
if (!customApiKey.trim() || !customOrganizationId.trim()) return;
newProvider = {
id: generateCustomProviderId(customProviderType), // Generate custom ID
name: customName.trim(),
type: 'deno',
apiKey: customApiKey.trim(),
organizationId: customOrganizationId.trim(),
...(customBaseURL?.trim() && { baseURL: customBaseURL.trim() }),
...(customBaseDomain?.trim() && { baseDomain: customBaseDomain.trim() }),
...(customProxy && { proxy: true }),
};
} else {
return; // Unknown type
}
setProviders([...settings.providers, newProvider]);
@@ -490,7 +645,10 @@ export function DeploySettings() {
setCustomProviderType('');
setCustomName('');
setCustomApiKey('');
setCustomAccountId('');
setCustomOrganizationId('');
setCustomBaseURL('');
setCustomBaseDomain('');
setCustomHost('');
setCustomProxy(false);
};
@@ -601,31 +759,20 @@ export function DeploySettings() {
return (
<Card key={preset.id}>
<CardContent className="p-4 space-y-3">
<div className="flex items-center justify-between">
<div className="flex items-center gap-2">
{(() => {
const url = getProviderUrl(preset);
return url ? (
<ExternalFavicon
url={url}
size={16}
fallback={<Rocket size={16} />}
/>
) : (
<Rocket size={16} />
);
})()}
<h5 className="font-medium">{preset.name}</h5>
</div>
{preset.apiKeyURL && !isOAuthConfigured && (
<button
type="button"
className="text-xs text-muted-foreground underline hover:text-foreground"
onClick={() => window.open(preset.apiKeyURL, '_blank')}
>
{t('getApiKey')}
</button>
)}
<div className="flex items-center gap-2">
{(() => {
const url = getProviderUrl(preset);
return url ? (
<ExternalFavicon
url={url}
size={16}
fallback={<Rocket size={16} />}
/>
) : (
<Rocket size={16} />
);
})()}
<h5 className="font-medium">{preset.name}</h5>
</div>
<p className="text-sm text-muted-foreground">{preset.description}</p>
@@ -703,34 +850,106 @@ export function DeploySettings() {
) : (
// Show manual token input
<div className="space-y-2">
<div className="flex gap-2">
{!preset.requiresNostr && preset.type !== 'nsite' && (
<PasswordInput
placeholder={preset.apiKeyLabel || t('enterApiKey')}
className="flex-1"
value={presetApiKeys[preset.id] || ''}
onChange={(e) => setPresetApiKeys(prev => ({
...prev,
[preset.id]: e.target.value,
}))}
onKeyDown={(e) => {
if (e.key === 'Enter' && presetApiKeys[preset.id]?.trim()) {
handleAddPresetProvider(preset);
}
}}
/>
)}
<Button
onClick={() => handleAddPresetProvider(preset)}
disabled={
(preset.requiresNostr && !isLoggedIntoNostr) ||
(!preset.requiresNostr && preset.type !== 'nsite' && !presetApiKeys[preset.id]?.trim())
}
className={(preset.requiresNostr || preset.type === 'nsite') ? "w-full" : "h-10 px-4 ml-auto"}
>
{t('add')}
</Button>
</div>
{!preset.requiresNostr && preset.type !== 'nsite' && (
<>
{preset.type === 'cloudflare' && (
<div className="relative">
<Input
placeholder={preset.accountIdLabel || 'Account ID'}
value={presetApiKeys[`${preset.id}-accountId`] || ''}
onChange={(e) => setPresetApiKeys(prev => ({
...prev,
[`${preset.id}-accountId`]: e.target.value,
}))}
onKeyDown={(e) => {
if (e.key === 'Enter' && presetApiKeys[preset.id]?.trim() &&
presetApiKeys[`${preset.id}-accountId`]?.trim()) {
handleAddPresetProvider(preset);
}
}}
/>
{preset.accountIdURL && !presetApiKeys[`${preset.id}-accountId`] && (
<button
type="button"
className="absolute right-3 top-1/2 -translate-y-1/2 inline-flex items-center gap-1 px-2 py-1 text-xs font-medium text-muted-foreground hover:text-foreground transition-colors rounded-md hover:bg-muted"
onClick={() => window.open(preset.accountIdURL, '_blank')}
>
Find ID
<ExternalLink className="h-3 w-3" />
</button>
)}
</div>
)}
{preset.type === 'deno' && (
<div className="relative">
<Input
placeholder={preset.organizationIdLabel || 'Organization ID'}
value={presetApiKeys[`${preset.id}-organizationId`] || ''}
onChange={(e) => setPresetApiKeys(prev => ({
...prev,
[`${preset.id}-organizationId`]: e.target.value,
}))}
onKeyDown={(e) => {
if (e.key === 'Enter' && presetApiKeys[preset.id]?.trim() &&
presetApiKeys[`${preset.id}-organizationId`]?.trim()) {
handleAddPresetProvider(preset);
}
}}
/>
{preset.organizationIdURL && !presetApiKeys[`${preset.id}-organizationId`] && (
<button
type="button"
className="absolute right-3 top-1/2 -translate-y-1/2 inline-flex items-center gap-1 px-2 py-1 text-xs font-medium text-muted-foreground hover:text-foreground transition-colors rounded-md hover:bg-muted"
onClick={() => window.open(preset.organizationIdURL, '_blank')}
>
Find ID
<ExternalLink className="h-3 w-3" />
</button>
)}
</div>
)}
<div className="relative">
<PasswordInput
placeholder={preset.apiKeyLabel || t('enterApiKey')}
value={presetApiKeys[preset.id] || ''}
onChange={(e) => setPresetApiKeys(prev => ({
...prev,
[preset.id]: e.target.value,
}))}
onKeyDown={(e) => {
if (e.key === 'Enter' && presetApiKeys[preset.id]?.trim() &&
(preset.type !== 'cloudflare' || presetApiKeys[`${preset.id}-accountId`]?.trim()) &&
(preset.type !== 'deno' || presetApiKeys[`${preset.id}-organizationId`]?.trim())) {
handleAddPresetProvider(preset);
}
}}
showToggle={!!presetApiKeys[preset.id]}
/>
{preset.apiKeyURL && !presetApiKeys[preset.id] && (
<button
type="button"
className="absolute right-3 top-1/2 -translate-y-1/2 inline-flex items-center gap-1 px-2 py-1 text-xs font-medium text-muted-foreground hover:text-foreground transition-colors rounded-md hover:bg-muted"
onClick={() => window.open(preset.apiKeyURL, '_blank')}
>
Get Key
<ExternalLink className="h-3 w-3" />
</button>
)}
</div>
</>
)}
<Button
onClick={() => handleAddPresetProvider(preset)}
disabled={
(preset.requiresNostr && !isLoggedIntoNostr) ||
(!preset.requiresNostr && preset.type !== 'nsite' && !presetApiKeys[preset.id]?.trim()) ||
(preset.type === 'cloudflare' && !presetApiKeys[`${preset.id}-accountId`]?.trim()) ||
(preset.type === 'deno' && !presetApiKeys[`${preset.id}-organizationId`]?.trim())
}
className="w-full"
>
{t('add')}
</Button>
</div>
)}
</CardContent>
@@ -759,11 +978,14 @@ export function DeploySettings() {
</Label>
<Select
value={customProviderType}
onValueChange={(value: 'shakespeare' | 'netlify' | 'vercel' | 'nsite') => {
onValueChange={(value: 'shakespeare' | 'netlify' | 'vercel' | 'nsite' | 'cloudflare' | 'deno') => {
setCustomProviderType(value);
// Reset form when provider type changes
setCustomApiKey('');
setCustomAccountId('');
setCustomOrganizationId('');
setCustomBaseURL('');
setCustomBaseDomain('');
setCustomHost('');
setCustomProxy(false);
setCustomGateway('');
@@ -779,6 +1001,8 @@ export function DeploySettings() {
<SelectItem value="nsite">nsite</SelectItem>
<SelectItem value="netlify">Netlify</SelectItem>
<SelectItem value="vercel">Vercel</SelectItem>
<SelectItem value="cloudflare">Cloudflare</SelectItem>
<SelectItem value="deno">Deno Deploy</SelectItem>
</SelectContent>
</Select>
</div>
@@ -847,9 +1071,38 @@ export function DeploySettings() {
</>
) : (
<>
{customProviderType === 'cloudflare' && (
<div className="grid gap-2">
<Label htmlFor="custom-accountid">
Account ID <span className="text-destructive">*</span>
</Label>
<Input
id="custom-accountid"
placeholder="Enter Account ID"
value={customAccountId}
onChange={(e) => setCustomAccountId(e.target.value)}
/>
</div>
)}
{customProviderType === 'deno' && (
<div className="grid gap-2">
<Label htmlFor="custom-organizationid">
Organization ID <span className="text-destructive">*</span>
</Label>
<Input
id="custom-organizationid"
placeholder="Enter Organization ID"
value={customOrganizationId}
onChange={(e) => setCustomOrganizationId(e.target.value)}
/>
</div>
)}
<div className="grid gap-2">
<Label htmlFor="custom-apikey">
{customProviderType === 'netlify' ? 'Personal Access Token' : 'Access Token'} <span className="text-destructive">*</span>
{customProviderType === 'netlify' ? 'Personal Access Token' :
customProviderType === 'cloudflare' ? 'API Token' :
customProviderType === 'deno' ? 'Access Token' :
'Access Token'} <span className="text-destructive">*</span>
</Label>
<PasswordInput
id="custom-apikey"
@@ -865,12 +1118,32 @@ export function DeploySettings() {
placeholder={
customProviderType === 'netlify'
? 'https://api.netlify.com/api/v1'
: 'https://api.vercel.com'
: customProviderType === 'vercel'
? 'https://api.vercel.com'
: customProviderType === 'deno'
? 'https://api.deno.com/v1'
: 'https://api.cloudflare.com/client/v4'
}
value={customBaseURL}
onChange={(e) => setCustomBaseURL(e.target.value)}
/>
</div>
{(customProviderType === 'cloudflare' || customProviderType === 'deno') && (
<div className="grid gap-2">
<Label htmlFor="custom-basedomain">Base Domain (Optional)</Label>
<Input
id="custom-basedomain"
placeholder={customProviderType === 'cloudflare' ? 'workers.dev' : 'deno.dev'}
value={customBaseDomain}
onChange={(e) => setCustomBaseDomain(e.target.value)}
/>
<p className="text-xs text-muted-foreground">
{customProviderType === 'cloudflare'
? 'The domain suffix for deployed workers (e.g., workers.dev)'
: 'The domain suffix for deployed projects (e.g., deno.dev)'}
</p>
</div>
)}
</>
)}
@@ -890,7 +1163,9 @@ export function DeploySettings() {
disabled={
!customProviderType ||
!customName.trim() ||
(customProviderType !== 'shakespeare' && customProviderType !== 'nsite' && !customApiKey.trim())
(customProviderType !== 'shakespeare' && customProviderType !== 'nsite' && !customApiKey.trim()) ||
(customProviderType === 'cloudflare' && !customAccountId.trim()) ||
(customProviderType === 'deno' && !customOrganizationId.trim())
}
className="gap-2 ml-auto"
>
+60 -47
View File
@@ -1,6 +1,6 @@
import { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Check, GitBranch, ArrowLeft, Trash2, ChevronDown, Plus, User } from 'lucide-react';
import { Check, GitBranch, ArrowLeft, Trash2, ChevronDown, Plus, User, ExternalLink } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
@@ -232,24 +232,13 @@ export function GitSettings() {
{availablePresets.map((preset) => (
<Card key={preset.id}>
<CardContent className="p-4 space-y-3">
<div className="flex items-center justify-between">
<div className="flex items-center gap-2">
<ExternalFavicon
url={preset.origin}
size={16}
fallback={<GitBranch size={16} />}
/>
<h5 className="font-medium">{preset.name}</h5>
</div>
{preset.tokenURL && (preset.id !== 'github' || !isOAuthConfigured) && (
<button
type="button"
className="text-xs text-muted-foreground underline hover:text-foreground"
onClick={() => window.open(preset.tokenURL, '_blank')}
>
{t('getToken')}
</button>
)}
<div className="flex items-center gap-2">
<ExternalFavicon
url={preset.origin}
size={16}
fallback={<GitBranch size={16} />}
/>
<h5 className="font-medium">{preset.name}</h5>
</div>
{preset.id === 'github' ? (
@@ -308,20 +297,32 @@ export function GitSettings() {
</div>
) : (
<div className="flex gap-2">
<PasswordInput
placeholder={t('enterToken')}
className="flex-1"
value={presetTokens[preset.id] || ''}
onChange={(e) => setPresetTokens(prev => ({
...prev,
[preset.id]: e.target.value,
}))}
onKeyDown={(e) => {
if (e.key === 'Enter' && presetTokens[preset.id]?.trim()) {
handleAddPresetProvider(preset);
}
}}
/>
<div className="relative flex-1">
<PasswordInput
placeholder={t('enterToken')}
value={presetTokens[preset.id] || ''}
onChange={(e) => setPresetTokens(prev => ({
...prev,
[preset.id]: e.target.value,
}))}
onKeyDown={(e) => {
if (e.key === 'Enter' && presetTokens[preset.id]?.trim()) {
handleAddPresetProvider(preset);
}
}}
showToggle={!!presetTokens[preset.id]}
/>
{preset.tokenURL && !presetTokens[preset.id] && (
<button
type="button"
className="absolute right-3 top-1/2 -translate-y-1/2 inline-flex items-center gap-1 px-2 py-1 text-xs font-medium text-muted-foreground hover:text-foreground transition-colors rounded-md hover:bg-muted"
onClick={() => window.open(preset.tokenURL, '_blank')}
>
Get Token
<ExternalLink className="h-3 w-3" />
</button>
)}
</div>
<Button
onClick={() => handleAddPresetProvider(preset)}
disabled={!presetTokens[preset.id]?.trim()}
@@ -334,20 +335,32 @@ export function GitSettings() {
) : (
// Standard rendering for other providers
<div className="flex gap-2">
<PasswordInput
placeholder={t('enterToken')}
className="flex-1"
value={presetTokens[preset.id] || ''}
onChange={(e) => setPresetTokens(prev => ({
...prev,
[preset.id]: e.target.value,
}))}
onKeyDown={(e) => {
if (e.key === 'Enter' && presetTokens[preset.id]?.trim()) {
handleAddPresetProvider(preset);
}
}}
/>
<div className="relative flex-1">
<PasswordInput
placeholder={t('enterToken')}
value={presetTokens[preset.id] || ''}
onChange={(e) => setPresetTokens(prev => ({
...prev,
[preset.id]: e.target.value,
}))}
onKeyDown={(e) => {
if (e.key === 'Enter' && presetTokens[preset.id]?.trim()) {
handleAddPresetProvider(preset);
}
}}
showToggle={!!presetTokens[preset.id]}
/>
{preset.tokenURL && !presetTokens[preset.id] && (
<button
type="button"
className="absolute right-3 top-1/2 -translate-y-1/2 inline-flex items-center gap-1 px-2 py-1 text-xs font-medium text-muted-foreground hover:text-foreground transition-colors rounded-md hover:bg-muted"
onClick={() => window.open(preset.tokenURL, '_blank')}
>
Get Token
<ExternalLink className="h-3 w-3" />
</button>
)}
</div>
<Button
onClick={() => handleAddPresetProvider(preset)}
disabled={!presetTokens[preset.id]?.trim()}
+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 ? (
+1 -65
View File
@@ -1,11 +1,10 @@
import { Settings, ArrowLeft, RefreshCw, Trash2, XCircle, Loader2, RotateCcw, Cog, Globe, Image, Code, Monitor, Award, Bug, FolderTree, Terminal as TerminalIcon, MessageCircle } from "lucide-react";
import { Settings, ArrowLeft, RefreshCw, Trash2, XCircle, Loader2, RotateCcw, Cog, Globe, Image, Code, Monitor, Award, Bug, FolderTree, Terminal as TerminalIcon } from "lucide-react";
import { useTranslation } from 'react-i18next';
import { useState, useEffect, useMemo } from "react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Switch } from "@/components/ui/switch";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { Accordion, AccordionContent, AccordionItem, AccordionTrigger } from '@/components/ui/accordion';
import { useIsMobile } from "@/hooks/useIsMobile";
import { useNavigate } from "react-router-dom";
@@ -14,11 +13,6 @@ import { useOffline } from "@/hooks/useOffline";
import { useToast } from "@/hooks/useToast";
import { Terminal } from "@/components/Terminal";
// Default system prompt for global chat
const DEFAULT_GLOBAL_CHAT_SYSTEM_PROMPT = `You are a helpful AI assistant. 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.`;
export function SystemSettings() {
const { t } = useTranslation();
const isMobile = useIsMobile();
@@ -38,9 +32,6 @@ export function SystemSettings() {
const [fsPathPluginsInput, setFsPathPluginsInput] = useState(config.fsPathPlugins);
const [fsPathTemplatesInput, setFsPathTemplatesInput] = useState(config.fsPathTemplates);
const [sentryDsnInput, setSentryDsnInput] = useState(config.sentryDsn);
const [chatSystemPromptInput, setChatSystemPromptInput] = useState(
config.globalChatSystemPrompt || DEFAULT_GLOBAL_CHAT_SYSTEM_PROMPT
);
// Check which settings differ from defaults
const isModified = useMemo(() => ({
@@ -56,7 +47,6 @@ export function SystemSettings() {
fsPathPlugins: config.fsPathPlugins !== defaultConfig.fsPathPlugins,
fsPathTemplates: config.fsPathTemplates !== defaultConfig.fsPathTemplates,
sentryDsn: config.sentryDsn !== defaultConfig.sentryDsn,
globalChatSystemPrompt: (config.globalChatSystemPrompt || DEFAULT_GLOBAL_CHAT_SYSTEM_PROMPT) !== DEFAULT_GLOBAL_CHAT_SYSTEM_PROMPT,
}), [config, defaultConfig]);
// Restore functions - clear the value from config to use the default
@@ -166,14 +156,6 @@ export function SystemSettings() {
});
};
const restoreChatSystemPrompt = () => {
setChatSystemPromptInput(DEFAULT_GLOBAL_CHAT_SYSTEM_PROMPT);
updateConfig((current) => {
const { globalChatSystemPrompt, ...rest } = current;
return rest;
});
};
// Service Worker state
const [swState, setSwState] = useState<string>('');
const [isUpdatingSW, setIsUpdatingSW] = useState(false);
@@ -970,52 +952,6 @@ export function SystemSettings() {
</AccordionItem>
</Accordion>
{/* Chat System Prompt Configuration */}
<Accordion type="single" collapsible className="w-full">
<AccordionItem value="chat-system-prompt">
<AccordionTrigger className="px-4 py-3 hover:no-underline">
<div className="flex items-center gap-2">
<MessageCircle className="h-4 w-4 text-muted-foreground" />
<h4 className="text-sm font-medium">{t('globalChatSystemPrompt')}</h4>
{isModified.globalChatSystemPrompt && (
<div className="h-2 w-2 rounded-full bg-yellow-500" title={t('modified')} />
)}
</div>
</AccordionTrigger>
<AccordionContent className="px-4 pb-4">
<div className="py-1 space-y-2">
<Textarea
placeholder="Enter system prompt..."
value={chatSystemPromptInput}
onChange={(e) => {
const value = e.target.value;
setChatSystemPromptInput(value);
updateConfig((current) => ({
...current,
globalChatSystemPrompt: value,
}));
}}
className="font-mono text-xs min-h-[150px]"
/>
{isModified.globalChatSystemPrompt && (
<Button
variant="outline"
size="sm"
onClick={restoreChatSystemPrompt}
className="w-full"
>
<RotateCcw className="h-4 w-4 mr-2" />
{t('restoreToDefault')}
</Button>
)}
<p className="text-xs text-muted-foreground">
{t('globalChatSystemPromptDescription')}
</p>
</div>
</AccordionContent>
</AccordionItem>
</Accordion>
{/* Terminal */}
<Accordion type="single" collapsible className="w-full">
<AccordionItem value="terminal">